Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

6080 行
174KB

  1. <?php
  2. /**
  3. * Friendica implementation of statusnet/twitter API
  4. *
  5. * @file include/api.php
  6. * @todo Automatically detect if incoming data is HTML or BBCode
  7. */
  8. use Friendica\App;
  9. use Friendica\Content\ContactSelector;
  10. use Friendica\Content\Feature;
  11. use Friendica\Content\Text\BBCode;
  12. use Friendica\Content\Text\HTML;
  13. use Friendica\Core\Authentication;
  14. use Friendica\Core\Config;
  15. use Friendica\Core\Hook;
  16. use Friendica\Core\L10n;
  17. use Friendica\Core\Logger;
  18. use Friendica\Core\NotificationsManager;
  19. use Friendica\Core\PConfig;
  20. use Friendica\Core\Protocol;
  21. use Friendica\Core\System;
  22. use Friendica\Core\Worker;
  23. use Friendica\Database\DBA;
  24. use Friendica\Model\Contact;
  25. use Friendica\Model\Group;
  26. use Friendica\Model\Item;
  27. use Friendica\Model\Mail;
  28. use Friendica\Model\Photo;
  29. use Friendica\Model\User;
  30. use Friendica\Network\FKOAuth1;
  31. use Friendica\Network\HTTPException;
  32. use Friendica\Network\HTTPException\BadRequestException;
  33. use Friendica\Network\HTTPException\ForbiddenException;
  34. use Friendica\Network\HTTPException\InternalServerErrorException;
  35. use Friendica\Network\HTTPException\MethodNotAllowedException;
  36. use Friendica\Network\HTTPException\NotFoundException;
  37. use Friendica\Network\HTTPException\NotImplementedException;
  38. use Friendica\Network\HTTPException\TooManyRequestsException;
  39. use Friendica\Network\HTTPException\UnauthorizedException;
  40. use Friendica\Object\Image;
  41. use Friendica\Protocol\Diaspora;
  42. use Friendica\Util\DateTimeFormat;
  43. use Friendica\Util\Network;
  44. use Friendica\Util\Proxy as ProxyUtils;
  45. use Friendica\Util\Strings;
  46. use Friendica\Util\XML;
  47. require_once 'mod/share.php';
  48. require_once 'mod/item.php';
  49. require_once 'mod/wall_upload.php';
  50. define('API_METHOD_ANY', '*');
  51. define('API_METHOD_GET', 'GET');
  52. define('API_METHOD_POST', 'POST,PUT');
  53. define('API_METHOD_DELETE', 'POST,DELETE');
  54. $API = [];
  55. $called_api = [];
  56. /**
  57. * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
  58. * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
  59. * into a page, and visitors will post something without noticing it).
  60. *
  61. * @brief Auth API user
  62. */
  63. function api_user()
  64. {
  65. if (!empty($_SESSION['allow_api'])) {
  66. return local_user();
  67. }
  68. return false;
  69. }
  70. /**
  71. * Clients can send 'source' parameter to be show in post metadata
  72. * as "sent via <source>".
  73. * Some clients doesn't send a source param, we support ones we know
  74. * (only Twidere, atm)
  75. *
  76. * @brief Get source name from API client
  77. *
  78. * @return string
  79. * Client source name, default to "api" if unset/unknown
  80. */
  81. function api_source()
  82. {
  83. if (requestdata('source')) {
  84. return requestdata('source');
  85. }
  86. // Support for known clients that doesn't send a source name
  87. if (!empty($_SERVER['HTTP_USER_AGENT'])) {
  88. if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
  89. return "Twidere";
  90. }
  91. Logger::log("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], Logger::DEBUG);
  92. } else {
  93. Logger::log("Empty user-agent", Logger::DEBUG);
  94. }
  95. return "api";
  96. }
  97. /**
  98. * @brief Format date for API
  99. *
  100. * @param string $str Source date, as UTC
  101. * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
  102. */
  103. function api_date($str)
  104. {
  105. // Wed May 23 06:01:13 +0000 2007
  106. return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
  107. }
  108. /**
  109. * Register a function to be the endpoint for defined API path.
  110. *
  111. * @brief Register API endpoint
  112. *
  113. * @param string $path API URL path, relative to System::baseUrl()
  114. * @param string $func Function name to call on path request
  115. * @param bool $auth API need logged user
  116. * @param string $method HTTP method reqiured to call this endpoint.
  117. * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
  118. * Default to API_METHOD_ANY
  119. */
  120. function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
  121. {
  122. global $API;
  123. $API[$path] = [
  124. 'func' => $func,
  125. 'auth' => $auth,
  126. 'method' => $method,
  127. ];
  128. // Workaround for hotot
  129. $path = str_replace("api/", "api/1.1/", $path);
  130. $API[$path] = [
  131. 'func' => $func,
  132. 'auth' => $auth,
  133. 'method' => $method,
  134. ];
  135. }
  136. /**
  137. * Log in user via OAuth1 or Simple HTTP Auth.
  138. * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
  139. *
  140. * @brief Login API user
  141. *
  142. * @param object $a App
  143. * @hook 'authenticate'
  144. * array $addon_auth
  145. * 'username' => username from login form
  146. * 'password' => password from login form
  147. * 'authenticated' => return status,
  148. * 'user_record' => return authenticated user record
  149. * @hook 'logged_in'
  150. * array $user logged user record
  151. */
  152. function api_login(App $a)
  153. {
  154. $oauth1 = new FKOAuth1();
  155. // login with oauth
  156. try {
  157. $request = OAuthRequest::from_request();
  158. list($consumer, $token) = $oauth1->verify_request($request);
  159. if (!is_null($token)) {
  160. $oauth1->loginUser($token->uid);
  161. Hook::callAll('logged_in', $a->user);
  162. return;
  163. }
  164. echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
  165. var_dump($consumer, $token);
  166. die();
  167. } catch (Exception $e) {
  168. $a->getLogger()->warning('API login: error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
  169. }
  170. // workaround for HTTP-auth in CGI mode
  171. if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
  172. $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
  173. if (strlen($userpass)) {
  174. list($name, $password) = explode(':', $userpass);
  175. $_SERVER['PHP_AUTH_USER'] = $name;
  176. $_SERVER['PHP_AUTH_PW'] = $password;
  177. }
  178. }
  179. if (empty($_SERVER['PHP_AUTH_USER'])) {
  180. $a->getLogger()->debug('API login: failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
  181. header('WWW-Authenticate: Basic realm="Friendica"');
  182. throw new UnauthorizedException("This API requires login");
  183. }
  184. $user = defaults($_SERVER, 'PHP_AUTH_USER', '');
  185. $password = defaults($_SERVER, 'PHP_AUTH_PW', '');
  186. // allow "user@server" login (but ignore 'server' part)
  187. $at = strstr($user, "@", true);
  188. if ($at) {
  189. $user = $at;
  190. }
  191. // next code from mod/auth.php. needs better solution
  192. $record = null;
  193. $addon_auth = [
  194. 'username' => trim($user),
  195. 'password' => trim($password),
  196. 'authenticated' => 0,
  197. 'user_record' => null,
  198. ];
  199. /*
  200. * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
  201. * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
  202. * and later addons should not interfere with an earlier one that succeeded.
  203. */
  204. Hook::callAll('authenticate', $addon_auth);
  205. if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
  206. $record = $addon_auth['user_record'];
  207. } else {
  208. $user_id = User::authenticate(trim($user), trim($password));
  209. if ($user_id !== false) {
  210. $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
  211. }
  212. }
  213. if (!DBA::isResult($record)) {
  214. $a->getLogger()->debug('API login: failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
  215. header('WWW-Authenticate: Basic realm="Friendica"');
  216. //header('HTTP/1.0 401 Unauthorized');
  217. //die('This api requires login');
  218. throw new UnauthorizedException("This API requires login");
  219. }
  220. Authentication::setAuthenticatedSessionForUser($record);
  221. $_SESSION["allow_api"] = true;
  222. Hook::callAll('logged_in', $a->user);
  223. }
  224. /**
  225. * API endpoints can define which HTTP method to accept when called.
  226. * This function check the current HTTP method agains endpoint
  227. * registered method.
  228. *
  229. * @brief Check HTTP method of called API
  230. *
  231. * @param string $method Required methods, uppercase, separated by comma
  232. * @return bool
  233. */
  234. function api_check_method($method)
  235. {
  236. if ($method == "*") {
  237. return true;
  238. }
  239. return (stripos($method, defaults($_SERVER, 'REQUEST_METHOD', 'GET')) !== false);
  240. }
  241. /**
  242. * Authenticate user, call registered API function, set HTTP headers
  243. *
  244. * @brief Main API entry point
  245. *
  246. * @param object $a App
  247. * @return string|array API call result
  248. */
  249. function api_call(App $a)
  250. {
  251. global $API, $called_api;
  252. $type = "json";
  253. if (strpos($a->query_string, ".xml") > 0) {
  254. $type = "xml";
  255. }
  256. if (strpos($a->query_string, ".json") > 0) {
  257. $type = "json";
  258. }
  259. if (strpos($a->query_string, ".rss") > 0) {
  260. $type = "rss";
  261. }
  262. if (strpos($a->query_string, ".atom") > 0) {
  263. $type = "atom";
  264. }
  265. try {
  266. foreach ($API as $p => $info) {
  267. if (strpos($a->query_string, $p) === 0) {
  268. if (!api_check_method($info['method'])) {
  269. throw new MethodNotAllowedException();
  270. }
  271. $called_api = explode("/", $p);
  272. //unset($_SERVER['PHP_AUTH_USER']);
  273. /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
  274. if (!empty($info['auth']) && api_user() === false) {
  275. api_login($a);
  276. }
  277. $a->getLogger()->info('API call', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
  278. $a->getLogger()->debug('API parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
  279. $stamp = microtime(true);
  280. $return = call_user_func($info['func'], $type);
  281. $duration = (float) (microtime(true) - $stamp);
  282. $a->getLogger()->info('API call', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
  283. if (Config::get("system", "profiler")) {
  284. $duration = microtime(true)-$a->performance["start"];
  285. /// @TODO round() really everywhere?
  286. $a->getLogger()->debug(
  287. 'API call performance',
  288. [
  289. 'module' => 'api',
  290. 'action' => 'performance',
  291. 'database_read' => round($a->performance["database"] - $a->performance["database_write"], 3),
  292. 'database_write' => round($a->performance["database_write"], 3),
  293. 'cache_read' => round($a->performance["cache"], 3),
  294. 'cache_write' => round($a->performance["cache_write"], 3),
  295. 'network_io' => round($a->performance["network"], 2),
  296. 'file_io' => round($a->performance["file"], 2),
  297. 'other_io' => round($duration - ($a->performance["database"]
  298. + $a->performance["cache"] + $a->performance["cache_write"]
  299. + $a->performance["network"] + $a->performance["file"]), 2),
  300. 'total' => round($duration, 2)
  301. ]
  302. );
  303. if (Config::get("rendertime", "callstack")) {
  304. $o = "Database Read:\n";
  305. foreach ($a->callstack["database"] as $func => $time) {
  306. $time = round($time, 3);
  307. if ($time > 0) {
  308. $o .= $func . ": " . $time . "\n";
  309. }
  310. }
  311. $o .= "\nDatabase Write:\n";
  312. foreach ($a->callstack["database_write"] as $func => $time) {
  313. $time = round($time, 3);
  314. if ($time > 0) {
  315. $o .= $func . ": " . $time . "\n";
  316. }
  317. }
  318. $o = "Cache Read:\n";
  319. foreach ($a->callstack["cache"] as $func => $time) {
  320. $time = round($time, 3);
  321. if ($time > 0) {
  322. $o .= $func . ": " . $time . "\n";
  323. }
  324. }
  325. $o .= "\nCache Write:\n";
  326. foreach ($a->callstack["cache_write"] as $func => $time) {
  327. $time = round($time, 3);
  328. if ($time > 0) {
  329. $o .= $func . ": " . $time . "\n";
  330. }
  331. }
  332. $o .= "\nNetwork:\n";
  333. foreach ($a->callstack["network"] as $func => $time) {
  334. $time = round($time, 3);
  335. if ($time > 0) {
  336. $o .= $func . ": " . $time . "\n";
  337. }
  338. }
  339. $a->getLogger()->debug($o, ['module' => 'api', 'action' => 'performance']);
  340. }
  341. }
  342. if (false === $return) {
  343. /*
  344. * api function returned false withour throw an
  345. * exception. This should not happend, throw a 500
  346. */
  347. throw new InternalServerErrorException();
  348. }
  349. switch ($type) {
  350. case "xml":
  351. header("Content-Type: text/xml");
  352. break;
  353. case "json":
  354. header("Content-Type: application/json");
  355. $json = json_encode(end($return));
  356. if (!empty($_GET['callback'])) {
  357. $json = $_GET['callback'] . "(" . $json . ")";
  358. }
  359. $return = $json;
  360. break;
  361. case "rss":
  362. header("Content-Type: application/rss+xml");
  363. $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
  364. break;
  365. case "atom":
  366. header("Content-Type: application/atom+xml");
  367. $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
  368. break;
  369. }
  370. return $return;
  371. }
  372. }
  373. $a->getLogger()->warning('API call not implemented');
  374. throw new NotImplementedException();
  375. } catch (HTTPException $e) {
  376. header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
  377. return api_error($type, $e);
  378. }
  379. }
  380. /**
  381. * @brief Format API error string
  382. *
  383. * @param string $type Return type (xml, json, rss, as)
  384. * @param object $e HTTPException Error object
  385. * @return string|array error message formatted as $type
  386. */
  387. function api_error($type, $e)
  388. {
  389. $a = \get_app();
  390. $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
  391. /// @TODO: https://dev.twitter.com/overview/api/response-codes
  392. $error = ["error" => $error,
  393. "code" => $e->httpcode . " " . $e->httpdesc,
  394. "request" => $a->query_string];
  395. $return = api_format_data('status', $type, ['status' => $error]);
  396. switch ($type) {
  397. case "xml":
  398. header("Content-Type: text/xml");
  399. break;
  400. case "json":
  401. header("Content-Type: application/json");
  402. $return = json_encode($return);
  403. break;
  404. case "rss":
  405. header("Content-Type: application/rss+xml");
  406. break;
  407. case "atom":
  408. header("Content-Type: application/atom+xml");
  409. break;
  410. }
  411. return $return;
  412. }
  413. /**
  414. * @brief Set values for RSS template
  415. *
  416. * @param App $a
  417. * @param array $arr Array to be passed to template
  418. * @param array $user_info User info
  419. * @return array
  420. * @todo find proper type-hints
  421. */
  422. function api_rss_extra(App $a, $arr, $user_info)
  423. {
  424. if (is_null($user_info)) {
  425. $user_info = api_get_user($a);
  426. }
  427. $arr['$user'] = $user_info;
  428. $arr['$rss'] = [
  429. 'alternate' => $user_info['url'],
  430. 'self' => System::baseUrl() . "/" . $a->query_string,
  431. 'base' => System::baseUrl(),
  432. 'updated' => api_date(null),
  433. 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
  434. 'language' => $user_info['lang'],
  435. 'logo' => System::baseUrl() . "/images/friendica-32.png",
  436. ];
  437. return $arr;
  438. }
  439. /**
  440. * @brief Unique contact to contact url.
  441. *
  442. * @param int $id Contact id
  443. * @return bool|string
  444. * Contact url or False if contact id is unknown
  445. */
  446. function api_unique_id_to_nurl($id)
  447. {
  448. $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
  449. if (DBA::isResult($r)) {
  450. return $r["nurl"];
  451. } else {
  452. return false;
  453. }
  454. }
  455. /**
  456. * @brief Get user info array.
  457. *
  458. * @param object $a App
  459. * @param int|string $contact_id Contact ID or URL
  460. */
  461. function api_get_user(App $a, $contact_id = null)
  462. {
  463. global $called_api;
  464. $user = null;
  465. $extra_query = "";
  466. $url = "";
  467. $a->getLogger()->info('api_get_user: Fetching user data', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
  468. // Searching for contact URL
  469. if (!is_null($contact_id) && (intval($contact_id) == 0)) {
  470. $user = DBA::escape(Strings::normaliseLink($contact_id));
  471. $url = $user;
  472. $extra_query = "AND `contact`.`nurl` = '%s' ";
  473. if (api_user() !== false) {
  474. $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
  475. }
  476. }
  477. // Searching for contact id with uid = 0
  478. if (!is_null($contact_id) && (intval($contact_id) != 0)) {
  479. $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
  480. if ($user == "") {
  481. throw new BadRequestException("User ID ".$contact_id." not found.");
  482. }
  483. $url = $user;
  484. $extra_query = "AND `contact`.`nurl` = '%s' ";
  485. if (api_user() !== false) {
  486. $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
  487. }
  488. }
  489. if (is_null($user) && !empty($_GET['user_id'])) {
  490. $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
  491. if ($user == "") {
  492. throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
  493. }
  494. $url = $user;
  495. $extra_query = "AND `contact`.`nurl` = '%s' ";
  496. if (api_user() !== false) {
  497. $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
  498. }
  499. }
  500. if (is_null($user) && !empty($_GET['screen_name'])) {
  501. $user = DBA::escape($_GET['screen_name']);
  502. $extra_query = "AND `contact`.`nick` = '%s' ";
  503. if (api_user() !== false) {
  504. $extra_query .= "AND `contact`.`uid`=".intval(api_user());
  505. }
  506. }
  507. if (is_null($user) && !empty($_GET['profileurl'])) {
  508. $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
  509. $extra_query = "AND `contact`.`nurl` = '%s' ";
  510. if (api_user() !== false) {
  511. $extra_query .= "AND `contact`.`uid`=".intval(api_user());
  512. }
  513. }
  514. // $called_api is the API path exploded on / and is expected to have at least 2 elements
  515. if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
  516. $argid = count($called_api);
  517. if (!empty($a->argv[$argid])) {
  518. $data = explode(".", $a->argv[$argid]);
  519. if (count($data) > 1) {
  520. list($user, $null) = $data;
  521. }
  522. }
  523. if (is_numeric($user)) {
  524. $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
  525. if ($user != "") {
  526. $url = $user;
  527. $extra_query = "AND `contact`.`nurl` = '%s' ";
  528. if (api_user() !== false) {
  529. $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
  530. }
  531. }
  532. } else {
  533. $user = DBA::escape($user);
  534. $extra_query = "AND `contact`.`nick` = '%s' ";
  535. if (api_user() !== false) {
  536. $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
  537. }
  538. }
  539. }
  540. $a->getLogger()->info('api_get_user: getting user', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
  541. if (!$user) {
  542. if (api_user() === false) {
  543. api_login($a);
  544. return false;
  545. } else {
  546. $user = $_SESSION['uid'];
  547. $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
  548. }
  549. }
  550. $a->getLogger()->info('api_get_user: found user', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
  551. // user info
  552. $uinfo = q(
  553. "SELECT *, `contact`.`id` AS `cid` FROM `contact`
  554. WHERE 1
  555. $extra_query",
  556. $user
  557. );
  558. // Selecting the id by priority, friendica first
  559. if (is_array($uinfo)) {
  560. api_best_nickname($uinfo);
  561. }
  562. // if the contact wasn't found, fetch it from the contacts with uid = 0
  563. if (!DBA::isResult($uinfo)) {
  564. if ($url == "") {
  565. throw new BadRequestException("User not found.");
  566. }
  567. $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
  568. if (DBA::isResult($contact)) {
  569. // If no nick where given, extract it from the address
  570. if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
  571. $contact['nick'] = api_get_nick($contact["url"]);
  572. }
  573. $ret = [
  574. 'id' => $contact["id"],
  575. 'id_str' => (string) $contact["id"],
  576. 'name' => $contact["name"],
  577. 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
  578. 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url']),
  579. 'description' => $contact["about"],
  580. 'profile_image_url' => $contact["micro"],
  581. 'profile_image_url_https' => $contact["micro"],
  582. 'profile_image_url_profile_size' => $contact["thumb"],
  583. 'profile_image_url_large' => $contact["photo"],
  584. 'url' => $contact["url"],
  585. 'protected' => false,
  586. 'followers_count' => 0,
  587. 'friends_count' => 0,
  588. 'listed_count' => 0,
  589. 'created_at' => api_date($contact["created"]),
  590. 'favourites_count' => 0,
  591. 'utc_offset' => 0,
  592. 'time_zone' => 'UTC',
  593. 'geo_enabled' => false,
  594. 'verified' => false,
  595. 'statuses_count' => 0,
  596. 'lang' => '',
  597. 'contributors_enabled' => false,
  598. 'is_translator' => false,
  599. 'is_translation_enabled' => false,
  600. 'following' => false,
  601. 'follow_request_sent' => false,
  602. 'statusnet_blocking' => false,
  603. 'notifications' => false,
  604. 'statusnet_profile_url' => $contact["url"],
  605. 'uid' => 0,
  606. 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
  607. 'pid' => Contact::getIdForURL($contact["url"], 0, true),
  608. 'self' => 0,
  609. 'network' => $contact["network"],
  610. ];
  611. return $ret;
  612. } else {
  613. throw new BadRequestException("User ".$url." not found.");
  614. }
  615. }
  616. if ($uinfo[0]['self']) {
  617. if ($uinfo[0]['network'] == "") {
  618. $uinfo[0]['network'] = Protocol::DFRN;
  619. }
  620. $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
  621. $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
  622. }
  623. $countitems = 0;
  624. $countfriends = 0;
  625. $countfollowers = 0;
  626. $starred = 0;
  627. // Add a nick if it isn't present there
  628. if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
  629. $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
  630. }
  631. $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
  632. if (!empty($profile['about'])) {
  633. $description = $profile['about'];
  634. } else {
  635. $description = $uinfo[0]["about"];
  636. }
  637. if (!empty($usr['default-location'])) {
  638. $location = $usr['default-location'];
  639. } elseif (!empty($uinfo[0]["location"])) {
  640. $location = $uinfo[0]["location"];
  641. } else {
  642. $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
  643. }
  644. $ret = [
  645. 'id' => intval($pcontact_id),
  646. 'id_str' => (string) intval($pcontact_id),
  647. 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
  648. 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
  649. 'location' => $location,
  650. 'description' => $description,
  651. 'profile_image_url' => $uinfo[0]['micro'],
  652. 'profile_image_url_https' => $uinfo[0]['micro'],
  653. 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
  654. 'profile_image_url_large' => $uinfo[0]["photo"],
  655. 'url' => $uinfo[0]['url'],
  656. 'protected' => false,
  657. 'followers_count' => intval($countfollowers),
  658. 'friends_count' => intval($countfriends),
  659. 'listed_count' => 0,
  660. 'created_at' => api_date($uinfo[0]['created']),
  661. 'favourites_count' => intval($starred),
  662. 'utc_offset' => "0",
  663. 'time_zone' => 'UTC',
  664. 'geo_enabled' => false,
  665. 'verified' => true,
  666. 'statuses_count' => intval($countitems),
  667. 'lang' => '',
  668. 'contributors_enabled' => false,
  669. 'is_translator' => false,
  670. 'is_translation_enabled' => false,
  671. 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
  672. 'follow_request_sent' => false,
  673. 'statusnet_blocking' => false,
  674. 'notifications' => false,
  675. /// @TODO old way?
  676. //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
  677. 'statusnet_profile_url' => $uinfo[0]['url'],
  678. 'uid' => intval($uinfo[0]['uid']),
  679. 'cid' => intval($uinfo[0]['cid']),
  680. 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
  681. 'self' => $uinfo[0]['self'],
  682. 'network' => $uinfo[0]['network'],
  683. ];
  684. // If this is a local user and it uses Frio, we can get its color preferences.
  685. if ($ret['self']) {
  686. $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
  687. if ($theme_info['theme'] === 'frio') {
  688. $schema = PConfig::get($ret['uid'], 'frio', 'schema');
  689. if ($schema && ($schema != '---')) {
  690. if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
  691. $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
  692. require_once $schemefile;
  693. }
  694. } else {
  695. $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
  696. $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
  697. $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
  698. }
  699. if (empty($nav_bg)) {
  700. $nav_bg = "#708fa0";
  701. }
  702. if (empty($link_color)) {
  703. $link_color = "#6fdbe8";
  704. }
  705. if (empty($bgcolor)) {
  706. $bgcolor = "#ededed";
  707. }
  708. $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
  709. $ret['profile_link_color'] = str_replace('#', '', $link_color);
  710. $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
  711. }
  712. }
  713. return $ret;
  714. }
  715. /**
  716. * @brief return api-formatted array for item's author and owner
  717. *
  718. * @param object $a App
  719. * @param array $item item from db
  720. * @return array(array:author, array:owner)
  721. */
  722. function api_item_get_user(App $a, $item)
  723. {
  724. $status_user = api_get_user($a, defaults($item, 'author-id', null));
  725. $status_user["protected"] = defaults($item, 'private', 0);
  726. if (defaults($item, 'thr-parent', '') == defaults($item, 'uri', '')) {
  727. $owner_user = api_get_user($a, defaults($item, 'owner-id', null));
  728. } else {
  729. $owner_user = $status_user;
  730. }
  731. return ([$status_user, $owner_user]);
  732. }
  733. /**
  734. * @brief walks recursively through an array with the possibility to change value and key
  735. *
  736. * @param array $array The array to walk through
  737. * @param string $callback The callback function
  738. *
  739. * @return array the transformed array
  740. */
  741. function api_walk_recursive(array &$array, callable $callback)
  742. {
  743. $new_array = [];
  744. foreach ($array as $k => $v) {
  745. if (is_array($v)) {
  746. if ($callback($v, $k)) {
  747. $new_array[$k] = api_walk_recursive($v, $callback);
  748. }
  749. } else {
  750. if ($callback($v, $k)) {
  751. $new_array[$k] = $v;
  752. }
  753. }
  754. }
  755. $array = $new_array;
  756. return $array;
  757. }
  758. /**
  759. * @brief Callback function to transform the array in an array that can be transformed in a XML file
  760. *
  761. * @param mixed $item Array item value
  762. * @param string $key Array key
  763. *
  764. * @return boolean Should the array item be deleted?
  765. */
  766. function api_reformat_xml(&$item, &$key)
  767. {
  768. if (is_bool($item)) {
  769. $item = ($item ? "true" : "false");
  770. }
  771. if (substr($key, 0, 10) == "statusnet_") {
  772. $key = "statusnet:".substr($key, 10);
  773. } elseif (substr($key, 0, 10) == "friendica_") {
  774. $key = "friendica:".substr($key, 10);
  775. }
  776. /// @TODO old-lost code?
  777. //else
  778. // $key = "default:".$key;
  779. return true;
  780. }
  781. /**
  782. * @brief Creates the XML from a JSON style array
  783. *
  784. * @param array $data JSON style array
  785. * @param string $root_element Name of the root element
  786. *
  787. * @return string The XML data
  788. */
  789. function api_create_xml(array $data, $root_element)
  790. {
  791. $childname = key($data);
  792. $data2 = array_pop($data);
  793. $namespaces = ["" => "http://api.twitter.com",
  794. "statusnet" => "http://status.net/schema/api/1/",
  795. "friendica" => "http://friendi.ca/schema/api/1/",
  796. "georss" => "http://www.georss.org/georss"];
  797. /// @todo Auto detection of needed namespaces
  798. if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
  799. $namespaces = [];
  800. }
  801. if (is_array($data2)) {
  802. $key = key($data2);
  803. api_walk_recursive($data2, "api_reformat_xml");
  804. if ($key == "0") {
  805. $data4 = [];
  806. $i = 1;
  807. foreach ($data2 as $item) {
  808. $data4[$i++ . ":" . $childname] = $item;
  809. }
  810. $data2 = $data4;
  811. }
  812. }
  813. $data3 = [$root_element => $data2];
  814. $ret = XML::fromArray($data3, $xml, false, $namespaces);
  815. return $ret;
  816. }
  817. /**
  818. * @brief Formats the data according to the data type
  819. *
  820. * @param string $root_element Name of the root element
  821. * @param string $type Return type (atom, rss, xml, json)
  822. * @param array $data JSON style array
  823. *
  824. * @return (string|array) XML data or JSON data
  825. */
  826. function api_format_data($root_element, $type, $data)
  827. {
  828. switch ($type) {
  829. case "atom":
  830. case "rss":
  831. case "xml":
  832. $ret = api_create_xml($data, $root_element);
  833. break;
  834. case "json":
  835. default:
  836. $ret = $data;
  837. break;
  838. }
  839. return $ret;
  840. }
  841. /**
  842. * TWITTER API
  843. */
  844. /**
  845. * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
  846. * returns a 401 status code and an error message if not.
  847. * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
  848. *
  849. * @param string $type Return type (atom, rss, xml, json)
  850. */
  851. function api_account_verify_credentials($type)
  852. {
  853. $a = \get_app();
  854. if (api_user() === false) {
  855. throw new ForbiddenException();
  856. }
  857. unset($_REQUEST["user_id"]);
  858. unset($_GET["user_id"]);
  859. unset($_REQUEST["screen_name"]);
  860. unset($_GET["screen_name"]);
  861. $skip_status = defaults($_REQUEST, 'skip_status', false);
  862. $user_info = api_get_user($a);
  863. // "verified" isn't used here in the standard
  864. unset($user_info["verified"]);
  865. // - Adding last status
  866. if (!$skip_status) {
  867. $user_info["status"] = api_status_show("raw");
  868. if (!count($user_info["status"])) {
  869. unset($user_info["status"]);
  870. } else {
  871. unset($user_info["status"]["user"]);
  872. }
  873. }
  874. // "uid" and "self" are only needed for some internal stuff, so remove it from here
  875. unset($user_info["uid"]);
  876. unset($user_info["self"]);
  877. return api_format_data("user", $type, ['user' => $user_info]);
  878. }
  879. /// @TODO move to top of file or somewhere better
  880. api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
  881. /**
  882. * Get data from $_POST or $_GET
  883. *
  884. * @param string $k
  885. */
  886. function requestdata($k)
  887. {
  888. if (!empty($_POST[$k])) {
  889. return $_POST[$k];
  890. }
  891. if (!empty($_GET[$k])) {
  892. return $_GET[$k];
  893. }
  894. return null;
  895. }
  896. /**
  897. * Deprecated function to upload media.
  898. *
  899. * @param string $type Return type (atom, rss, xml, json)
  900. *
  901. * @return array|string
  902. */
  903. function api_statuses_mediap($type)
  904. {
  905. $a = \get_app();
  906. if (api_user() === false) {
  907. Logger::log('api_statuses_update: no user');
  908. throw new ForbiddenException();
  909. }
  910. $user_info = api_get_user($a);
  911. $_REQUEST['profile_uid'] = api_user();
  912. $_REQUEST['api_source'] = true;
  913. $txt = requestdata('status');
  914. /// @TODO old-lost code?
  915. //$txt = urldecode(requestdata('status'));
  916. if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
  917. $txt = HTML::toBBCodeVideo($txt);
  918. $config = HTMLPurifier_Config::createDefault();
  919. $config->set('Cache.DefinitionImpl', null);
  920. $purifier = new HTMLPurifier($config);
  921. $txt = $purifier->purify($txt);
  922. }
  923. $txt = HTML::toBBCode($txt);
  924. $a->argv[1] = $user_info['screen_name']; //should be set to username?
  925. $picture = wall_upload_post($a, false);
  926. // now that we have the img url in bbcode we can add it to the status and insert the wall item.
  927. $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
  928. $item_id = item_post($a);
  929. // output the post that we just posted.
  930. return api_status_show($type, $item_id);
  931. }
  932. /// @TODO move this to top of file or somewhere better!
  933. api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
  934. /**
  935. * Updates the user’s current status.
  936. *
  937. * @param string $type Return type (atom, rss, xml, json)
  938. *
  939. * @return array|string
  940. * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
  941. */
  942. function api_statuses_update($type)
  943. {
  944. $a = \get_app();
  945. if (api_user() === false) {
  946. Logger::log('api_statuses_update: no user');
  947. throw new ForbiddenException();
  948. }
  949. api_get_user($a);
  950. // convert $_POST array items to the form we use for web posts.
  951. if (requestdata('htmlstatus')) {
  952. $txt = requestdata('htmlstatus');
  953. if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
  954. $txt = HTML::toBBCodeVideo($txt);
  955. $config = HTMLPurifier_Config::createDefault();
  956. $config->set('Cache.DefinitionImpl', null);
  957. $purifier = new HTMLPurifier($config);
  958. $txt = $purifier->purify($txt);
  959. $_REQUEST['body'] = HTML::toBBCode($txt);
  960. }
  961. } else {
  962. $_REQUEST['body'] = requestdata('status');
  963. }
  964. $_REQUEST['title'] = requestdata('title');
  965. $parent = requestdata('in_reply_to_status_id');
  966. // Twidere sends "-1" if it is no reply ...
  967. if ($parent == -1) {
  968. $parent = "";
  969. }
  970. if (ctype_digit($parent)) {
  971. $_REQUEST['parent'] = $parent;
  972. } else {
  973. $_REQUEST['parent_uri'] = $parent;
  974. }
  975. if (requestdata('lat') && requestdata('long')) {
  976. $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
  977. }
  978. $_REQUEST['profile_uid'] = api_user();
  979. if (!$parent) {
  980. // Check for throttling (maximum posts per day, week and month)
  981. $throttle_day = Config::get('system', 'throttle_limit_day');
  982. if ($throttle_day > 0) {
  983. $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
  984. $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
  985. $posts_day = DBA::count('thread', $condition);
  986. if ($posts_day > $throttle_day) {
  987. Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
  988. // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
  989. throw new TooManyRequestsException(L10n::tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
  990. }
  991. }
  992. $throttle_week = Config::get('system', 'throttle_limit_week');
  993. if ($throttle_week > 0) {
  994. $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
  995. $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
  996. $posts_week = DBA::count('thread', $condition);
  997. if ($posts_week > $throttle_week) {
  998. Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
  999. // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
  1000. throw new TooManyRequestsException(L10n::tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week));
  1001. }
  1002. }
  1003. $throttle_month = Config::get('system', 'throttle_limit_month');
  1004. if ($throttle_month > 0) {
  1005. $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
  1006. $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
  1007. $posts_month = DBA::count('thread', $condition);
  1008. if ($posts_month > $throttle_month) {
  1009. Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
  1010. // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
  1011. throw new TooManyRequestsException(L10n::t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
  1012. }
  1013. }
  1014. }
  1015. if (!empty($_FILES['media'])) {
  1016. // upload the image if we have one
  1017. $picture = wall_upload_post($a, false);
  1018. if (is_array($picture)) {
  1019. $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
  1020. }
  1021. }
  1022. // To-Do: Multiple IDs
  1023. if (requestdata('media_ids')) {
  1024. $r = q(
  1025. "SELECT `resource-id`, `scale`, `nickname`, `type` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1",
  1026. intval(requestdata('media_ids')),
  1027. api_user()
  1028. );
  1029. if (DBA::isResult($r)) {
  1030. $phototypes = Image::supportedTypes();
  1031. $ext = $phototypes[$r[0]['type']];
  1032. $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
  1033. $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
  1034. }
  1035. }
  1036. // set this so that the item_post() function is quiet and doesn't redirect or emit json
  1037. $_REQUEST['api_source'] = true;
  1038. if (empty($_REQUEST['source'])) {
  1039. $_REQUEST["source"] = api_source();
  1040. }
  1041. // call out normal post function
  1042. $item_id = item_post($a);
  1043. // output the post that we just posted.
  1044. return api_status_show($type, $item_id);
  1045. }
  1046. /// @TODO move to top of file or somewhere better
  1047. api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
  1048. api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
  1049. /**
  1050. * Uploads an image to Friendica.
  1051. *
  1052. * @return array
  1053. * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
  1054. */
  1055. function api_media_upload()
  1056. {
  1057. $a = \get_app();
  1058. if (api_user() === false) {
  1059. Logger::log('no user');
  1060. throw new ForbiddenException();
  1061. }
  1062. api_get_user($a);
  1063. if (empty($_FILES['media'])) {
  1064. // Output error
  1065. throw new BadRequestException("No media.");
  1066. }
  1067. $media = wall_upload_post($a, false);
  1068. if (!$media) {
  1069. // Output error
  1070. throw new InternalServerErrorException();
  1071. }
  1072. $returndata = [];
  1073. $returndata["media_id"] = $media["id"];
  1074. $returndata["media_id_string"] = (string)$media["id"];
  1075. $returndata["size"] = $media["size"];
  1076. $returndata["image"] = ["w" => $media["width"],
  1077. "h" => $media["height"],
  1078. "image_type" => $media["type"],
  1079. "friendica_preview_url" => $media["preview"]];
  1080. Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
  1081. return ["media" => $returndata];
  1082. }
  1083. /// @TODO move to top of file or somewhere better
  1084. api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
  1085. /**
  1086. *
  1087. * @param string $type Return type (atom, rss, xml, json)
  1088. *
  1089. * @return array|string
  1090. */
  1091. function api_status_show($type, $item_id = 0)
  1092. {
  1093. $a = \get_app();
  1094. $user_info = api_get_user($a);
  1095. Logger::log('api_status_show: user_info: '.print_r($user_info, true), Logger::DEBUG);
  1096. if ($type == "raw") {
  1097. $privacy_sql = "AND NOT `private`";
  1098. } else {
  1099. $privacy_sql = "";
  1100. }
  1101. if (!empty($item_id)) {
  1102. // Get the item with the given id
  1103. $condition = ['id' => $item_id];
  1104. } else {
  1105. // get last public wall message
  1106. $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
  1107. 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
  1108. }
  1109. $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
  1110. if (DBA::isResult($lastwall)) {
  1111. $in_reply_to = api_in_reply_to($lastwall);
  1112. $converted = api_convert_item($lastwall);
  1113. if ($type == "xml") {
  1114. $geo = "georss:point";
  1115. } else {
  1116. $geo = "geo";
  1117. }
  1118. $status_info = [
  1119. 'created_at' => api_date($lastwall['created']),
  1120. 'id' => intval($lastwall['id']),
  1121. 'id_str' => (string) $lastwall['id'],
  1122. 'text' => $converted["text"],
  1123. 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
  1124. 'truncated' => false,
  1125. 'in_reply_to_status_id' => $in_reply_to['status_id'],
  1126. 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
  1127. 'in_reply_to_user_id' => $in_reply_to['user_id'],
  1128. 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
  1129. 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
  1130. 'user' => $user_info,
  1131. $geo => null,
  1132. 'coordinates' => '',
  1133. 'place' => '',
  1134. 'contributors' => '',
  1135. 'is_quote_status' => false,
  1136. 'retweet_count' => 0,
  1137. 'favorite_count' => 0,
  1138. 'favorited' => $lastwall['starred'] ? true : false,
  1139. 'retweeted' => false,
  1140. 'possibly_sensitive' => false,
  1141. 'lang' => '',
  1142. 'statusnet_html' => $converted["html"],
  1143. 'statusnet_conversation_id' => $lastwall['parent'],
  1144. 'external_url' => System::baseUrl() . '/display/' . $lastwall['guid'],
  1145. ];
  1146. if (count($converted["attachments"]) > 0) {
  1147. $status_info["attachments"] = $converted["attachments"];
  1148. }
  1149. if (count($converted["entities"]) > 0) {
  1150. $status_info["entities"] = $converted["entities"];
  1151. }
  1152. if ($status_info["source"] == 'web') {
  1153. $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
  1154. } elseif (ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) != $status_info["source"]) {
  1155. $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']).')');
  1156. }
  1157. // "uid" and "self" are only needed for some internal stuff, so remove it from here
  1158. unset($status_info["user"]["uid"]);
  1159. unset($status_info["user"]["self"]);
  1160. Logger::log('status_info: '.print_r($status_info, true), Logger::DEBUG);
  1161. if ($type == "raw") {
  1162. return $status_info;
  1163. }
  1164. return api_format_data("statuses", $type, ['status' => $status_info]);
  1165. }
  1166. }
  1167. /**
  1168. * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
  1169. * The author's most recent status will be returned inline.
  1170. *
  1171. * @param string $type Return type (atom, rss, xml, json)
  1172. * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
  1173. */
  1174. function api_users_show($type)
  1175. {
  1176. $a = \get_app();
  1177. $user_info = api_get_user($a);
  1178. $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
  1179. 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'private' => false];
  1180. $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
  1181. if (DBA::isResult($lastwall)) {
  1182. $in_reply_to = api_in_reply_to($lastwall);
  1183. $converted = api_convert_item($lastwall);
  1184. if ($type == "xml") {
  1185. $geo = "georss:point";
  1186. } else {
  1187. $geo = "geo";
  1188. }
  1189. $user_info['status'] = [
  1190. 'text' => $converted["text"],
  1191. 'truncated' => false,
  1192. 'created_at' => api_date($lastwall['created']),
  1193. 'in_reply_to_status_id' => $in_reply_to['status_id'],
  1194. 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
  1195. 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
  1196. 'id' => intval($lastwall['contact-id']),
  1197. 'id_str' => (string) $lastwall['contact-id'],
  1198. 'in_reply_to_user_id' => $in_reply_to['user_id'],
  1199. 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
  1200. 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
  1201. $geo => null,
  1202. 'favorited' => $lastwall['starred'] ? true : false,
  1203. 'statusnet_html' => $converted["html"],
  1204. 'statusnet_conversation_id' => $lastwall['parent'],
  1205. 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
  1206. ];
  1207. if (count($converted["attachments"]) > 0) {
  1208. $user_info["status"]["attachments"] = $converted["attachments"];
  1209. }
  1210. if (count($converted["entities"]) > 0) {
  1211. $user_info["status"]["entities"] = $converted["entities"];
  1212. }
  1213. if ($user_info["status"]["source"] == 'web') {
  1214. $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
  1215. }
  1216. if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
  1217. $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) . ')');
  1218. }
  1219. }
  1220. // "uid" and "self" are only needed for some internal stuff, so remove it from here
  1221. unset($user_info["uid"]);
  1222. unset($user_info["self"]);
  1223. return api_format_data("user", $type, ['user' => $user_info]);
  1224. }
  1225. /// @TODO move to top of file or somewhere better
  1226. api_register_func('api/users/show', 'api_users_show');
  1227. api_register_func('api/externalprofile/show', 'api_users_show');
  1228. /**
  1229. * Search a public user account.
  1230. *
  1231. * @param string $type Return type (atom, rss, xml, json)
  1232. *
  1233. * @return array|string
  1234. * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
  1235. */
  1236. function api_users_search($type)
  1237. {
  1238. $a = \get_app();
  1239. $userlist = [];
  1240. if (!empty($_GET['q'])) {
  1241. $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
  1242. if (!DBA::isResult($r)) {
  1243. $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
  1244. }
  1245. if (DBA::isResult($r)) {
  1246. $k = 0;
  1247. foreach ($r as $user) {
  1248. $user_info = api_get_user($a, $user["id"]);
  1249. if ($type == "xml") {
  1250. $userlist[$k++.":user"] = $user_info;
  1251. } else {
  1252. $userlist[] = $user_info;
  1253. }
  1254. }
  1255. $userlist = ["users" => $userlist];
  1256. } else {
  1257. throw new BadRequestException("User ".$_GET["q"]." not found.");
  1258. }
  1259. } else {
  1260. throw new BadRequestException("No user specified.");
  1261. }
  1262. return api_format_data("users", $type, $userlist);
  1263. }
  1264. /// @TODO move to top of file or somewhere better
  1265. api_register_func('api/users/search', 'api_users_search');
  1266. /**
  1267. * Return user objects
  1268. *
  1269. * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
  1270. *
  1271. * @param string $type Return format: json or xml
  1272. *
  1273. * @return array|string
  1274. * @throws NotFoundException if the results are empty.
  1275. */
  1276. function api_users_lookup($type)
  1277. {
  1278. $users = [];
  1279. if (!empty($_REQUEST['user_id'])) {
  1280. foreach (explode(',', $_REQUEST['user_id']) as $id) {
  1281. if (!empty($id)) {
  1282. $users[] = api_get_user(get_app(), $id);
  1283. }
  1284. }
  1285. }
  1286. if (empty($users)) {
  1287. throw new NotFoundException;
  1288. }
  1289. return api_format_data("users", $type, ['users' => $users]);
  1290. }
  1291. /// @TODO move to top of file or somewhere better
  1292. api_register_func('api/users/lookup', 'api_users_lookup', true);
  1293. /**
  1294. * Returns statuses that match a specified query.
  1295. *
  1296. * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
  1297. *
  1298. * @param string $type Return format: json, xml, atom, rss
  1299. *
  1300. * @return array|string
  1301. * @throws BadRequestException if the "q" parameter is missing.
  1302. */
  1303. function api_search($type)
  1304. {
  1305. $a = \get_app();
  1306. $user_info = api_get_user($a);
  1307. if (api_user() === false || $user_info === false) { throw new ForbiddenException(); }
  1308. if (empty($_REQUEST['q'])) { throw new BadRequestException('q parameter is required.'); }
  1309. $searchTerm = trim(rawurldecode($_REQUEST['q']));
  1310. $data = [];
  1311. $data['status'] = [];
  1312. $count = 15;
  1313. $exclude_replies = !empty($_REQUEST['exclude_replies']);
  1314. if (!empty($_REQUEST['rpp'])) {
  1315. $count = $_REQUEST['rpp'];
  1316. } elseif (!empty($_REQUEST['count'])) {
  1317. $count = $_REQUEST['count'];
  1318. }
  1319. $since_id = defaults($_REQUEST, 'since_id', 0);
  1320. $max_id = defaults($_REQUEST, 'max_id', 0);
  1321. $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
  1322. $start = $page * $count;
  1323. $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
  1324. if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
  1325. $searchTerm = $matches[1];
  1326. $condition = ["`oid` > ?
  1327. AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
  1328. AND `otype` = ? AND `type` = ? AND `term` = ?",
  1329. $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
  1330. if ($max_id > 0) {
  1331. $condition[0] .= ' AND `oid` <= ?';
  1332. $condition[] = $max_id;
  1333. }
  1334. $terms = DBA::select('term', ['oid'], $condition, []);
  1335. $itemIds = [];
  1336. while ($term = DBA::fetch($terms)) {
  1337. $itemIds[] = $term['oid'];
  1338. }
  1339. DBA::close($terms);
  1340. if (empty($itemIds)) {
  1341. return api_format_data('statuses', $type, $data);
  1342. }
  1343. $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
  1344. if ($exclude_replies) {
  1345. $preCondition[] = '`id` = `parent`';
  1346. }
  1347. $condition = [implode(' AND ', $preCondition)];
  1348. } else {
  1349. $condition = ["`id` > ?
  1350. " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
  1351. AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
  1352. AND `body` LIKE CONCAT('%',?,'%')",
  1353. $since_id, api_user(), $_REQUEST['q']];
  1354. if ($max_id > 0) {
  1355. $condition[0] .= ' AND `id` <= ?';
  1356. $condition[] = $max_id;
  1357. }
  1358. }
  1359. $statuses = Item::selectForUser(api_user(), [], $condition, $params);
  1360. $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
  1361. bindComments($data['status']);
  1362. return api_format_data('statuses', $type, $data);
  1363. }
  1364. /// @TODO move to top of file or somewhere better
  1365. api_register_func('api/search/tweets', 'api_search', true);
  1366. api_register_func('api/search', 'api_search', true);
  1367. /**
  1368. * Returns the most recent statuses posted by the user and the users they follow.
  1369. *
  1370. * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
  1371. *
  1372. * @param string $type Return type (atom, rss, xml, json)
  1373. *
  1374. * @todo Optional parameters
  1375. * @todo Add reply info
  1376. */
  1377. function api_statuses_home_timeline($type)
  1378. {
  1379. $a = \get_app();
  1380. $user_info = api_get_user($a);
  1381. if (api_user() === false || $user_info === false) {
  1382. throw new ForbiddenException();
  1383. }
  1384. unset($_REQUEST["user_id"]);
  1385. unset($_GET["user_id"]);
  1386. unset($_REQUEST["screen_name"]);
  1387. unset($_GET["screen_name"]);
  1388. // get last network messages
  1389. // params
  1390. $count = defaults($_REQUEST, 'count', 20);
  1391. $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
  1392. if ($page < 0) {
  1393. $page = 0;
  1394. }
  1395. $since_id = defaults($_REQUEST, 'since_id', 0);
  1396. $max_id = defaults($_REQUEST, 'max_id', 0);
  1397. $exclude_replies = !empty($_REQUEST['exclude_replies']);
  1398. $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
  1399. $start = $page * $count;
  1400. $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
  1401. api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
  1402. if ($max_id > 0) {
  1403. $condition[0] .= " AND `item`.`id` <= ?";
  1404. $condition[] = $max_id;
  1405. }
  1406. if ($exclude_replies) {
  1407. $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
  1408. }
  1409. if ($conversation_id > 0) {
  1410. $condition[0] .= " AND `item`.`parent` = ?";
  1411. $condition[] = $conversation_id;
  1412. }
  1413. $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
  1414. $statuses = Item::selectForUser(api_user(), [], $condition, $params);
  1415. $items = Item::inArray($statuses);
  1416. $ret = api_format_items($items, $user_info, false, $type);
  1417. // Set all posts from the query above to seen
  1418. $idarray = [];
  1419. foreach ($items as $item) {
  1420. $idarray[] = intval($item["id"]);
  1421. }
  1422. if (!empty($idarray)) {
  1423. $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
  1424. if ($unseen) {
  1425. Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
  1426. }
  1427. }
  1428. bindComments($ret);
  1429. $data = ['status' => $ret];
  1430. switch ($type) {
  1431. case "atom":
  1432. break;
  1433. case "rss":
  1434. $data = api_rss_extra($a, $data, $user_info);
  1435. break;
  1436. }
  1437. return api_format_data("statuses", $type, $data);
  1438. }
  1439. /// @TODO move to top of file or somewhere better
  1440. api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
  1441. api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
  1442. /**
  1443. * Returns the most recent statuses from public users.
  1444. *
  1445. * @param string $type Return type (atom, rss, xml, json)
  1446. *
  1447. * @return array|string
  1448. */
  1449. function api_statuses_public_timeline($type)
  1450. {
  1451. $a = \get_app();
  1452. $user_info = api_get_user($a);
  1453. if (api_user() === false || $user_info === false) {
  1454. throw new ForbiddenException();
  1455. }
  1456. // get last network messages
  1457. // params
  1458. $count = defaults($_REQUEST, 'count', 20);
  1459. $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
  1460. if ($page < 0) {
  1461. $page = 0;
  1462. }
  1463. $since_id = defaults($_REQUEST, 'since_id', 0);
  1464. $max_id = defaults($_REQUEST, 'max_id', 0);
  1465. $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
  1466. $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
  1467. $start = $page * $count;
  1468. if ($exclude_replies && !$conversation_id) {
  1469. $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall`",
  1470. GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
  1471. if ($max_id > 0) {
  1472. $condition[0] .= " AND `thread`.`iid` <= ?";
  1473. $condition[] = $max_id;
  1474. }
  1475. $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
  1476. $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
  1477. $r = Item::inArray($statuses);
  1478. } else {
  1479. $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin`",
  1480. GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
  1481. if ($max_id > 0) {
  1482. $condition[0] .= " AND `item`.`id` <= ?";
  1483. $condition[] = $max_id;
  1484. }
  1485. if ($conversation_id > 0) {
  1486. $condition[0] .= " AND `item`.`parent` = ?";
  1487. $condition[] = $conversation_id;
  1488. }
  1489. $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
  1490. $statuses = Item::selectForUser(api_user(), [], $condition, $params);
  1491. $r = Item::inArray($statuses);
  1492. }
  1493. $ret = api_format_items($r, $user_info, false, $type);
  1494. bindComments($ret);
  1495. $data = ['status' => $ret];
  1496. switch ($type) {
  1497. case "atom":
  1498. break;
  1499. case "rss":
  1500. $data = api_rss_extra($a, $data, $user_info);
  1501. break;
  1502. }
  1503. return api_format_data("statuses", $type, $data);
  1504. }
  1505. /// @TODO move to top of file or somewhere better
  1506. api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
  1507. /**
  1508. * Returns the most recent statuses posted by users this node knows about.
  1509. *
  1510. * @brief Returns the list of public federated posts this node knows about
  1511. *
  1512. * @param string $type Return format: json, xml, atom, rss
  1513. * @return array|string
  1514. * @throws ForbiddenException
  1515. */
  1516. function api_statuses_networkpublic_timeline($type)
  1517. {
  1518. $a = \get_app();
  1519. $user_info = api_get_user($a);
  1520. if (api_user() === false || $user_info === false) {
  1521. throw new ForbiddenException();
  1522. }
  1523. $since_id = defaults($_REQUEST, 'since_id', 0);
  1524. $max_id = defaults($_REQUEST, 'max_id', 0);
  1525. // pagination
  1526. $count = defaults($_REQUEST, 'count', 20);
  1527. $page = defaults($_REQUEST, 'page', 1);
  1528. if ($page < 1) {
  1529. $page = 1;
  1530. }
  1531. $start = ($page - 1) * $count;
  1532. $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
  1533. GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
  1534. if ($max_id > 0) {
  1535. $condition[0] .= " AND `thread`.`iid` <= ?";
  1536. $condition[] = $max_id;
  1537. }
  1538. $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
  1539. $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
  1540. $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
  1541. bindComments($ret);
  1542. $data = ['status' => $ret];
  1543. switch ($type) {
  1544. case "atom":
  1545. break;
  1546. case "rss":
  1547. $data = api_rss_extra($a, $data, $user_info);
  1548. break;
  1549. }
  1550. return api_format_data("statuses", $type, $data);
  1551. }
  1552. /// @TODO move to top of file or somewhere better
  1553. api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
  1554. /**
  1555. * Returns a single status.
  1556. *
  1557. * @param string $type Return type (atom, rss, xml, json)
  1558. *
  1559. * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
  1560. */
  1561. function api_statuses_show($type)
  1562. {
  1563. $a = \get_app();
  1564. $user_info = api_get_user($a);
  1565. if (api_user() === false || $user_info === false) {
  1566. throw new ForbiddenException();
  1567. }
  1568. // params
  1569. $id = intval(defaults($a->argv, 3, 0));
  1570. if ($id == 0) {
  1571. $id = intval(defaults($_REQUEST, 'id', 0));
  1572. }
  1573. // Hotot workaround
  1574. if ($id == 0) {
  1575. $id = intval(defaults($a->argv, 4, 0));
  1576. }
  1577. Logger::log('API: api_statuses_show: ' . $id);
  1578. $conversation = !empty($_REQUEST['conversation']);
  1579. // try to fetch the item for the local user - or the public item, if there is no local one
  1580. $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
  1581. if (!DBA::isResult($uri_item)) {
  1582. throw new BadRequestException("There is no status with this id.");
  1583. }
  1584. $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
  1585. if (!DBA::isResult($item)) {
  1586. throw new BadRequestException("There is no status with this id.");
  1587. }
  1588. $id = $item['id'];
  1589. if ($conversation) {
  1590. $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
  1591. $params = ['order' => ['id' => true]];
  1592. } else {
  1593. $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
  1594. $params = [];
  1595. }
  1596. $statuses = Item::selectForUser(api_user(), [], $condition, $params);
  1597. /// @TODO How about copying this to above methods which don't check $r ?
  1598. if (!DBA::isResult($statuses)) {
  1599. throw new BadRequestException("There is no status with this id.");
  1600. }
  1601. $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
  1602. if ($conversation) {
  1603. $data = ['status' => $ret];
  1604. return api_format_data("statuses", $type, $data);
  1605. } else {
  1606. $data = ['status' => $ret[0]];
  1607. return api_format_data("status", $type, $data);
  1608. }
  1609. }
  1610. /// @TODO move to top of file or somewhere better
  1611. api_register_func('api/statuses/show', 'api_statuses_show', true);
  1612. /**
  1613. *
  1614. * @param string $type Return type (atom, rss, xml, json)
  1615. *
  1616. * @todo nothing to say?
  1617. */
  1618. function api_conversation_show($type)
  1619. {
  1620. $a = \get_app();
  1621. $user_info = api_get_user($a);
  1622. if (api_user() === false || $user_info === false) {
  1623. throw new ForbiddenException();
  1624. }
  1625. // params
  1626. $id = intval(defaults($a->argv , 3 , 0));
  1627. $since_id = intval(defaults($_REQUEST, 'since_id', 0));
  1628. $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
  1629. $count = intval(defaults($_REQUEST, 'count' , 20));
  1630. $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
  1631. if ($page < 0) {
  1632. $page = 0;
  1633. }
  1634. $start = $page * $count;
  1635. if ($id == 0) {
  1636. $id = intval(defaults($_REQUEST, 'id', 0));
  1637. }
  1638. // Hotot workaround
  1639. if ($id == 0) {
  1640. $id = intval(defaults($a->argv, 4, 0));
  1641. }
  1642. $a->getLogger()->info('API: api_conversation_show', ['module' => 'api', 'action' => 'conversation', 'id' => $id]);
  1643. // try to fetch the item for the local user - or the public item, if there is no local one
  1644. $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
  1645. if (!DBA::isResult($item)) {
  1646. throw new BadRequestException("There is no status with this id.");
  1647. }
  1648. $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
  1649. if (!DBA::isResult($parent)) {
  1650. throw new BadRequestException("There is no status with this id.");
  1651. }
  1652. $id = $parent['id'];
  1653. $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
  1654. $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
  1655. if ($max_id > 0) {
  1656. $condition[0] .= " AND `item`.`id` <= ?";
  1657. $condition[] = $max_id;
  1658. }
  1659. $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
  1660. $statuses = Item::selectForUser(api_user(), [], $condition, $params);
  1661. if (!DBA::isResult($statuses)) {
  1662. throw new BadRequestException("There is no status with id $id.");
  1663. }
  1664. $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
  1665. $data = ['status' => $ret];
  1666. return api_format_data("statuses", $type, $data);
  1667. }
  1668. /// @TODO move to top of file or somewhere better
  1669. api_register_func('api/conversation/show', 'api_conversation_show', true);
  1670. api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
  1671. /**
  1672. * Repeats a status.
  1673. *
  1674. * @param string $type Return type (atom, rss, xml, json)
  1675. *
  1676. * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
  1677. */
  1678. function api_statuses_repeat($type)
  1679. {
  1680. global $called_api;
  1681. $a = \get_app();
  1682. if (api_user() === false) {
  1683. throw new ForbiddenException();
  1684. }
  1685. api_get_user($a);
  1686. // params
  1687. $id = intval(defaults($a->argv, 3, 0));
  1688. if ($id == 0) {
  1689. $id = intval(defaults($_REQUEST, 'id', 0));
  1690. }
  1691. // Hotot workaround
  1692. if ($id == 0) {
  1693. $id = intval(defaults($a->argv, 4, 0));
  1694. }
  1695. Logger::log('API: api_statuses_repeat: '.$id);
  1696. $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
  1697. $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
  1698. if (DBA::isResult($item) && $item['body'] != "") {
  1699. if (strpos($item['body'], "[/share]") !== false) {
  1700. $pos = strpos($item['body'], "[share");
  1701. $post = substr($item['body'], $pos);
  1702. } else {
  1703. $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
  1704. $post .= $item['body'];
  1705. $post .= "[/share]";
  1706. }
  1707. $_REQUEST['body'] = $post;
  1708. $_REQUEST['profile_uid'] = api_user();
  1709. $_REQUEST['api_source'] = true;
  1710. if (empty($_REQUEST['source'])) {
  1711. $_REQUEST["source"] = api_source();
  1712. }
  1713. $item_id = item_post($a);
  1714. } else {
  1715. throw new ForbiddenException();
  1716. }
  1717. // output the post that we just posted.
  1718. $called_api = [];
  1719. return api_status_show($type, $item_id);
  1720. }
  1721. /// @TODO move to top of file or somewhere better
  1722. api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
  1723. /**
  1724. * Destroys a specific status.
  1725. *
  1726. * @param string $type Return type (atom, rss, xml, json)
  1727. *
  1728. * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
  1729. */
  1730. function api_statuses_destroy($type)
  1731. {
  1732. $a = \get_app();
  1733. if (api_user() === false) {
  1734. throw new ForbiddenException();
  1735. }
  1736. api_get_user($a);
  1737. // params
  1738. $id = intval(defaults($a->argv, 3, 0));
  1739. if ($id == 0) {
  1740. $id = intval(defaults($_REQUEST, 'id', 0));
  1741. }
  1742. // Hotot workaround
  1743. if ($id == 0) {
  1744. $id = intval(defaults($a->argv, 4, 0));
  1745. }
  1746. Logger::log('API: api_statuses_destroy: '.$id);
  1747. $ret = api_statuses_show($type);
  1748. Item::deleteForUser(['id' => $id], api_user());
  1749. return $ret;
  1750. }
  1751. /// @TODO move to top of file or somewhere better
  1752. api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
  1753. /**
  1754. * Returns the most recent mentions.
  1755. *
  1756. * @param string $type Return type (atom, rss, xml, json)
  1757. *
  1758. * @see http://developer.twitter.com/doc/get/statuses/mentions
  1759. */
  1760. function api_statuses_mentions($type)
  1761. {
  1762. $a = \get_app();
  1763. $user_info = api_get_user($a);
  1764. if (api_user() === false || $user_info === false) {
  1765. throw new ForbiddenException();
  1766. }
  1767. unset($_REQUEST["user_id"]);
  1768. unset($_GET["user_id"]);
  1769. unset($_REQUEST["screen_name"]);
  1770. unset($_GET["screen_name"]);
  1771. // get last network messages
  1772. // params
  1773. $since_id = defaults($_REQUEST, 'since_id', 0);
  1774. $max_id = defaults($_REQUEST, 'max_id' , 0);
  1775. $count = defaults($_REQUEST, 'count' , 20);
  1776. $page = defaults($_REQUEST, 'page' , 1);
  1777. if ($page < 1) {
  1778. $page = 1;
  1779. }
  1780. $start = ($page - 1) * $count;
  1781. $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
  1782. AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
  1783. api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
  1784. if ($max_id > 0) {
  1785. $condition[0] .= " AND `item`.`id` <= ?";
  1786. $condition[] = $max_id;
  1787. }
  1788. $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
  1789. $statuses = Item::selectForUser(api_user(), [], $condition, $params);
  1790. $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
  1791. $data = ['status' => $ret];
  1792. switch ($type) {
  1793. case "atom":
  1794. break;
  1795. case "rss":
  1796. $data = api_rss_extra($a, $data, $user_info);
  1797. break;
  1798. }
  1799. return api_format_data("statuses", $type, $data);
  1800. }
  1801. /// @TODO move to top of file or somewhere better
  1802. api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
  1803. api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
  1804. /**
  1805. * Returns the most recent statuses posted by the user.
  1806. *
  1807. * @brief Returns a user's public timeline
  1808. *
  1809. * @param string $type Either "json" or "xml"
  1810. * @return string|array
  1811. * @throws ForbiddenException
  1812. * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
  1813. */
  1814. function api_statuses_user_timeline($type)
  1815. {
  1816. $a = \get_app();
  1817. $user_info = api_get_user($a);
  1818. if (api_user() === false || $user_info === false) {
  1819. throw new ForbiddenException();
  1820. }
  1821. Logger::log(
  1822. "api_statuses_user_timeline: api_user: ". api_user() .
  1823. "\nuser_info: ".print_r($user_info, true) .
  1824. "\n_REQUEST: ".print_r($_REQUEST, true),
  1825. Logger::DEBUG
  1826. );
  1827. $since_id = defaults($_REQUEST, 'since_id', 0);
  1828. $max_id = defaults($_REQUEST, 'max_id', 0);
  1829. $exclude_replies = !empty($_REQUEST['exclude_replies']);
  1830. $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
  1831. // pagination
  1832. $count = defaults($_REQUEST, 'count', 20);
  1833. $page = defaults($_REQUEST, 'page', 1);
  1834. if ($page < 1) {
  1835. $page = 1;
  1836. }
  1837. $start = ($page - 1) * $count;
  1838. $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
  1839. api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
  1840. if ($user_info['self'] == 1) {
  1841. $condition[0] .= ' AND `item`.`wall` ';
  1842. }
  1843. if ($exclude_replies) {
  1844. $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
  1845. }
  1846. if ($conversation_id > 0) {
  1847. $condition[0] .= " AND `item`.`parent` = ?";
  1848. $condition[] = $conversation_id;
  1849. }
  1850. if ($max_id > 0) {
  1851. $condition[0] .= " AND `item`.`id` <= ?";
  1852. $condition[] = $max_id;
  1853. }
  1854. $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
  1855. $statuses = Item::selectForUser(api_user(), [], $condition, $params);
  1856. $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
  1857. bindComments($ret);
  1858. $data = ['status' => $ret];
  1859. switch ($type) {
  1860. case "atom":
  1861. break;
  1862. case "rss":
  1863. $data = api_rss_extra($a, $data, $user_info);
  1864. break;
  1865. }
  1866. return api_format_data("statuses", $type, $data);
  1867. }
  1868. /// @TODO move to top of file or somewhere better
  1869. api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
  1870. /**
  1871. * Star/unstar an item.
  1872. * param: id : id of the item
  1873. *
  1874. * @param string $type Return type (atom, rss, xml, json)
  1875. *
  1876. * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
  1877. */
  1878. function api_favorites_create_destroy($type)
  1879. {
  1880. $a = \get_app();
  1881. if (api_user() === false) {
  1882. throw new ForbiddenException();
  1883. }
  1884. // for versioned api.
  1885. /// @TODO We need a better global soluton
  1886. $action_argv_id = 2;
  1887. if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
  1888. $action_argv_id = 3;
  1889. }
  1890. if ($a->argc <= $action_argv_id) {
  1891. throw new BadRequestException("Invalid request.");
  1892. }
  1893. $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
  1894. if ($a->argc == $action_argv_id + 2) {
  1895. $itemid = intval(defaults($a->argv, $action_argv_id + 1, 0));
  1896. } else {
  1897. $itemid = intval(defaults($_REQUEST, 'id', 0));
  1898. }
  1899. $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
  1900. if (!DBA::isResult($item)) {
  1901. throw new BadRequestException("Invalid item.");
  1902. }
  1903. switch ($action) {
  1904. case "create":
  1905. $item['starred'] = 1;
  1906. break;
  1907. case "destroy":
  1908. $item['starred'] = 0;
  1909. break;
  1910. default:
  1911. throw new BadRequestException("Invalid action ".$action);
  1912. }
  1913. $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
  1914. if ($r === false) {
  1915. throw new InternalServerErrorException("DB error");
  1916. }
  1917. $user_info = api_get_user($a);
  1918. $rets = api_format_items([$item], $user_info, false, $type);
  1919. $ret = $rets[0];
  1920. $data = ['status' => $ret];
  1921. switch ($type) {
  1922. case "atom":
  1923. break;
  1924. case "rss":
  1925. $data = api_rss_extra($a, $data, $user_info);
  1926. break;
  1927. }
  1928. return api_format_data("status", $type, $data);
  1929. }
  1930. /// @TODO move to top of file or somewhere better
  1931. api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
  1932. api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
  1933. /**
  1934. * Returns the most recent favorite statuses.
  1935. *
  1936. * @param string $type Return type (atom, rss, xml, json)
  1937. *
  1938. * @return string|array
  1939. */
  1940. function api_favorites($type)
  1941. {
  1942. global $called_api;
  1943. $a = \get_app();
  1944. $user_info = api_get_user($a);
  1945. if (api_user() === false || $user_info === false) {
  1946. throw new ForbiddenException();
  1947. }
  1948. $called_api = [];
  1949. // in friendica starred item are private
  1950. // return favorites only for self
  1951. $a->getLogger()->info('API: api_favorites', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
  1952. if ($user_info['self'] == 0) {
  1953. $ret = [];
  1954. } else {
  1955. // params
  1956. $since_id = defaults($_REQUEST, 'since_id', 0);
  1957. $max_id = defaults($_REQUEST, 'max_id', 0);
  1958. $count = defaults($_GET, 'count', 20);
  1959. $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
  1960. if ($page < 0) {
  1961. $page = 0;
  1962. }
  1963. $start = $page*$count;
  1964. $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
  1965. api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
  1966. $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
  1967. if ($max_id > 0) {
  1968. $condition[0] .= " AND `item`.`id` <= ?";
  1969. $condition[] = $max_id;
  1970. }
  1971. $statuses = Item::selectForUser(api_user(), [], $condition, $params);
  1972. $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
  1973. }
  1974. bindComments($ret);
  1975. $data = ['status' => $ret];
  1976. switch ($type) {
  1977. case "atom":
  1978. break;
  1979. case "rss":
  1980. $data = api_rss_extra($a, $data, $user_info);
  1981. break;
  1982. }
  1983. return api_format_data("statuses", $type, $data);
  1984. }
  1985. /// @TODO move to top of file or somewhere better
  1986. api_register_func('api/favorites', 'api_favorites', true);
  1987. /**
  1988. *
  1989. * @param array $item
  1990. * @param array $recipient
  1991. * @param array $sender
  1992. *
  1993. * @return array
  1994. */
  1995. function api_format_messages($item, $recipient, $sender)
  1996. {
  1997. // standard meta information
  1998. $ret = [
  1999. 'id' => $item['id'],
  2000. 'sender_id' => $sender['id'],
  2001. 'text' => "",
  2002. 'recipient_id' => $recipient['id'],
  2003. 'created_at' => api_date(defaults($item, 'created', DateTimeFormat::utcNow())),
  2004. 'sender_screen_name' => $sender['screen_name'],
  2005. 'recipient_screen_name' => $recipient['screen_name'],
  2006. 'sender' => $sender,
  2007. 'recipient' => $recipient,
  2008. 'title' => "",
  2009. 'friendica_seen' => defaults($item, 'seen', 0),
  2010. 'friendica_parent_uri' => defaults($item, 'parent-uri', ''),
  2011. ];
  2012. // "uid" and "self" are only needed for some internal stuff, so remove it from here
  2013. if (isset($ret['sender']['uid'])) {
  2014. unset($ret['sender']['uid']);
  2015. }
  2016. if (isset($ret['sender']['self'])) {
  2017. unset($ret['sender']['self']);
  2018. }
  2019. if (isset($ret['recipient']['uid'])) {
  2020. unset($ret['recipient']['uid']);
  2021. }
  2022. if (isset($ret['recipient']['self'])) {
  2023. unset($ret['recipient']['self']);
  2024. }
  2025. //don't send title to regular StatusNET requests to avoid confusing these apps
  2026. if (!empty($_GET['getText'])) {
  2027. $ret['title'] = $item['title'];
  2028. if ($_GET['getText'] == 'html') {
  2029. $ret['text'] = BBCode::convert($item['body'], false);
  2030. } elseif ($_GET['getText'] == 'plain') {
  2031. $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
  2032. }
  2033. } else {
  2034. $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
  2035. }
  2036. if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
  2037. unset($ret['sender']);
  2038. unset($ret['recipient']);
  2039. }
  2040. return $ret;
  2041. }
  2042. /**
  2043. *
  2044. * @param array $item
  2045. *
  2046. * @return array
  2047. */
  2048. function api_convert_item($item)
  2049. {
  2050. $body = $item['body'];
  2051. $attachments = api_get_attachments($body);
  2052. // Workaround for ostatus messages where the title is identically to the body
  2053. $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
  2054. $statusbody = trim(HTML::toPlaintext($html, 0));
  2055. // handle data: images
  2056. $statusbody = api_format_items_embeded_images($item, $statusbody);
  2057. $statustitle = trim($item['title']);
  2058. if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
  2059. $statustext = trim($statusbody);
  2060. } else {
  2061. $statustext = trim($statustitle."\n\n".$statusbody);
  2062. }
  2063. if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($statustext)> 1000)) {
  2064. $statustext = substr($statustext, 0, 1000) . "... \n" . defaults($item, 'plink', '');
  2065. }
  2066. $statushtml = BBCode::convert(api_clean_attachments($body), false);
  2067. // Workaround for clients with limited HTML parser functionality
  2068. $search = ["<br>", "<blockquote>", "</blockquote>",
  2069. "<h1>", "</h1>", "<h2>", "</h2>",
  2070. "<h3>", "</h3>", "<h4>", "</h4>",
  2071. "<h5>", "</h5>", "<h6>", "</h6>"];
  2072. $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
  2073. "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
  2074. "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
  2075. "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
  2076. $statushtml = str_replace($search, $replace, $statushtml);
  2077. if ($item['title'] != "") {
  2078. $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
  2079. }
  2080. do {
  2081. $oldtext = $statushtml;
  2082. $statushtml = str_replace("<br><br>", "<br>", $statushtml);
  2083. } while ($oldtext != $statushtml);
  2084. if (substr($statushtml, 0, 4) == '<br>') {
  2085. $statushtml = substr($statushtml, 4);
  2086. }
  2087. if (substr($statushtml, 0, -4) == '<br>') {
  2088. $statushtml = substr($statushtml, -4);
  2089. }
  2090. // feeds without body should contain the link
  2091. if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
  2092. $statushtml .= BBCode::convert($item['plink']);
  2093. }
  2094. $entities = api_get_entitities($statustext, $body);
  2095. return [
  2096. "text" => $statustext,
  2097. "html" => $statushtml,
  2098. "attachments" => $attachments,
  2099. "entities" => $entities
  2100. ];
  2101. }
  2102. /**
  2103. *
  2104. * @param string $body
  2105. *
  2106. * @return array
  2107. */
  2108. function api_get_attachments(&$body)
  2109. {
  2110. $text = $body;
  2111. $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
  2112. $URLSearchString = "^\[\]";
  2113. $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
  2114. if (!$ret) {
  2115. return [];
  2116. }
  2117. $attachments = [];
  2118. foreach ($images[1] as $image) {
  2119. $imagedata = Image::getInfoFromURL($image);
  2120. if ($imagedata) {
  2121. $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
  2122. }
  2123. }
  2124. if (strstr(defaults($_SERVER, 'HTTP_USER_AGENT', ''), "AndStatus")) {
  2125. foreach ($images[0] as $orig) {
  2126. $body = str_replace($orig, "", $body);
  2127. }
  2128. }
  2129. return $attachments;
  2130. }
  2131. /**
  2132. *
  2133. * @param string $text
  2134. * @param string $bbcode
  2135. *
  2136. * @return array
  2137. * @todo Links at the first character of the post
  2138. */
  2139. function api_get_entitities(&$text, $bbcode)
  2140. {
  2141. $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
  2142. if ($include_entities != "true") {
  2143. preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
  2144. foreach ($images[1] as $image) {
  2145. $replace = ProxyUtils::proxifyUrl($image);
  2146. $text = str_replace($image, $replace, $text);
  2147. }
  2148. return [];
  2149. }
  2150. $bbcode = BBCode::cleanPictureLinks($bbcode);
  2151. // Change pure links in text to bbcode uris
  2152. $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
  2153. $entities = [];
  2154. $entities["hashtags"] = [];
  2155. $entities["symbols"] = [];
  2156. $entities["urls"] = [];
  2157. $entities["user_mentions"] = [];
  2158. $URLSearchString = "^\[\]";
  2159. $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
  2160. $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
  2161. //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
  2162. $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
  2163. $bbcode = preg_replace(
  2164. "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
  2165. '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
  2166. $bbcode
  2167. );
  2168. $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
  2169. $bbcode = preg_replace(
  2170. "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
  2171. '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
  2172. $bbcode
  2173. );
  2174. $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
  2175. $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
  2176. //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
  2177. preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
  2178. $ordered_urls = [];
  2179. foreach ($urls[1] as $id => $url) {
  2180. //$start = strpos($text, $url, $offset);
  2181. $start = iconv_strpos($text, $url, 0, "UTF-8");
  2182. if (!($start === false)) {
  2183. $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
  2184. }
  2185. }
  2186. ksort($ordered_urls);
  2187. $offset = 0;
  2188. //foreach ($urls[1] AS $id=>$url) {
  2189. foreach ($ordered_urls as $url) {
  2190. if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
  2191. && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
  2192. ) {
  2193. $display_url = $url["title"];
  2194. } else {
  2195. $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
  2196. $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
  2197. if (strlen($display_url) > 26) {
  2198. $display_url = substr($display_url, 0, 25)."…";
  2199. }
  2200. }
  2201. //$start = strpos($text, $url, $offset);
  2202. $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
  2203. if (!($start === false)) {
  2204. $entities["urls"][] = ["url" => $url["url"],
  2205. "expanded_url" => $url["url"],
  2206. "display_url" => $display_url,
  2207. "indices" => [$start, $start+strlen($url["url"])]];
  2208. $offset = $start + 1;
  2209. }
  2210. }
  2211. preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
  2212. $ordered_images = [];
  2213. foreach ($images[1] as $image) {
  2214. //$start = strpos($text, $url, $offset);
  2215. $start = iconv_strpos($text, $image, 0, "UTF-8");
  2216. if (!($start === false)) {
  2217. $ordered_images[$start] = $image;
  2218. }
  2219. }
  2220. //$entities["media"] = array();
  2221. $offset = 0;
  2222. foreach ($ordered_images as $url) {
  2223. $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
  2224. $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
  2225. if (strlen($display_url) > 26) {
  2226. $display_url = substr($display_url, 0, 25)."…";
  2227. }
  2228. $start = iconv_strpos($text, $url, $offset, "UTF-8");
  2229. if (!($start === false)) {
  2230. $image = Image::getInfoFromURL($url);
  2231. if ($image) {
  2232. // If image cache is activated, then use the following sizes:
  2233. // thumb (150), small (340), medium (600) and large (1024)
  2234. if (!Config::get("system", "proxy_disabled")) {
  2235. $media_url = ProxyUtils::proxifyUrl($url);
  2236. $sizes = [];
  2237. $scale = Image::getScalingDimensions($image[0], $image[1], 150);
  2238. $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
  2239. if (($image[0] > 150) || ($image[1] > 150)) {
  2240. $scale = Image::getScalingDimensions($image[0], $image[1], 340);
  2241. $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
  2242. }
  2243. $scale = Image::getScalingDimensions($image[0], $image[1], 600);
  2244. $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
  2245. if (($image[0] > 600) || ($image[1] > 600)) {
  2246. $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
  2247. $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
  2248. }
  2249. } else {
  2250. $media_url = $url;
  2251. $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
  2252. }
  2253. $entities["media"][] = [
  2254. "id" => $start+1,
  2255. "id_str" => (string)$start+1,
  2256. "indices" => [$start, $start+strlen($url)],
  2257. "media_url" => Strings::normaliseLink($media_url),
  2258. "media_url_https" => $media_url,
  2259. "url" => $url,
  2260. "display_url" => $display_url,
  2261. "expanded_url" => $url,
  2262. "type" => "photo",
  2263. "sizes" => $sizes];
  2264. }
  2265. $offset = $start + 1;
  2266. }
  2267. }
  2268. return $entities;
  2269. }
  2270. /**
  2271. *
  2272. * @param array $item
  2273. * @param string $text
  2274. *
  2275. * @return string
  2276. */
  2277. function api_format_items_embeded_images($item, $text)
  2278. {
  2279. $text = preg_replace_callback(
  2280. '|data:image/([^;]+)[^=]+=*|m',
  2281. function () use ($item) {
  2282. return System::baseUrl() . '/display/' . $item['guid'];
  2283. },
  2284. $text
  2285. );
  2286. return $text;
  2287. }
  2288. /**
  2289. * @brief return <a href='url'>name</a> as array
  2290. *
  2291. * @param string $txt text
  2292. * @return array
  2293. * 'name' => 'name',
  2294. * 'url => 'url'
  2295. */
  2296. function api_contactlink_to_array($txt)
  2297. {
  2298. $match = [];
  2299. $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
  2300. if ($r && count($match)==3) {
  2301. $res = [
  2302. 'name' => $match[2],
  2303. 'url' => $match[1]
  2304. ];
  2305. } else {
  2306. $res = [
  2307. 'name' => $txt,
  2308. 'url' => ""
  2309. ];
  2310. }
  2311. return $res;
  2312. }
  2313. /**
  2314. * @brief return likes, dislikes and attend status for item
  2315. *
  2316. * @param array $item array
  2317. * @param string $type Return type (atom, rss, xml, json)
  2318. *
  2319. * @return array
  2320. * likes => int count,
  2321. * dislikes => int count
  2322. */
  2323. function api_format_items_activities($item, $type = "json")
  2324. {
  2325. $a = \get_app();
  2326. $activities = [
  2327. 'like' => [],
  2328. 'dislike' => [],
  2329. 'attendyes' => [],
  2330. 'attendno' => [],
  2331. 'attendmaybe' => [],
  2332. ];
  2333. $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
  2334. $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
  2335. while ($parent_item = Item::fetch($ret)) {
  2336. // not used as result should be structured like other user data
  2337. //builtin_activity_puller($i, $activities);
  2338. // get user data and add it to the array of the activity
  2339. $user = api_get_user($a, $parent_item['author-id']);
  2340. switch ($parent_item['verb']) {
  2341. case ACTIVITY_LIKE:
  2342. $activities['like'][] = $user;
  2343. break;
  2344. case ACTIVITY_DISLIKE:
  2345. $activities['dislike'][] = $user;
  2346. break;
  2347. case ACTIVITY_ATTEND:
  2348. $activities['attendyes'][] = $user;
  2349. break;
  2350. case ACTIVITY_ATTENDNO:
  2351. $activities['attendno'][] = $user;
  2352. break;
  2353. case ACTIVITY_ATTENDMAYBE:
  2354. $activities['attendmaybe'][] = $user;
  2355. break;
  2356. default:
  2357. break;
  2358. }
  2359. }
  2360. DBA::close($ret);
  2361. if ($type == "xml") {
  2362. $xml_activities = [];
  2363. foreach ($activities as $k => $v) {
  2364. // change xml element from "like" to "friendica:like"
  2365. $xml_activities["friendica:".$k] = $v;
  2366. // add user data into xml output
  2367. $k_user = 0;
  2368. foreach ($v as $user) {
  2369. $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
  2370. }
  2371. }
  2372. $activities = $xml_activities;
  2373. }
  2374. return $activities;
  2375. }
  2376. /**
  2377. * @brief return data from profiles
  2378. *
  2379. * @param array $profile_row array containing data from db table 'profile'
  2380. * @return array
  2381. */
  2382. function api_format_items_profiles($profile_row)
  2383. {
  2384. $profile = [
  2385. 'profile_id' => $profile_row['id'],
  2386. 'profile_name' => $profile_row['profile-name'],
  2387. 'is_default' => $profile_row['is-default'] ? true : false,
  2388. 'hide_friends' => $profile_row['hide-friends'] ? true : false,
  2389. 'profile_photo' => $profile_row['photo'],
  2390. 'profile_thumb' => $profile_row['thumb'],
  2391. 'publish' => $profile_row['publish'] ? true : false,
  2392. 'net_publish' => $profile_row['net-publish'] ? true : false,
  2393. 'description' => $profile_row['pdesc'],
  2394. 'date_of_birth' => $profile_row['dob'],
  2395. 'address' => $profile_row['address'],
  2396. 'city' => $profile_row['locality'],
  2397. 'region' => $profile_row['region'],
  2398. 'postal_code' => $profile_row['postal-code'],
  2399. 'country' => $profile_row['country-name'],
  2400. 'hometown' => $profile_row['hometown'],
  2401. 'gender' => $profile_row['gender'],
  2402. 'marital' => $profile_row['marital'],
  2403. 'marital_with' => $profile_row['with'],
  2404. 'marital_since' => $profile_row['howlong'],
  2405. 'sexual' => $profile_row['sexual'],
  2406. 'politic' => $profile_row['politic'],
  2407. 'religion' => $profile_row['religion'],
  2408. 'public_keywords' => $profile_row['pub_keywords'],
  2409. 'private_keywords' => $profile_row['prv_keywords'],
  2410. 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
  2411. 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
  2412. 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
  2413. 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
  2414. 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
  2415. 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
  2416. 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
  2417. 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
  2418. 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
  2419. 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
  2420. 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
  2421. 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
  2422. 'homepage' => $profile_row['homepage'],
  2423. 'users' => null
  2424. ];
  2425. return $profile;
  2426. }
  2427. /**
  2428. * @brief format items to be returned by api
  2429. *
  2430. * @param array $r array of items
  2431. * @param array $user_info
  2432. * @param bool $filter_user filter items by $user_info
  2433. * @param string $type Return type (atom, rss, xml, json)
  2434. */
  2435. function api_format_items($r, $user_info, $filter_user = false, $type = "json")
  2436. {
  2437. $a = \get_app();
  2438. $ret = [];
  2439. foreach ((array)$r as $item) {
  2440. localize_item($item);
  2441. list($status_user, $owner_user) = api_item_get_user($a, $item);
  2442. // Look if the posts are matching if they should be filtered by user id
  2443. if ($filter_user && ($status_user["id"] != $user_info["id"])) {
  2444. continue;
  2445. }
  2446. $in_reply_to = api_in_reply_to($item);
  2447. $converted = api_convert_item($item);
  2448. if ($type == "xml") {
  2449. $geo = "georss:point";
  2450. } else {
  2451. $geo = "geo";
  2452. }
  2453. $status = [
  2454. 'text' => $converted["text"],
  2455. 'truncated' => false,
  2456. 'created_at'=> api_date($item['created']),
  2457. 'in_reply_to_status_id' => $in_reply_to['status_id'],
  2458. 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
  2459. 'source' => (($item['app']) ? $item['app'] : 'web'),
  2460. 'id' => intval($item['id']),
  2461. 'id_str' => (string) intval($item['id']),
  2462. 'in_reply_to_user_id' => $in_reply_to['user_id'],
  2463. 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
  2464. 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
  2465. $geo => null,
  2466. 'favorited' => $item['starred'] ? true : false,
  2467. 'user' => $status_user,
  2468. 'friendica_owner' => $owner_user,
  2469. 'friendica_private' => $item['private'] == 1,
  2470. //'entities' => NULL,
  2471. 'statusnet_html' => $converted["html"],
  2472. 'statusnet_conversation_id' => $item['parent'],
  2473. 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
  2474. 'friendica_activities' => api_format_items_activities($item, $type),
  2475. ];
  2476. if (count($converted["attachments"]) > 0) {
  2477. $status["attachments"] = $converted["attachments"];
  2478. }
  2479. if (count($converted["entities"]) > 0) {
  2480. $status["entities"] = $converted["entities"];
  2481. }
  2482. if ($status["source"] == 'web') {
  2483. $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
  2484. } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
  2485. $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
  2486. }
  2487. if ($item["id"] == $item["parent"]) {
  2488. $retweeted_item = api_share_as_retweet($item);
  2489. if ($retweeted_item !== false) {
  2490. $retweeted_status = $status;
  2491. $status['user'] = $status['friendica_owner'];
  2492. try {
  2493. $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
  2494. } catch (BadRequestException $e) {
  2495. // user not found. should be found?
  2496. /// @todo check if the user should be always found
  2497. $retweeted_status["user"] = [];
  2498. }
  2499. $rt_converted = api_convert_item($retweeted_item);
  2500. $retweeted_status['text'] = $rt_converted["text"];
  2501. $retweeted_status['statusnet_html'] = $rt_converted["html"];
  2502. $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
  2503. $retweeted_status['created_at'] = api_date($retweeted_item['created']);
  2504. $status['retweeted_status'] = $retweeted_status;
  2505. }
  2506. }
  2507. // "uid" and "self" are only needed for some internal stuff, so remove it from here
  2508. unset($status["user"]["uid"]);
  2509. unset($status["user"]["self"]);
  2510. if ($item["coord"] != "") {
  2511. $coords = explode(' ', $item["coord"]);
  2512. if (count($coords) == 2) {
  2513. if ($type == "json") {
  2514. $status["geo"] = ['type' => 'Point',
  2515. 'coordinates' => [(float) $coords[0],
  2516. (float) $coords[1]]];
  2517. } else {// Not sure if this is the official format - if someone founds a documentation we can check
  2518. $status["georss:point"] = $item["coord"];
  2519. }
  2520. }
  2521. }
  2522. $ret[] = $status;
  2523. };
  2524. return $ret;
  2525. }
  2526. /**
  2527. * Returns the remaining number of API requests available to the user before the API limit is reached.
  2528. *
  2529. * @param string $type Return type (atom, rss, xml, json)
  2530. *
  2531. * @return array|string
  2532. */
  2533. function api_account_rate_limit_status($type)
  2534. {
  2535. if ($type == "xml") {
  2536. $hash = [
  2537. 'remaining-hits' => '150',
  2538. '@attributes' => ["type" => "integer"],
  2539. 'hourly-limit' => '150',
  2540. '@attributes2' => ["type" => "integer"],
  2541. 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
  2542. '@attributes3' => ["type" => "datetime"],
  2543. 'reset_time_in_seconds' => strtotime('now + 1 hour'),
  2544. '@attributes4' => ["type" => "integer"],
  2545. ];
  2546. } else {
  2547. $hash = [
  2548. 'reset_time_in_seconds' => strtotime('now + 1 hour'),
  2549. 'remaining_hits' => '150',
  2550. 'hourly_limit' => '150',
  2551. 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
  2552. ];
  2553. }
  2554. return api_format_data('hash', $type, ['hash' => $hash]);
  2555. }
  2556. /// @TODO move to top of file or somewhere better
  2557. api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
  2558. /**
  2559. * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
  2560. *
  2561. * @param string $type Return type (atom, rss, xml, json)
  2562. *
  2563. * @return array|string
  2564. */
  2565. function api_help_test($type)
  2566. {
  2567. if ($type == 'xml') {
  2568. $ok = "true";
  2569. } else {
  2570. $ok = "ok";
  2571. }
  2572. return api_format_data('ok', $type, ["ok" => $ok]);
  2573. }
  2574. /// @TODO move to top of file or somewhere better
  2575. api_register_func('api/help/test', 'api_help_test', false);
  2576. /**
  2577. * Returns all lists the user subscribes to.
  2578. *
  2579. * @param string $type Return type (atom, rss, xml, json)
  2580. *
  2581. * @return array|string
  2582. * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
  2583. */
  2584. function api_lists_list($type)
  2585. {
  2586. $ret = [];
  2587. /// @TODO $ret is not filled here?
  2588. return api_format_data('lists', $type, ["lists_list" => $ret]);
  2589. }
  2590. /// @TODO move to top of file or somewhere better
  2591. api_register_func('api/lists/list', 'api_lists_list', true);
  2592. api_register_func('api/lists/subscriptions', 'api_lists_list', true);
  2593. /**
  2594. * Returns all groups the user owns.
  2595. *
  2596. * @param string $type Return type (atom, rss, xml, json)
  2597. *
  2598. * @return array|string
  2599. * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
  2600. */
  2601. function api_lists_ownerships($type)
  2602. {
  2603. $a = \get_app();
  2604. if (api_user() === false) {
  2605. throw new ForbiddenException();
  2606. }
  2607. // params
  2608. $user_info = api_get_user($a);
  2609. $uid = $user_info['uid'];
  2610. $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
  2611. // loop through all groups
  2612. $lists = [];
  2613. foreach ($groups as $group) {
  2614. if ($group['visible']) {
  2615. $mode = 'public';
  2616. } else {
  2617. $mode = 'private';
  2618. }
  2619. $lists[] = [
  2620. 'name' => $group['name'],
  2621. 'id' => intval($group['id']),
  2622. 'id_str' => (string) $group['id'],
  2623. 'user' => $user_info,
  2624. 'mode' => $mode
  2625. ];
  2626. }
  2627. return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
  2628. }
  2629. /// @TODO move to top of file or somewhere better
  2630. api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
  2631. /**
  2632. * Returns recent statuses from users in the specified group.
  2633. *
  2634. * @param string $type Return type (atom, rss, xml, json)
  2635. *
  2636. * @return array|string
  2637. * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
  2638. */
  2639. function api_lists_statuses($type)
  2640. {
  2641. $a = \get_app();
  2642. $user_info = api_get_user($a);
  2643. if (api_user() === false || $user_info === false) {
  2644. throw new ForbiddenException();
  2645. }
  2646. unset($_REQUEST["user_id"]);
  2647. unset($_GET["user_id"]);
  2648. unset($_REQUEST["screen_name"]);
  2649. unset($_GET["screen_name"]);
  2650. if (empty($_REQUEST['list_id'])) {
  2651. throw new BadRequestException('list_id not specified');
  2652. }
  2653. // params
  2654. $count = defaults($_REQUEST, 'count', 20);
  2655. $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
  2656. if ($page < 0) {
  2657. $page = 0;
  2658. }
  2659. $since_id = defaults($_REQUEST, 'since_id', 0);
  2660. $max_id = defaults($_REQUEST, 'max_id', 0);
  2661. $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
  2662. $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
  2663. $start = $page * $count;
  2664. $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
  2665. api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
  2666. if ($max_id > 0) {
  2667. $condition[0] .= " AND `item`.`id` <= ?";
  2668. $condition[] = $max_id;
  2669. }
  2670. if ($exclude_replies > 0) {
  2671. $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
  2672. }
  2673. if ($conversation_id > 0) {
  2674. $condition[0] .= " AND `item`.`parent` = ?";
  2675. $condition[] = $conversation_id;
  2676. }
  2677. $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
  2678. $statuses = Item::selectForUser(api_user(), [], $condition, $params);
  2679. $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
  2680. $data = ['status' => $items];
  2681. switch ($type) {
  2682. case "atom":
  2683. break;
  2684. case "rss":
  2685. $data = api_rss_extra($a, $data, $user_info);
  2686. break;
  2687. }
  2688. return api_format_data("statuses", $type, $data);
  2689. }
  2690. /// @TODO move to top of file or somewhere better
  2691. api_register_func('api/lists/statuses', 'api_lists_statuses', true);
  2692. /**
  2693. * Considers friends and followers lists to be private and won't return
  2694. * anything if any user_id parameter is passed.
  2695. *
  2696. * @brief Returns either the friends of the follower list
  2697. *
  2698. * @param string $qtype Either "friends" or "followers"
  2699. * @return boolean|array
  2700. * @throws ForbiddenException
  2701. */
  2702. function api_statuses_f($qtype)
  2703. {
  2704. $a = \get_app();
  2705. if (api_user() === false) {
  2706. throw new ForbiddenException();
  2707. }
  2708. // pagination
  2709. $count = defaults($_GET, 'count', 20);
  2710. $page = defaults($_GET, 'page', 1);
  2711. if ($page < 1) {
  2712. $page = 1;
  2713. }
  2714. $start = ($page - 1) * $count;
  2715. $user_info = api_get_user($a);
  2716. if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
  2717. /* this is to stop Hotot to load friends multiple times
  2718. * I'm not sure if I'm missing return something or
  2719. * is a bug in hotot. Workaround, meantime
  2720. */
  2721. /*$ret=Array();
  2722. return array('$users' => $ret);*/
  2723. return false;
  2724. }
  2725. $sql_extra = '';
  2726. if ($qtype == 'friends') {
  2727. $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
  2728. } elseif ($qtype == 'followers') {
  2729. $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
  2730. }
  2731. // friends and followers only for self
  2732. if ($user_info['self'] == 0) {
  2733. $sql_extra = " AND false ";
  2734. }
  2735. if ($qtype == 'blocks') {
  2736. $sql_filter = 'AND `blocked` AND NOT `pending`';
  2737. } elseif ($qtype == 'incoming') {
  2738. $sql_filter = 'AND `pending`';
  2739. } else {
  2740. $sql_filter = 'AND (NOT `blocked` OR `pending`)';
  2741. }
  2742. $r = q(
  2743. "SELECT `nurl`
  2744. FROM `contact`
  2745. WHERE `uid` = %d
  2746. AND NOT `self`
  2747. $sql_filter
  2748. $sql_extra
  2749. ORDER BY `nick`
  2750. LIMIT %d, %d",
  2751. intval(api_user()),
  2752. intval($start),
  2753. intval($count)
  2754. );
  2755. $ret = [];
  2756. foreach ($r as $cid) {
  2757. $user = api_get_user($a, $cid['nurl']);
  2758. // "uid" and "self" are only needed for some internal stuff, so remove it from here
  2759. unset($user["uid"]);
  2760. unset($user["self"]);
  2761. if ($user) {
  2762. $ret[] = $user;
  2763. }
  2764. }
  2765. return ['user' => $ret];
  2766. }
  2767. /**
  2768. * Returns the user's friends.
  2769. *
  2770. * @brief Returns the list of friends of the provided user
  2771. *
  2772. * @deprecated By Twitter API in favor of friends/list
  2773. *
  2774. * @param string $type Either "json" or "xml"
  2775. * @return boolean|string|array
  2776. */
  2777. function api_statuses_friends($type)
  2778. {
  2779. $data = api_statuses_f("friends");
  2780. if ($data === false) {
  2781. return false;
  2782. }
  2783. return api_format_data("users", $type, $data);
  2784. }
  2785. /**
  2786. * Returns the user's followers.
  2787. *
  2788. * @brief Returns the list of followers of the provided user
  2789. *
  2790. * @deprecated By Twitter API in favor of friends/list
  2791. *
  2792. * @param string $type Either "json" or "xml"
  2793. * @return boolean|string|array
  2794. */
  2795. function api_statuses_followers($type)
  2796. {
  2797. $data = api_statuses_f("followers");
  2798. if ($data === false) {
  2799. return false;
  2800. }
  2801. return api_format_data("users", $type, $data);
  2802. }
  2803. /// @TODO move to top of file or somewhere better
  2804. api_register_func('api/statuses/friends', 'api_statuses_friends', true);
  2805. api_register_func('api/statuses/followers', 'api_statuses_followers', true);
  2806. /**
  2807. * Returns the list of blocked users
  2808. *
  2809. * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
  2810. *
  2811. * @param string $type Either "json" or "xml"
  2812. *
  2813. * @return boolean|string|array
  2814. */
  2815. function api_blocks_list($type)
  2816. {
  2817. $data = api_statuses_f('blocks');
  2818. if ($data === false) {
  2819. return false;
  2820. }
  2821. return api_format_data("users", $type, $data);
  2822. }
  2823. /// @TODO move to top of file or somewhere better
  2824. api_register_func('api/blocks/list', 'api_blocks_list', true);
  2825. /**
  2826. * Returns the list of pending users IDs
  2827. *
  2828. * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
  2829. *
  2830. * @param string $type Either "json" or "xml"
  2831. *
  2832. * @return boolean|string|array
  2833. */
  2834. function api_friendships_incoming($type)
  2835. {
  2836. $data = api_statuses_f('incoming');
  2837. if ($data === false) {
  2838. return false;
  2839. }
  2840. $ids = [];
  2841. foreach ($data['user'] as $user) {
  2842. $ids[] = $user['id'];
  2843. }
  2844. return api_format_data("ids", $type, ['id' => $ids]);
  2845. }
  2846. /// @TODO move to top of file or somewhere better
  2847. api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
  2848. /**
  2849. * Returns the instance's configuration information.
  2850. *
  2851. * @param string $type Return type (atom, rss, xml, json)
  2852. *
  2853. * @return array|string
  2854. */
  2855. function api_statusnet_config($type)
  2856. {
  2857. $a = \get_app();
  2858. $name = Config::get('config', 'sitename');
  2859. $server = $a->getHostName();
  2860. $logo = System::baseUrl() . '/images/friendica-64.png';
  2861. $email = Config::get('config', 'admin_email');
  2862. $closed = intval(Config::get('config', 'register_policy')) === REGISTER_CLOSED ? 'true' : 'false';
  2863. $private = Config::get('system', 'block_public') ? 'true' : 'false';
  2864. $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
  2865. $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
  2866. $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
  2867. $config = [
  2868. 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
  2869. 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
  2870. 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
  2871. 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
  2872. 'shorturllength' => '30',
  2873. 'friendica' => [
  2874. 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
  2875. 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
  2876. 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
  2877. 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
  2878. ]
  2879. ],
  2880. ];
  2881. return api_format_data('config', $type, ['config' => $config]);
  2882. }
  2883. /// @TODO move to top of file or somewhere better
  2884. api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
  2885. api_register_func('api/statusnet/config', 'api_statusnet_config', false);
  2886. /**
  2887. *
  2888. * @param string $type Return type (atom, rss, xml, json)
  2889. *
  2890. * @return array|string
  2891. */
  2892. function api_statusnet_version($type)
  2893. {
  2894. // liar
  2895. $fake_statusnet_version = "0.9.7";
  2896. return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
  2897. }
  2898. /// @TODO move to top of file or somewhere better
  2899. api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
  2900. api_register_func('api/statusnet/version', 'api_statusnet_version', false);
  2901. /**
  2902. *
  2903. * @param string $type Return type (atom, rss, xml, json)
  2904. *
  2905. * @todo use api_format_data() to return data
  2906. */
  2907. function api_ff_ids($type)
  2908. {
  2909. if (!api_user()) {
  2910. throw new ForbiddenException();
  2911. }
  2912. $a = \get_app();
  2913. api_get_user($a);
  2914. $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
  2915. $r = q(
  2916. "SELECT `pcontact`.`id` FROM `contact`
  2917. INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
  2918. WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
  2919. intval(api_user())
  2920. );
  2921. if (!DBA::isResult($r)) {
  2922. return;
  2923. }
  2924. $ids = [];
  2925. foreach ($r as $rr) {
  2926. if ($stringify_ids) {
  2927. $ids[] = $rr['id'];
  2928. } else {
  2929. $ids[] = intval($rr['id']);
  2930. }
  2931. }
  2932. return api_format_data("ids", $type, ['id' => $ids]);
  2933. }
  2934. /**
  2935. * Returns the ID of every user the user is following.
  2936. *
  2937. * @param string $type Return type (atom, rss, xml, json)
  2938. *
  2939. * @return array|string
  2940. * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
  2941. */
  2942. function api_friends_ids($type)
  2943. {
  2944. return api_ff_ids($type);
  2945. }
  2946. /**
  2947. * Returns the ID of every user following the user.
  2948. *
  2949. * @param string $type Return type (atom, rss, xml, json)
  2950. *
  2951. * @return array|string
  2952. * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
  2953. */
  2954. function api_followers_ids($type)
  2955. {
  2956. return api_ff_ids($type);
  2957. }
  2958. /// @TODO move to top of file or somewhere better
  2959. api_register_func('api/friends/ids', 'api_friends_ids', true);
  2960. api_register_func('api/followers/ids', 'api_followers_ids', true);
  2961. /**
  2962. * Sends a new direct message.
  2963. *
  2964. * @param string $type Return type (atom, rss, xml, json)
  2965. *
  2966. * @return array|string
  2967. * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
  2968. */
  2969. function api_direct_messages_new($type)
  2970. {
  2971. $a = \get_app();
  2972. if (api_user() === false) {
  2973. throw new ForbiddenException();
  2974. }
  2975. if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
  2976. return;
  2977. }
  2978. $sender = api_get_user($a);
  2979. $recipient = null;
  2980. if (!empty($_POST['screen_name'])) {
  2981. $r = q(
  2982. "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
  2983. intval(api_user()),
  2984. DBA::escape($_POST['screen_name'])
  2985. );
  2986. if (DBA::isResult($r)) {
  2987. // Selecting the id by priority, friendica first
  2988. api_best_nickname($r);
  2989. $recipient = api_get_user($a, $r[0]['nurl']);
  2990. }
  2991. } else {
  2992. $recipient = api_get_user($a, $_POST['user_id']);
  2993. }
  2994. if (empty($recipient)) {
  2995. throw new NotFoundException('Recipient not found');
  2996. }
  2997. $replyto = '';
  2998. $sub = '';
  2999. if (!empty($_REQUEST['replyto'])) {
  3000. $r = q(
  3001. 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
  3002. intval(api_user()),
  3003. intval($_REQUEST['replyto'])
  3004. );
  3005. $replyto = $r[0]['parent-uri'];
  3006. $sub = $r[0]['title'];
  3007. } else {
  3008. if (!empty($_REQUEST['title'])) {
  3009. $sub = $_REQUEST['title'];
  3010. } else {
  3011. $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
  3012. }
  3013. }
  3014. $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
  3015. if ($id > -1) {
  3016. $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
  3017. $ret = api_format_messages($r[0], $recipient, $sender);
  3018. } else {
  3019. $ret = ["error"=>$id];
  3020. }
  3021. $data = ['direct_message'=>$ret];
  3022. switch ($type) {
  3023. case "atom":
  3024. break;
  3025. case "rss":
  3026. $data = api_rss_extra($a, $data, $sender);
  3027. break;
  3028. }
  3029. return api_format_data("direct-messages", $type, $data);
  3030. }
  3031. /// @TODO move to top of file or somewhere better
  3032. api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
  3033. /**
  3034. * Destroys a direct message.
  3035. *
  3036. * @brief delete a direct_message from mail table through api
  3037. *
  3038. * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  3039. * @return string|array
  3040. * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
  3041. */
  3042. function api_direct_messages_destroy($type)
  3043. {
  3044. $a = \get_app();
  3045. if (api_user() === false) {
  3046. throw new ForbiddenException();
  3047. }
  3048. // params
  3049. $user_info = api_get_user($a);
  3050. //required
  3051. $id = defaults($_REQUEST, 'id', 0);
  3052. // optional
  3053. $parenturi = defaults($_REQUEST, 'friendica_parenturi', "");
  3054. $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
  3055. /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
  3056. $uid = $user_info['uid'];
  3057. // error if no id or parenturi specified (for clients posting parent-uri as well)
  3058. if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
  3059. $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
  3060. return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
  3061. }
  3062. // BadRequestException if no id specified (for clients using Twitter API)
  3063. if ($id == 0) {
  3064. throw new BadRequestException('Message id not specified');
  3065. }
  3066. // add parent-uri to sql command if specified by calling app
  3067. $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
  3068. // get data of the specified message id
  3069. $r = q(
  3070. "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
  3071. intval($uid),
  3072. intval($id)
  3073. );
  3074. // error message if specified id is not in database
  3075. if (!DBA::isResult($r)) {
  3076. if ($verbose == "true") {
  3077. $answer = ['result' => 'error', 'message' => 'message id not in database'];
  3078. return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
  3079. }
  3080. /// @todo BadRequestException ok for Twitter API clients?
  3081. throw new BadRequestException('message id not in database');
  3082. }
  3083. // delete message
  3084. $result = q(
  3085. "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
  3086. intval($uid),
  3087. intval($id)
  3088. );
  3089. if ($verbose == "true") {
  3090. if ($result) {
  3091. // return success
  3092. $answer = ['result' => 'ok', 'message' => 'message deleted'];
  3093. return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
  3094. } else {
  3095. $answer = ['result' => 'error', 'message' => 'unknown error'];
  3096. return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
  3097. }
  3098. }
  3099. /// @todo return JSON data like Twitter API not yet implemented
  3100. }
  3101. /// @TODO move to top of file or somewhere better
  3102. api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
  3103. /**
  3104. * Unfollow Contact
  3105. *
  3106. * @brief unfollow contact
  3107. *
  3108. * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  3109. * @return string|array
  3110. * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
  3111. */
  3112. function api_friendships_destroy($type)
  3113. {
  3114. $uid = api_user();
  3115. $a = get_app();
  3116. if ($uid === false) {
  3117. throw new ForbiddenException();
  3118. }
  3119. $contact_id = defaults($_REQUEST, 'user_id');
  3120. if (empty($contact_id)) {
  3121. $a->getLogger()->notice('No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
  3122. throw new BadRequestException("no user_id specified");
  3123. }
  3124. // Get Contact by given id
  3125. $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
  3126. if(!DBA::isResult($contact)) {
  3127. $a->getLogger()->notice('No contact found for ID', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
  3128. throw new NotFoundException("no contact found to given ID");
  3129. }
  3130. $url = $contact["url"];
  3131. $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
  3132. $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
  3133. Strings::normaliseLink($url), $url];
  3134. $contact = DBA::selectFirst('contact', [], $condition);
  3135. if (!DBA::isResult($contact)) {
  3136. $a->getLogger()->notice('Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
  3137. throw new NotFoundException("Not following Contact");
  3138. }
  3139. if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
  3140. $a->getLogger()->notice('Not supported', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
  3141. throw new ExpectationFailedException("Not supported");
  3142. }
  3143. $dissolve = ($contact['rel'] == Contact::SHARING);
  3144. $owner = User::getOwnerDataById($uid);
  3145. if ($owner) {
  3146. Contact::terminateFriendship($owner, $contact, $dissolve);
  3147. }
  3148. else {
  3149. $a->getLogger()->notice('No owner found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
  3150. throw new NotFoundException("Error Processing Request");
  3151. }
  3152. // Sharing-only contacts get deleted as there no relationship any more
  3153. if ($dissolve) {
  3154. Contact::remove($contact['id']);
  3155. } else {
  3156. DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
  3157. }
  3158. // "uid" and "self" are only needed for some internal stuff, so remove it from here
  3159. unset($contact["uid"]);
  3160. unset($contact["self"]);
  3161. // Set screen_name since Twidere requests it
  3162. $contact["screen_name"] = $contact["nick"];
  3163. return api_format_data("friendships-destroy", $type, ['user' => $contact]);
  3164. }
  3165. api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
  3166. /**
  3167. *
  3168. * @param string $type Return type (atom, rss, xml, json)
  3169. * @param string $box
  3170. * @param string $verbose
  3171. *
  3172. * @return array|string
  3173. */
  3174. function api_direct_messages_box($type, $box, $verbose)
  3175. {
  3176. $a = \get_app();
  3177. if (api_user() === false) {
  3178. throw new ForbiddenException();
  3179. }
  3180. // params
  3181. $count = defaults($_GET, 'count', 20);
  3182. $page = defaults($_REQUEST, 'page', 1) - 1;
  3183. if ($page < 0) {
  3184. $page = 0;
  3185. }
  3186. $since_id = defaults($_REQUEST, 'since_id', 0);
  3187. $max_id = defaults($_REQUEST, 'max_id', 0);
  3188. $user_id = defaults($_REQUEST, 'user_id', '');
  3189. $screen_name = defaults($_REQUEST, 'screen_name', '');
  3190. // caller user info
  3191. unset($_REQUEST["user_id"]);
  3192. unset($_GET["user_id"]);
  3193. unset($_REQUEST["screen_name"]);
  3194. unset($_GET["screen_name"]);
  3195. $user_info = api_get_user($a);
  3196. if ($user_info === false) {
  3197. throw new ForbiddenException();
  3198. }
  3199. $profile_url = $user_info["url"];
  3200. // pagination
  3201. $start = $page * $count;
  3202. $sql_extra = "";
  3203. // filters
  3204. if ($box=="sentbox") {
  3205. $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
  3206. } elseif ($box == "conversation") {
  3207. $sql_extra = "`mail`.`parent-uri`='" . DBA::escape(defaults($_GET, 'uri', '')) . "'";
  3208. } elseif ($box == "all") {
  3209. $sql_extra = "true";
  3210. } elseif ($box == "inbox") {
  3211. $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
  3212. }
  3213. if ($max_id > 0) {
  3214. $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
  3215. }
  3216. if ($user_id != "") {
  3217. $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
  3218. } elseif ($screen_name !="") {
  3219. $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
  3220. }
  3221. $r = q(
  3222. "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND $sql_extra AND `mail`.`id` > %d ORDER BY `mail`.`id` DESC LIMIT %d,%d",
  3223. intval(api_user()),
  3224. intval($since_id),
  3225. intval($start),
  3226. intval($count)
  3227. );
  3228. if ($verbose == "true" && !DBA::isResult($r)) {
  3229. $answer = ['result' => 'error', 'message' => 'no mails available'];
  3230. return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
  3231. }
  3232. $ret = [];
  3233. foreach ($r as $item) {
  3234. if ($box == "inbox" || $item['from-url'] != $profile_url) {
  3235. $recipient = $user_info;
  3236. $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
  3237. } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
  3238. $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
  3239. $sender = $user_info;
  3240. }
  3241. if (isset($recipient) && isset($sender)) {
  3242. $ret[] = api_format_messages($item, $recipient, $sender);
  3243. }
  3244. }
  3245. $data = ['direct_message' => $ret];
  3246. switch ($type) {
  3247. case "atom":
  3248. break;
  3249. case "rss":
  3250. $data = api_rss_extra($a, $data, $user_info);
  3251. break;
  3252. }
  3253. return api_format_data("direct-messages", $type, $data);
  3254. }
  3255. /**
  3256. * Returns the most recent direct messages sent by the user.
  3257. *
  3258. * @param string $type Return type (atom, rss, xml, json)
  3259. *
  3260. * @return array|string
  3261. * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
  3262. */
  3263. function api_direct_messages_sentbox($type)
  3264. {
  3265. $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
  3266. return api_direct_messages_box($type, "sentbox", $verbose);
  3267. }
  3268. /**
  3269. * Returns the most recent direct messages sent to the user.
  3270. *
  3271. * @param string $type Return type (atom, rss, xml, json)
  3272. *
  3273. * @return array|string
  3274. * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
  3275. */
  3276. function api_direct_messages_inbox($type)
  3277. {
  3278. $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
  3279. return api_direct_messages_box($type, "inbox", $verbose);
  3280. }
  3281. /**
  3282. *
  3283. * @param string $type Return type (atom, rss, xml, json)
  3284. *
  3285. * @return array|string
  3286. */
  3287. function api_direct_messages_all($type)
  3288. {
  3289. $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
  3290. return api_direct_messages_box($type, "all", $verbose);
  3291. }
  3292. /**
  3293. *
  3294. * @param string $type Return type (atom, rss, xml, json)
  3295. *
  3296. * @return array|string
  3297. */
  3298. function api_direct_messages_conversation($type)
  3299. {
  3300. $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
  3301. return api_direct_messages_box($type, "conversation", $verbose);
  3302. }
  3303. /// @TODO move to top of file or somewhere better
  3304. api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
  3305. api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
  3306. api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
  3307. api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
  3308. /**
  3309. * Returns an OAuth Request Token.
  3310. *
  3311. * @see https://oauth.net/core/1.0/#auth_step1
  3312. */
  3313. function api_oauth_request_token()
  3314. {
  3315. $oauth1 = new FKOAuth1();
  3316. try {
  3317. $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
  3318. } catch (Exception $e) {
  3319. echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
  3320. exit();
  3321. }
  3322. echo $r;
  3323. exit();
  3324. }
  3325. /**
  3326. * Returns an OAuth Access Token.
  3327. *
  3328. * @return array|string
  3329. * @see https://oauth.net/core/1.0/#auth_step3
  3330. */
  3331. function api_oauth_access_token()
  3332. {
  3333. $oauth1 = new FKOAuth1();
  3334. try {
  3335. $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
  3336. } catch (Exception $e) {
  3337. echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
  3338. exit();
  3339. }
  3340. echo $r;
  3341. exit();
  3342. }
  3343. /// @TODO move to top of file or somewhere better
  3344. api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
  3345. api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
  3346. /**
  3347. * @brief delete a complete photoalbum with all containing photos from database through api
  3348. *
  3349. * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  3350. * @return string|array
  3351. */
  3352. function api_fr_photoalbum_delete($type)
  3353. {
  3354. if (api_user() === false) {
  3355. throw new ForbiddenException();
  3356. }
  3357. // input params
  3358. $album = defaults($_REQUEST, 'album', "");
  3359. // we do not allow calls without album string
  3360. if ($album == "") {
  3361. throw new BadRequestException("no albumname specified");
  3362. }
  3363. // check if album is existing
  3364. $r = q(
  3365. "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
  3366. intval(api_user()),
  3367. DBA::escape($album)
  3368. );
  3369. if (!DBA::isResult($r)) {
  3370. throw new BadRequestException("album not available");
  3371. }
  3372. // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
  3373. // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
  3374. foreach ($r as $rr) {
  3375. $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
  3376. $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
  3377. if (!DBA::isResult($photo_item)) {
  3378. throw new InternalServerErrorException("problem with deleting items occured");
  3379. }
  3380. Item::deleteForUser(['id' => $photo_item['id']], api_user());
  3381. }
  3382. // now let's delete all photos from the album
  3383. $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
  3384. // return success of deletion or error message
  3385. if ($result) {
  3386. $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
  3387. return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
  3388. } else {
  3389. throw new InternalServerErrorException("unknown error - deleting from database failed");
  3390. }
  3391. }
  3392. /**
  3393. * @brief update the name of the album for all photos of an album
  3394. *
  3395. * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  3396. * @return string|array
  3397. */
  3398. function api_fr_photoalbum_update($type)
  3399. {
  3400. if (api_user() === false) {
  3401. throw new ForbiddenException();
  3402. }
  3403. // input params
  3404. $album = defaults($_REQUEST, 'album', "");
  3405. $album_new = defaults($_REQUEST, 'album_new', "");
  3406. // we do not allow calls without album string
  3407. if ($album == "") {
  3408. throw new BadRequestException("no albumname specified");
  3409. }
  3410. if ($album_new == "") {
  3411. throw new BadRequestException("no new albumname specified");
  3412. }
  3413. // check if album is existing
  3414. if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
  3415. throw new BadRequestException("album not available");
  3416. }
  3417. // now let's update all photos to the albumname
  3418. $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
  3419. // return success of updating or error message
  3420. if ($result) {
  3421. $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
  3422. return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
  3423. } else {
  3424. throw new InternalServerErrorException("unknown error - updating in database failed");
  3425. }
  3426. }
  3427. /**
  3428. * @brief list all photos of the authenticated user
  3429. *
  3430. * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  3431. * @return string|array
  3432. */
  3433. function api_fr_photos_list($type)
  3434. {
  3435. if (api_user() === false) {
  3436. throw new ForbiddenException();
  3437. }
  3438. $r = q(
  3439. "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
  3440. MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
  3441. WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
  3442. intval(local_user())
  3443. );
  3444. $typetoext = [
  3445. 'image/jpeg' => 'jpg',
  3446. 'image/png' => 'png',
  3447. 'image/gif' => 'gif'
  3448. ];
  3449. $data = ['photo'=>[]];
  3450. if (DBA::isResult($r)) {
  3451. foreach ($r as $rr) {
  3452. $photo = [];
  3453. $photo['id'] = $rr['resource-id'];
  3454. $photo['album'] = $rr['album'];
  3455. $photo['filename'] = $rr['filename'];
  3456. $photo['type'] = $rr['type'];
  3457. $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
  3458. $photo['created'] = $rr['created'];
  3459. $photo['edited'] = $rr['edited'];
  3460. $photo['desc'] = $rr['desc'];
  3461. if ($type == "xml") {
  3462. $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
  3463. } else {
  3464. $photo['thumb'] = $thumb;
  3465. $data['photo'][] = $photo;
  3466. }
  3467. }
  3468. }
  3469. return api_format_data("photos", $type, $data);
  3470. }
  3471. /**
  3472. * @brief upload a new photo or change an existing photo
  3473. *
  3474. * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  3475. * @return string|array
  3476. */
  3477. function api_fr_photo_create_update($type)
  3478. {
  3479. if (api_user() === false) {
  3480. throw new ForbiddenException();
  3481. }
  3482. // input params
  3483. $photo_id = defaults($_REQUEST, 'photo_id', null);
  3484. $desc = defaults($_REQUEST, 'desc', (array_key_exists('desc', $_REQUEST) ? "" : null)) ; // extra check necessary to distinguish between 'not provided' and 'empty string'
  3485. $album = defaults($_REQUEST, 'album', null);
  3486. $album_new = defaults($_REQUEST, 'album_new', null);
  3487. $allow_cid = defaults($_REQUEST, 'allow_cid', (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
  3488. $deny_cid = defaults($_REQUEST, 'deny_cid' , (array_key_exists('deny_cid' , $_REQUEST) ? " " : null));
  3489. $allow_gid = defaults($_REQUEST, 'allow_gid', (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
  3490. $deny_gid = defaults($_REQUEST, 'deny_gid' , (array_key_exists('deny_gid' , $_REQUEST) ? " " : null));
  3491. $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
  3492. // do several checks on input parameters
  3493. // we do not allow calls without album string
  3494. if ($album == null) {
  3495. throw new BadRequestException("no albumname specified");
  3496. }
  3497. // if photo_id == null --> we are uploading a new photo
  3498. if ($photo_id == null) {
  3499. $mode = "create";
  3500. // error if no media posted in create-mode
  3501. if (empty($_FILES['media'])) {
  3502. // Output error
  3503. throw new BadRequestException("no media data submitted");
  3504. }
  3505. // album_new will be ignored in create-mode
  3506. $album_new = "";
  3507. } else {
  3508. $mode = "update";
  3509. // check if photo is existing in databasei
  3510. if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
  3511. throw new BadRequestException("photo not available");
  3512. }
  3513. }
  3514. // checks on acl strings provided by clients
  3515. $acl_input_error = false;
  3516. $acl_input_error |= check_acl_input($allow_cid);
  3517. $acl_input_error |= check_acl_input($deny_cid);
  3518. $acl_input_error |= check_acl_input($allow_gid);
  3519. $acl_input_error |= check_acl_input($deny_gid);
  3520. if ($acl_input_error) {
  3521. throw new BadRequestException("acl data invalid");
  3522. }
  3523. // now let's upload the new media in create-mode
  3524. if ($mode == "create") {
  3525. $media = $_FILES['media'];
  3526. $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
  3527. // return success of updating or error message
  3528. if (!is_null($data)) {
  3529. return api_format_data("photo_create", $type, $data);
  3530. } else {
  3531. throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
  3532. }
  3533. }
  3534. // now let's do the changes in update-mode
  3535. if ($mode == "update") {
  3536. $updated_fields = [];
  3537. if (!is_null($desc)) {
  3538. $updated_fields['desc'] = $desc;
  3539. }
  3540. if (!is_null($album_new)) {
  3541. $updated_fields['album'] = $album_new;
  3542. }
  3543. if (!is_null($allow_cid)) {
  3544. $allow_cid = trim($allow_cid);
  3545. $updated_fields['allow_cid'] = $allow_cid;
  3546. }
  3547. if (!is_null($deny_cid)) {
  3548. $deny_cid = trim($deny_cid);
  3549. $updated_fields['deny_cid'] = $deny_cid;
  3550. }
  3551. if (!is_null($allow_gid)) {
  3552. $allow_gid = trim($allow_gid);
  3553. $updated_fields['allow_gid'] = $allow_gid;
  3554. }
  3555. if (!is_null($deny_gid)) {
  3556. $deny_gid = trim($deny_gid);
  3557. $updated_fields['deny_gid'] = $deny_gid;
  3558. }
  3559. $result = false;
  3560. if (count($updated_fields) > 0) {
  3561. $nothingtodo = false;
  3562. $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
  3563. } else {
  3564. $nothingtodo = true;
  3565. }
  3566. if (!empty($_FILES['media'])) {
  3567. $nothingtodo = false;
  3568. $media = $_FILES['media'];
  3569. $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
  3570. if (!is_null($data)) {
  3571. return api_format_data("photo_update", $type, $data);
  3572. }
  3573. }
  3574. // return success of updating or error message
  3575. if ($result) {
  3576. $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
  3577. return api_format_data("photo_update", $type, ['$result' => $answer]);
  3578. } else {
  3579. if ($nothingtodo) {
  3580. $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
  3581. return api_format_data("photo_update", $type, ['$result' => $answer]);
  3582. }
  3583. throw new InternalServerErrorException("unknown error - update photo entry in database failed");
  3584. }
  3585. }
  3586. throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
  3587. }
  3588. /**
  3589. * @brief delete a single photo from the database through api
  3590. *
  3591. * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  3592. * @return string|array
  3593. */
  3594. function api_fr_photo_delete($type)
  3595. {
  3596. if (api_user() === false) {
  3597. throw new ForbiddenException();
  3598. }
  3599. // input params
  3600. $photo_id = defaults($_REQUEST, 'photo_id', null);
  3601. // do several checks on input parameters
  3602. // we do not allow calls without photo id
  3603. if ($photo_id == null) {
  3604. throw new BadRequestException("no photo_id specified");
  3605. }
  3606. // check if photo is existing in database
  3607. $r = Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()]);
  3608. if (!$r) {
  3609. throw new BadRequestException("photo not available");
  3610. }
  3611. // now we can perform on the deletion of the photo
  3612. $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
  3613. // return success of deletion or error message
  3614. if ($result) {
  3615. // retrieve the id of the parent element (the photo element)
  3616. $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
  3617. $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
  3618. if (!DBA::isResult($photo_item)) {
  3619. throw new InternalServerErrorException("problem with deleting items occured");
  3620. }
  3621. // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
  3622. // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
  3623. Item::deleteForUser(['id' => $photo_item['id']], api_user());
  3624. $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
  3625. return api_format_data("photo_delete", $type, ['$result' => $answer]);
  3626. } else {
  3627. throw new InternalServerErrorException("unknown error on deleting photo from database table");
  3628. }
  3629. }
  3630. /**
  3631. * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
  3632. *
  3633. * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  3634. * @return string|array
  3635. */
  3636. function api_fr_photo_detail($type)
  3637. {
  3638. if (api_user() === false) {
  3639. throw new ForbiddenException();
  3640. }
  3641. if (empty($_REQUEST['photo_id'])) {
  3642. throw new BadRequestException("No photo id.");
  3643. }
  3644. $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
  3645. $photo_id = $_REQUEST['photo_id'];
  3646. // prepare json/xml output with data from database for the requested photo
  3647. $data = prepare_photo_data($type, $scale, $photo_id);
  3648. return api_format_data("photo_detail", $type, $data);
  3649. }
  3650. /**
  3651. * Updates the user’s profile image.
  3652. *
  3653. * @brief updates the profile image for the user (either a specified profile or the default profile)
  3654. *
  3655. * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  3656. *
  3657. * @return string|array
  3658. * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
  3659. */
  3660. function api_account_update_profile_image($type)
  3661. {
  3662. if (api_user() === false) {
  3663. throw new ForbiddenException();
  3664. }
  3665. // input params
  3666. $profile_id = defaults($_REQUEST, 'profile_id', 0);
  3667. // error if image data is missing
  3668. if (empty($_FILES['image'])) {
  3669. throw new BadRequestException("no media data submitted");
  3670. }
  3671. // check if specified profile id is valid
  3672. if ($profile_id != 0) {
  3673. $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
  3674. // error message if specified profile id is not in database
  3675. if (!DBA::isResult($profile)) {
  3676. throw new BadRequestException("profile_id not available");
  3677. }
  3678. $is_default_profile = $profile['is-default'];
  3679. } else {
  3680. $is_default_profile = 1;
  3681. }
  3682. // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
  3683. $media = null;
  3684. if (!empty($_FILES['image'])) {
  3685. $media = $_FILES['image'];
  3686. } elseif (!empty($_FILES['media'])) {
  3687. $media = $_FILES['media'];
  3688. }
  3689. // save new profile image
  3690. $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
  3691. // get filetype
  3692. if (is_array($media['type'])) {
  3693. $filetype = $media['type'][0];
  3694. } else {
  3695. $filetype = $media['type'];
  3696. }
  3697. if ($filetype == "image/jpeg") {
  3698. $fileext = "jpg";
  3699. } elseif ($filetype == "image/png") {
  3700. $fileext = "png";
  3701. } else {
  3702. throw new InternalServerErrorException('Unsupported filetype');
  3703. }
  3704. // change specified profile or all profiles to the new resource-id
  3705. if ($is_default_profile) {
  3706. $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
  3707. Photo::update(['profile' => false], $condition);
  3708. } else {
  3709. $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype,
  3710. 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype];
  3711. DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
  3712. }
  3713. Contact::updateSelfFromUserID(api_user(), true);
  3714. // Update global directory in background
  3715. $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
  3716. if ($url && strlen(Config::get('system', 'directory'))) {
  3717. Worker::add(PRIORITY_LOW, "Directory", $url);
  3718. }
  3719. Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
  3720. // output for client
  3721. if ($data) {
  3722. return api_account_verify_credentials($type);
  3723. } else {
  3724. // SaveMediaToDatabase failed for some reason
  3725. throw new InternalServerErrorException("image upload failed");
  3726. }
  3727. }
  3728. // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
  3729. api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
  3730. api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
  3731. api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
  3732. api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
  3733. api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
  3734. api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
  3735. api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
  3736. api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
  3737. /**
  3738. * Update user profile
  3739. *
  3740. * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  3741. *
  3742. * @return array|string
  3743. */
  3744. function api_account_update_profile($type)
  3745. {
  3746. $local_user = api_user();
  3747. $api_user = api_get_user(get_app());
  3748. if (!empty($_POST['name'])) {
  3749. DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
  3750. DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
  3751. DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
  3752. DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
  3753. }
  3754. if (isset($_POST['description'])) {
  3755. DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
  3756. DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
  3757. DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
  3758. }
  3759. Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
  3760. // Update global directory in background
  3761. if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
  3762. Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
  3763. }
  3764. return api_account_verify_credentials($type);
  3765. }
  3766. /// @TODO move to top of file or somewhere better
  3767. api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
  3768. /**
  3769. *
  3770. * @param string $acl_string
  3771. */
  3772. function check_acl_input($acl_string)
  3773. {
  3774. if ($acl_string == null || $acl_string == " ") {
  3775. return false;
  3776. }
  3777. $contact_not_found = false;
  3778. // split <x><y><z> into array of cid's
  3779. preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
  3780. // check for each cid if it is available on server
  3781. $cid_array = $array[0];
  3782. foreach ($cid_array as $cid) {
  3783. $cid = str_replace("<", "", $cid);
  3784. $cid = str_replace(">", "", $cid);
  3785. $condition = ['id' => $cid, 'uid' => api_user()];
  3786. $contact_not_found |= !DBA::exists('contact', $condition);
  3787. }
  3788. return $contact_not_found;
  3789. }
  3790. /**
  3791. *
  3792. * @param string $mediatype
  3793. * @param array $media
  3794. * @param string $type
  3795. * @param string $album
  3796. * @param string $allow_cid
  3797. * @param string $deny_cid
  3798. * @param string $allow_gid
  3799. * @param string $deny_gid
  3800. * @param string $desc
  3801. * @param integer $profile
  3802. * @param boolean $visibility
  3803. * @param string $photo_id
  3804. */
  3805. function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $profile = 0, $visibility = false, $photo_id = null)
  3806. {
  3807. $visitor = 0;
  3808. $src = "";
  3809. $filetype = "";
  3810. $filename = "";
  3811. $filesize = 0;
  3812. if (is_array($media)) {
  3813. if (is_array($media['tmp_name'])) {
  3814. $src = $media['tmp_name'][0];
  3815. } else {
  3816. $src = $media['tmp_name'];
  3817. }
  3818. if (is_array($media['name'])) {
  3819. $filename = basename($media['name'][0]);
  3820. } else {
  3821. $filename = basename($media['name']);
  3822. }
  3823. if (is_array($media['size'])) {
  3824. $filesize = intval($media['size'][0]);
  3825. } else {
  3826. $filesize = intval($media['size']);
  3827. }
  3828. if (is_array($media['type'])) {
  3829. $filetype = $media['type'][0];
  3830. } else {
  3831. $filetype = $media['type'];
  3832. }
  3833. }
  3834. if ($filetype == "") {
  3835. $filetype=Image::guessType($filename);
  3836. }
  3837. $imagedata = @getimagesize($src);
  3838. if ($imagedata) {
  3839. $filetype = $imagedata['mime'];
  3840. }
  3841. Logger::log(
  3842. "File upload src: " . $src . " - filename: " . $filename .
  3843. " - size: " . $filesize . " - type: " . $filetype,
  3844. Logger::DEBUG
  3845. );
  3846. // check if there was a php upload error
  3847. if ($filesize == 0 && $media['error'] == 1) {
  3848. throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
  3849. }
  3850. // check against max upload size within Friendica instance
  3851. $maximagesize = Config::get('system', 'maximagesize');
  3852. if ($maximagesize && ($filesize > $maximagesize)) {
  3853. $formattedBytes = Strings::formatBytes($maximagesize);
  3854. throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
  3855. }
  3856. // create Photo instance with the data of the image
  3857. $imagedata = @file_get_contents($src);
  3858. $Image = new Image($imagedata, $filetype);
  3859. if (!$Image->isValid()) {
  3860. throw new InternalServerErrorException("unable to process image data");
  3861. }
  3862. // check orientation of image
  3863. $Image->orient($src);
  3864. @unlink($src);
  3865. // check max length of images on server
  3866. $max_length = Config::get('system', 'max_image_length');
  3867. if (!$max_length) {
  3868. $max_length = MAX_IMAGE_LENGTH;
  3869. }
  3870. if ($max_length > 0) {
  3871. $Image->scaleDown($max_length);
  3872. Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
  3873. }
  3874. $width = $Image->getWidth();
  3875. $height = $Image->getHeight();
  3876. // create a new resource-id if not already provided
  3877. $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
  3878. if ($mediatype == "photo") {
  3879. // upload normal image (scales 0, 1, 2)
  3880. Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
  3881. $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
  3882. if (!$r) {
  3883. Logger::log("photo upload: image upload with scale 0 (original size) failed");
  3884. }
  3885. if ($width > 640 || $height > 640) {
  3886. $Image->scaleDown(640);
  3887. $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
  3888. if (!$r) {
  3889. Logger::log("photo upload: image upload with scale 1 (640x640) failed");
  3890. }
  3891. }
  3892. if ($width > 320 || $height > 320) {
  3893. $Image->scaleDown(320);
  3894. $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
  3895. if (!$r) {
  3896. Logger::log("photo upload: image upload with scale 2 (320x320) failed");
  3897. }
  3898. }
  3899. Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
  3900. } elseif ($mediatype == "profileimage") {
  3901. // upload profile image (scales 4, 5, 6)
  3902. Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
  3903. if ($width > 300 || $height > 300) {
  3904. $Image->scaleDown(300);
  3905. $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
  3906. if (!$r) {
  3907. Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
  3908. }
  3909. }
  3910. if ($width > 80 || $height > 80) {
  3911. $Image->scaleDown(80);
  3912. $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
  3913. if (!$r) {
  3914. Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
  3915. }
  3916. }
  3917. if ($width > 48 || $height > 48) {
  3918. $Image->scaleDown(48);
  3919. $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
  3920. if (!$r) {
  3921. Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
  3922. }
  3923. }
  3924. $Image->__destruct();
  3925. Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
  3926. }
  3927. if (isset($r) && $r) {
  3928. // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
  3929. if ($photo_id == null && $mediatype == "photo") {
  3930. post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
  3931. }
  3932. // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
  3933. return prepare_photo_data($type, false, $hash);
  3934. } else {
  3935. throw new InternalServerErrorException("image upload failed");
  3936. }
  3937. }
  3938. /**
  3939. *
  3940. * @param string $hash
  3941. * @param string $allow_cid
  3942. * @param string $deny_cid
  3943. * @param string $allow_gid
  3944. * @param string $deny_gid
  3945. * @param string $filetype
  3946. * @param boolean $visibility
  3947. */
  3948. function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
  3949. {
  3950. // get data about the api authenticated user
  3951. $uri = Item::newURI(intval(api_user()));
  3952. $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
  3953. $arr = [];
  3954. $arr['guid'] = System::createUUID();
  3955. $arr['uid'] = intval(api_user());
  3956. $arr['uri'] = $uri;
  3957. $arr['parent-uri'] = $uri;
  3958. $arr['type'] = 'photo';
  3959. $arr['wall'] = 1;
  3960. $arr['resource-id'] = $hash;
  3961. $arr['contact-id'] = $owner_record['id'];
  3962. $arr['owner-name'] = $owner_record['name'];
  3963. $arr['owner-link'] = $owner_record['url'];
  3964. $arr['owner-avatar'] = $owner_record['thumb'];
  3965. $arr['author-name'] = $owner_record['name'];
  3966. $arr['author-link'] = $owner_record['url'];
  3967. $arr['author-avatar'] = $owner_record['thumb'];
  3968. $arr['title'] = "";
  3969. $arr['allow_cid'] = $allow_cid;
  3970. $arr['allow_gid'] = $allow_gid;
  3971. $arr['deny_cid'] = $deny_cid;
  3972. $arr['deny_gid'] = $deny_gid;
  3973. $arr['visible'] = $visibility;
  3974. $arr['origin'] = 1;
  3975. $typetoext = [
  3976. 'image/jpeg' => 'jpg',
  3977. 'image/png' => 'png',
  3978. 'image/gif' => 'gif'
  3979. ];
  3980. // adds link to the thumbnail scale photo
  3981. $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
  3982. . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
  3983. . '[/url]';
  3984. // do the magic for storing the item in the database and trigger the federation to other contacts
  3985. Item::insert($arr);
  3986. }
  3987. /**
  3988. *
  3989. * @param string $type
  3990. * @param int $scale
  3991. * @param string $photo_id
  3992. *
  3993. * @return array
  3994. */
  3995. function prepare_photo_data($type, $scale, $photo_id)
  3996. {
  3997. $a = \get_app();
  3998. $user_info = api_get_user($a);
  3999. if ($user_info === false) {
  4000. throw new ForbiddenException();
  4001. }
  4002. $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
  4003. $data_sql = ($scale === false ? "" : "data, ");
  4004. // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
  4005. // clients needs to convert this in their way for further processing
  4006. $r = q(
  4007. "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
  4008. `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
  4009. MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
  4010. FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
  4011. $data_sql,
  4012. intval(local_user()),
  4013. DBA::escape($photo_id),
  4014. $scale_sql
  4015. );
  4016. $typetoext = [
  4017. 'image/jpeg' => 'jpg',
  4018. 'image/png' => 'png',
  4019. 'image/gif' => 'gif'
  4020. ];
  4021. // prepare output data for photo
  4022. if (DBA::isResult($r)) {
  4023. $data = ['photo' => $r[0]];
  4024. $data['photo']['id'] = $data['photo']['resource-id'];
  4025. if ($scale !== false) {
  4026. $data['photo']['data'] = base64_encode($data['photo']['data']);
  4027. } else {
  4028. unset($data['photo']['datasize']); //needed only with scale param
  4029. }
  4030. if ($type == "xml") {
  4031. $data['photo']['links'] = [];
  4032. for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
  4033. $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
  4034. "scale" => $k,
  4035. "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
  4036. }
  4037. } else {
  4038. $data['photo']['link'] = [];
  4039. // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
  4040. $i = 0;
  4041. for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
  4042. $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
  4043. $i++;
  4044. }
  4045. }
  4046. unset($data['photo']['resource-id']);
  4047. unset($data['photo']['minscale']);
  4048. unset($data['photo']['maxscale']);
  4049. } else {
  4050. throw new NotFoundException();
  4051. }
  4052. // retrieve item element for getting activities (like, dislike etc.) related to photo
  4053. $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
  4054. $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
  4055. $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
  4056. // retrieve comments on photo
  4057. $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
  4058. $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
  4059. $statuses = Item::selectForUser(api_user(), [], $condition);
  4060. // prepare output of comments
  4061. $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
  4062. $comments = [];
  4063. if ($type == "xml") {
  4064. $k = 0;
  4065. foreach ($commentData as $comment) {
  4066. $comments[$k++ . ":comment"] = $comment;
  4067. }
  4068. } else {
  4069. foreach ($commentData as $comment) {
  4070. $comments[] = $comment;
  4071. }
  4072. }
  4073. $data['photo']['friendica_comments'] = $comments;
  4074. // include info if rights on photo and rights on item are mismatching
  4075. $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
  4076. $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
  4077. $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
  4078. $data['photo']['deny_cid'] != $item[0]['deny_cid'];
  4079. $data['photo']['rights_mismatch'] = $rights_mismatch;
  4080. return $data;
  4081. }
  4082. /**
  4083. * Similar as /mod/redir.php
  4084. * redirect to 'url' after dfrn auth
  4085. *
  4086. * Why this when there is mod/redir.php already?
  4087. * This use api_user() and api_login()
  4088. *
  4089. * params
  4090. * c_url: url of remote contact to auth to
  4091. * url: string, url to redirect after auth
  4092. */
  4093. function api_friendica_remoteauth()
  4094. {
  4095. $url = defaults($_GET, 'url', '');
  4096. $c_url = defaults($_GET, 'c_url', '');
  4097. if ($url === '' || $c_url === '') {
  4098. throw new BadRequestException("Wrong parameters.");
  4099. }
  4100. $c_url = Strings::normaliseLink($c_url);
  4101. // traditional DFRN
  4102. $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
  4103. if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
  4104. throw new BadRequestException("Unknown contact");
  4105. }
  4106. $cid = $contact['id'];
  4107. $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
  4108. if ($contact['duplex'] && $contact['issued-id']) {
  4109. $orig_id = $contact['issued-id'];
  4110. $dfrn_id = '1:' . $orig_id;
  4111. }
  4112. if ($contact['duplex'] && $contact['dfrn-id']) {
  4113. $orig_id = $contact['dfrn-id'];
  4114. $dfrn_id = '0:' . $orig_id;
  4115. }
  4116. $sec = Strings::getRandomHex();
  4117. $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
  4118. 'sec' => $sec, 'expire' => time() + 45];
  4119. DBA::insert('profile_check', $fields);
  4120. $a = get_app();
  4121. $a->getLogger()->info('API: friendica_remoteauth', ['module' => 'api', 'action' => 'remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
  4122. $dest = ($url ? '&destination_url=' . $url : '');
  4123. System::externalRedirect(
  4124. $contact['poll'] . '?dfrn_id=' . $dfrn_id
  4125. . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
  4126. . '&type=profile&sec=' . $sec . $dest
  4127. );
  4128. }
  4129. api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
  4130. /**
  4131. * @brief Return the item shared, if the item contains only the [share] tag
  4132. *
  4133. * @param array $item Sharer item
  4134. * @return array|false Shared item or false if not a reshare
  4135. */
  4136. function api_share_as_retweet(&$item)
  4137. {
  4138. $body = trim($item["body"]);
  4139. if (Diaspora::isReshare($body, false) === false) {
  4140. if ($item['author-id'] == $item['owner-id']) {
  4141. return false;
  4142. } else {
  4143. // Reshares from OStatus, ActivityPub and Twitter
  4144. $reshared_item = $item;
  4145. $reshared_item['owner-id'] = $reshared_item['author-id'];
  4146. $reshared_item['owner-link'] = $reshared_item['author-link'];
  4147. $reshared_item['owner-name'] = $reshared_item['author-name'];
  4148. $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
  4149. return $reshared_item;
  4150. }
  4151. }
  4152. /// @TODO "$1" should maybe mean '$1' ?
  4153. $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
  4154. /*
  4155. * Skip if there is no shared message in there
  4156. * we already checked this in diaspora::isReshare()
  4157. * but better one more than one less...
  4158. */
  4159. if (($body == $attributes) || empty($attributes)) {
  4160. return false;
  4161. }
  4162. // build the fake reshared item
  4163. $reshared_item = $item;
  4164. $author = "";
  4165. preg_match("/author='(.*?)'/ism", $attributes, $matches);
  4166. if (!empty($matches[1])) {
  4167. $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
  4168. }
  4169. preg_match('/author="(.*?)"/ism', $attributes, $matches);
  4170. if (!empty($matches[1])) {
  4171. $author = $matches[1];
  4172. }
  4173. $profile = "";
  4174. preg_match("/profile='(.*?)'/ism", $attributes, $matches);
  4175. if (!empty($matches[1])) {
  4176. $profile = $matches[1];
  4177. }
  4178. preg_match('/profile="(.*?)"/ism', $attributes, $matches);
  4179. if (!empty($matches[1])) {
  4180. $profile = $matches[1];
  4181. }
  4182. $avatar = "";
  4183. preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
  4184. if (!empty($matches[1])) {
  4185. $avatar = $matches[1];
  4186. }
  4187. preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
  4188. if (!empty($matches[1])) {
  4189. $avatar = $matches[1];
  4190. }
  4191. $link = "";
  4192. preg_match("/link='(.*?)'/ism", $attributes, $matches);
  4193. if (!empty($matches[1])) {
  4194. $link = $matches[1];
  4195. }
  4196. preg_match('/link="(.*?)"/ism', $attributes, $matches);
  4197. if (!empty($matches[1])) {
  4198. $link = $matches[1];
  4199. }
  4200. $posted = "";
  4201. preg_match("/posted='(.*?)'/ism", $attributes, $matches);
  4202. if (!empty($matches[1])) {
  4203. $posted = $matches[1];
  4204. }
  4205. preg_match('/posted="(.*?)"/ism', $attributes, $matches);
  4206. if (!empty($matches[1])) {
  4207. $posted = $matches[1];
  4208. }
  4209. $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
  4210. if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
  4211. return false;
  4212. }
  4213. $reshared_item["body"] = $shared_body;
  4214. $reshared_item["author-id"] = Contact::getIdForURL($profile, 0, true);
  4215. $reshared_item["author-name"] = $author;
  4216. $reshared_item["author-link"] = $profile;
  4217. $reshared_item["author-avatar"] = $avatar;
  4218. $reshared_item["plink"] = $link;
  4219. $reshared_item["created"] = $posted;
  4220. $reshared_item["edited"] = $posted;
  4221. return $reshared_item;
  4222. }
  4223. /**
  4224. *
  4225. * @param string $profile
  4226. *
  4227. * @return string|false
  4228. * @todo remove trailing junk from profile url
  4229. * @todo pump.io check has to check the website
  4230. */
  4231. function api_get_nick($profile)
  4232. {
  4233. $nick = "";
  4234. $r = q(
  4235. "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
  4236. DBA::escape(Strings::normaliseLink($profile))
  4237. );
  4238. if (DBA::isResult($r)) {
  4239. $nick = $r[0]["nick"];
  4240. }
  4241. if (!$nick == "") {
  4242. $r = q(
  4243. "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
  4244. DBA::escape(Strings::normaliseLink($profile))
  4245. );
  4246. if (DBA::isResult($r)) {
  4247. $nick = $r[0]["nick"];
  4248. }
  4249. }
  4250. if (!$nick == "") {
  4251. $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
  4252. if ($friendica != $profile) {
  4253. $nick = $friendica;
  4254. }
  4255. }
  4256. if (!$nick == "") {
  4257. $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
  4258. if ($diaspora != $profile) {
  4259. $nick = $diaspora;
  4260. }
  4261. }
  4262. if (!$nick == "") {
  4263. $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
  4264. if ($twitter != $profile) {
  4265. $nick = $twitter;
  4266. }
  4267. }
  4268. if (!$nick == "") {
  4269. $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
  4270. if ($StatusnetHost != $profile) {
  4271. $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
  4272. if ($StatusnetUser != $profile) {
  4273. $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
  4274. $user = json_decode($UserData);
  4275. if ($user) {
  4276. $nick = $user->screen_name;
  4277. }
  4278. }
  4279. }
  4280. }
  4281. // To-Do: look at the page if its really a pumpio site
  4282. //if (!$nick == "") {
  4283. // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
  4284. // if ($pumpio != $profile)
  4285. // $nick = $pumpio;
  4286. // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
  4287. //}
  4288. if ($nick != "") {
  4289. return $nick;
  4290. }
  4291. return false;
  4292. }
  4293. /**
  4294. *
  4295. * @param array $item
  4296. *
  4297. * @return array
  4298. */
  4299. function api_in_reply_to($item)
  4300. {
  4301. $in_reply_to = [];
  4302. $in_reply_to['status_id'] = null;
  4303. $in_reply_to['user_id'] = null;
  4304. $in_reply_to['status_id_str'] = null;
  4305. $in_reply_to['user_id_str'] = null;
  4306. $in_reply_to['screen_name'] = null;
  4307. if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
  4308. $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
  4309. if (DBA::isResult($parent)) {
  4310. $in_reply_to['status_id'] = intval($parent['id']);
  4311. } else {
  4312. $in_reply_to['status_id'] = intval($item['parent']);
  4313. }
  4314. $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
  4315. $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
  4316. $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
  4317. if (DBA::isResult($parent)) {
  4318. if ($parent['author-nick'] == "") {
  4319. $parent['author-nick'] = api_get_nick($parent['author-link']);
  4320. }
  4321. $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
  4322. $in_reply_to['user_id'] = intval($parent['author-id']);
  4323. $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
  4324. }
  4325. // There seems to be situation, where both fields are identical:
  4326. // https://github.com/friendica/friendica/issues/1010
  4327. // This is a bugfix for that.
  4328. if (intval($in_reply_to['status_id']) == intval($item['id'])) {
  4329. $a = get_app();
  4330. $a->getLogger()->warning('ID is similar to reply-to', ['module' => 'api', 'action' => 'in_reply_to', 'id' => $item['id'], 'reply-to' => $in_reply_to['status_id']]);
  4331. $in_reply_to['status_id'] = null;
  4332. $in_reply_to['user_id'] = null;
  4333. $in_reply_to['status_id_str'] = null;
  4334. $in_reply_to['user_id_str'] = null;
  4335. $in_reply_to['screen_name'] = null;
  4336. }
  4337. }
  4338. return $in_reply_to;
  4339. }
  4340. /**
  4341. *
  4342. * @param string $text
  4343. *
  4344. * @return string
  4345. */
  4346. function api_clean_plain_items($text)
  4347. {
  4348. $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
  4349. $text = BBCode::cleanPictureLinks($text);
  4350. $URLSearchString = "^\[\]";
  4351. $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
  4352. if ($include_entities == "true") {
  4353. $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
  4354. }
  4355. // Simplify "attachment" element
  4356. $text = api_clean_attachments($text);
  4357. return $text;
  4358. }
  4359. /**
  4360. * @brief Removes most sharing information for API text export
  4361. *
  4362. * @param string $body The original body
  4363. *
  4364. * @return string Cleaned body
  4365. */
  4366. function api_clean_attachments($body)
  4367. {
  4368. $data = BBCode::getAttachmentData($body);
  4369. if (empty($data)) {
  4370. return $body;
  4371. }
  4372. $body = "";
  4373. if (isset($data["text"])) {
  4374. $body = $data["text"];
  4375. }
  4376. if (($body == "") && isset($data["title"])) {
  4377. $body = $data["title"];
  4378. }
  4379. if (isset($data["url"])) {
  4380. $body .= "\n".$data["url"];
  4381. }
  4382. $body .= $data["after"];
  4383. return $body;
  4384. }
  4385. /**
  4386. *
  4387. * @param array $contacts
  4388. *
  4389. * @return array
  4390. */
  4391. function api_best_nickname(&$contacts)
  4392. {
  4393. $best_contact = [];
  4394. if (count($contacts) == 0) {
  4395. return;
  4396. }
  4397. foreach ($contacts as $contact) {
  4398. if ($contact["network"] == "") {
  4399. $contact["network"] = "dfrn";
  4400. $best_contact = [$contact];
  4401. }
  4402. }
  4403. if (sizeof($best_contact) == 0) {
  4404. foreach ($contacts as $contact) {
  4405. if ($contact["network"] == "dfrn") {
  4406. $best_contact = [$contact];
  4407. }
  4408. }
  4409. }
  4410. if (sizeof($best_contact) == 0) {
  4411. foreach ($contacts as $contact) {
  4412. if ($contact["network"] == "dspr") {
  4413. $best_contact = [$contact];
  4414. }
  4415. }
  4416. }
  4417. if (sizeof($best_contact) == 0) {
  4418. foreach ($contacts as $contact) {
  4419. if ($contact["network"] == "stat") {
  4420. $best_contact = [$contact];
  4421. }
  4422. }
  4423. }
  4424. if (sizeof($best_contact) == 0) {
  4425. foreach ($contacts as $contact) {
  4426. if ($contact["network"] == "pump") {
  4427. $best_contact = [$contact];
  4428. }
  4429. }
  4430. }
  4431. if (sizeof($best_contact) == 0) {
  4432. foreach ($contacts as $contact) {
  4433. if ($contact["network"] == "twit") {
  4434. $best_contact = [$contact];
  4435. }
  4436. }
  4437. }
  4438. if (sizeof($best_contact) == 1) {
  4439. $contacts = $best_contact;
  4440. } else {
  4441. $contacts = [$contacts[0]];
  4442. }
  4443. }
  4444. /**
  4445. * Return all or a specified group of the user with the containing contacts.
  4446. *
  4447. * @param string $type Return type (atom, rss, xml, json)
  4448. *
  4449. * @return array|string
  4450. */
  4451. function api_friendica_group_show($type)
  4452. {
  4453. $a = \get_app();
  4454. if (api_user() === false) {
  4455. throw new ForbiddenException();
  4456. }
  4457. // params
  4458. $user_info = api_get_user($a);
  4459. $gid = defaults($_REQUEST, 'gid', 0);
  4460. $uid = $user_info['uid'];
  4461. // get data of the specified group id or all groups if not specified
  4462. if ($gid != 0) {
  4463. $r = q(
  4464. "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
  4465. intval($uid),
  4466. intval($gid)
  4467. );
  4468. // error message if specified gid is not in database
  4469. if (!DBA::isResult($r)) {
  4470. throw new BadRequestException("gid not available");
  4471. }
  4472. } else {
  4473. $r = q(
  4474. "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
  4475. intval($uid)
  4476. );
  4477. }
  4478. // loop through all groups and retrieve all members for adding data in the user array
  4479. $grps = [];
  4480. foreach ($r as $rr) {
  4481. $members = Contact::getByGroupId($rr['id']);
  4482. $users = [];
  4483. if ($type == "xml") {
  4484. $user_element = "users";
  4485. $k = 0;
  4486. foreach ($members as $member) {
  4487. $user = api_get_user($a, $member['nurl']);
  4488. $users[$k++.":user"] = $user;
  4489. }
  4490. } else {
  4491. $user_element = "user";
  4492. foreach ($members as $member) {
  4493. $user = api_get_user($a, $member['nurl']);
  4494. $users[] = $user;
  4495. }
  4496. }
  4497. $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
  4498. }
  4499. return api_format_data("groups", $type, ['group' => $grps]);
  4500. }
  4501. api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
  4502. /**
  4503. * Delete the specified group of the user.
  4504. *
  4505. * @param string $type Return type (atom, rss, xml, json)
  4506. *
  4507. * @return array|string
  4508. */
  4509. function api_friendica_group_delete($type)
  4510. {
  4511. $a = \get_app();
  4512. if (api_user() === false) {
  4513. throw new ForbiddenException();
  4514. }
  4515. // params
  4516. $user_info = api_get_user($a);
  4517. $gid = defaults($_REQUEST, 'gid', 0);
  4518. $name = defaults($_REQUEST, 'name', "");
  4519. $uid = $user_info['uid'];
  4520. // error if no gid specified
  4521. if ($gid == 0 || $name == "") {
  4522. throw new BadRequestException('gid or name not specified');
  4523. }
  4524. // get data of the specified group id
  4525. $r = q(
  4526. "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
  4527. intval($uid),
  4528. intval($gid)
  4529. );
  4530. // error message if specified gid is not in database
  4531. if (!DBA::isResult($r)) {
  4532. throw new BadRequestException('gid not available');
  4533. }
  4534. // get data of the specified group id and group name
  4535. $rname = q(
  4536. "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
  4537. intval($uid),
  4538. intval($gid),
  4539. DBA::escape($name)
  4540. );
  4541. // error message if specified gid is not in database
  4542. if (!DBA::isResult($rname)) {
  4543. throw new BadRequestException('wrong group name');
  4544. }
  4545. // delete group
  4546. $ret = Group::removeByName($uid, $name);
  4547. if ($ret) {
  4548. // return success
  4549. $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
  4550. return api_format_data("group_delete", $type, ['result' => $success]);
  4551. } else {
  4552. throw new BadRequestException('other API error');
  4553. }
  4554. }
  4555. api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
  4556. /**
  4557. * Delete a group.
  4558. *
  4559. * @param string $type Return type (atom, rss, xml, json)
  4560. *
  4561. * @return array|string
  4562. * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
  4563. */
  4564. function api_lists_destroy($type)
  4565. {
  4566. $a = \get_app();
  4567. if (api_user() === false) {
  4568. throw new ForbiddenException();
  4569. }
  4570. // params
  4571. $user_info = api_get_user($a);
  4572. $gid = defaults($_REQUEST, 'list_id', 0);
  4573. $uid = $user_info['uid'];
  4574. // error if no gid specified
  4575. if ($gid == 0) {
  4576. throw new BadRequestException('gid not specified');
  4577. }
  4578. // get data of the specified group id
  4579. $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
  4580. // error message if specified gid is not in database
  4581. if (!$group) {
  4582. throw new BadRequestException('gid not available');
  4583. }
  4584. if (Group::remove($gid)) {
  4585. $list = [
  4586. 'name' => $group['name'],
  4587. 'id' => intval($gid),
  4588. 'id_str' => (string) $gid,
  4589. 'user' => $user_info
  4590. ];
  4591. return api_format_data("lists", $type, ['lists' => $list]);
  4592. }
  4593. }
  4594. api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
  4595. /**
  4596. * Add a new group to the database.
  4597. *
  4598. * @param string $name Group name
  4599. * @param int $uid User ID
  4600. * @param array $users List of users to add to the group
  4601. *
  4602. * @return array
  4603. */
  4604. function group_create($name, $uid, $users = [])
  4605. {
  4606. // error if no name specified
  4607. if ($name == "") {
  4608. throw new BadRequestException('group name not specified');
  4609. }
  4610. // get data of the specified group name
  4611. $rname = q(
  4612. "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
  4613. intval($uid),
  4614. DBA::escape($name)
  4615. );
  4616. // error message if specified group name already exists
  4617. if (DBA::isResult($rname)) {
  4618. throw new BadRequestException('group name already exists');
  4619. }
  4620. // check if specified group name is a deleted group
  4621. $rname = q(
  4622. "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
  4623. intval($uid),
  4624. DBA::escape($name)
  4625. );
  4626. // error message if specified group name already exists
  4627. if (DBA::isResult($rname)) {
  4628. $reactivate_group = true;
  4629. }
  4630. // create group
  4631. $ret = Group::create($uid, $name);
  4632. if ($ret) {
  4633. $gid = Group::getIdByName($uid, $name);
  4634. } else {
  4635. throw new BadRequestException('other API error');
  4636. }
  4637. // add members
  4638. $erroraddinguser = false;
  4639. $errorusers = [];
  4640. foreach ($users as $user) {
  4641. $cid = $user['cid'];
  4642. // check if user really exists as contact
  4643. $contact = q(
  4644. "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
  4645. intval($cid),
  4646. intval($uid)
  4647. );
  4648. if (count($contact)) {
  4649. Group::addMember($gid, $cid);
  4650. } else {
  4651. $erroraddinguser = true;
  4652. $errorusers[] = $cid;
  4653. }
  4654. }
  4655. // return success message incl. missing users in array
  4656. $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
  4657. return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
  4658. }
  4659. /**
  4660. * Create the specified group with the posted array of contacts.
  4661. *
  4662. * @param string $type Return type (atom, rss, xml, json)
  4663. *
  4664. * @return array|string
  4665. */
  4666. function api_friendica_group_create($type)
  4667. {
  4668. $a = \get_app();
  4669. if (api_user() === false) {
  4670. throw new ForbiddenException();
  4671. }
  4672. // params
  4673. $user_info = api_get_user($a);
  4674. $name = defaults($_REQUEST, 'name', "");
  4675. $uid = $user_info['uid'];
  4676. $json = json_decode($_POST['json'], true);
  4677. $users = $json['user'];
  4678. $success = group_create($name, $uid, $users);
  4679. return api_format_data("group_create", $type, ['result' => $success]);
  4680. }
  4681. api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
  4682. /**
  4683. * Create a new group.
  4684. *
  4685. * @param string $type Return type (atom, rss, xml, json)
  4686. *
  4687. * @return array|string
  4688. * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
  4689. */
  4690. function api_lists_create($type)
  4691. {
  4692. $a = \get_app();
  4693. if (api_user() === false) {
  4694. throw new ForbiddenException();
  4695. }
  4696. // params
  4697. $user_info = api_get_user($a);
  4698. $name = defaults($_REQUEST, 'name', "");
  4699. $uid = $user_info['uid'];
  4700. $success = group_create($name, $uid);
  4701. if ($success['success']) {
  4702. $grp = [
  4703. 'name' => $success['name'],
  4704. 'id' => intval($success['gid']),
  4705. 'id_str' => (string) $success['gid'],
  4706. 'user' => $user_info
  4707. ];
  4708. return api_format_data("lists", $type, ['lists'=>$grp]);
  4709. }
  4710. }
  4711. api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
  4712. /**
  4713. * Update the specified group with the posted array of contacts.
  4714. *
  4715. * @param string $type Return type (atom, rss, xml, json)
  4716. *
  4717. * @return array|string
  4718. */
  4719. function api_friendica_group_update($type)
  4720. {
  4721. $a = \get_app();
  4722. if (api_user() === false) {
  4723. throw new ForbiddenException();
  4724. }
  4725. // params
  4726. $user_info = api_get_user($a);
  4727. $uid = $user_info['uid'];
  4728. $gid = defaults($_REQUEST, 'gid', 0);
  4729. $name = defaults($_REQUEST, 'name', "");
  4730. $json = json_decode($_POST['json'], true);
  4731. $users = $json['user'];
  4732. // error if no name specified
  4733. if ($name == "") {
  4734. throw new BadRequestException('group name not specified');
  4735. }
  4736. // error if no gid specified
  4737. if ($gid == "") {
  4738. throw new BadRequestException('gid not specified');
  4739. }
  4740. // remove members
  4741. $members = Contact::getByGroupId($gid);
  4742. foreach ($members as $member) {
  4743. $cid = $member['id'];
  4744. foreach ($users as $user) {
  4745. $found = ($user['cid'] == $cid ? true : false);
  4746. }
  4747. if (!isset($found) || !$found) {
  4748. Group::removeMemberByName($uid, $name, $cid);
  4749. }
  4750. }
  4751. // add members
  4752. $erroraddinguser = false;
  4753. $errorusers = [];
  4754. foreach ($users as $user) {
  4755. $cid = $user['cid'];
  4756. // check if user really exists as contact
  4757. $contact = q(
  4758. "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
  4759. intval($cid),
  4760. intval($uid)
  4761. );
  4762. if (count($contact)) {
  4763. Group::addMember($gid, $cid);
  4764. } else {
  4765. $erroraddinguser = true;
  4766. $errorusers[] = $cid;
  4767. }
  4768. }
  4769. // return success message incl. missing users in array
  4770. $status = ($erroraddinguser ? "missing user" : "ok");
  4771. $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
  4772. return api_format_data("group_update", $type, ['result' => $success]);
  4773. }
  4774. api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
  4775. /**
  4776. * Update information about a group.
  4777. *
  4778. * @param string $type Return type (atom, rss, xml, json)
  4779. *
  4780. * @return array|string
  4781. * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
  4782. */
  4783. function api_lists_update($type)
  4784. {
  4785. $a = \get_app();
  4786. if (api_user() === false) {
  4787. throw new ForbiddenException();
  4788. }
  4789. // params
  4790. $user_info = api_get_user($a);
  4791. $gid = defaults($_REQUEST, 'list_id', 0);
  4792. $name = defaults($_REQUEST, 'name', "");
  4793. $uid = $user_info['uid'];
  4794. // error if no gid specified
  4795. if ($gid == 0) {
  4796. throw new BadRequestException('gid not specified');
  4797. }
  4798. // get data of the specified group id
  4799. $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
  4800. // error message if specified gid is not in database
  4801. if (!$group) {
  4802. throw new BadRequestException('gid not available');
  4803. }
  4804. if (Group::update($gid, $name)) {
  4805. $list = [
  4806. 'name' => $name,
  4807. 'id' => intval($gid),
  4808. 'id_str' => (string) $gid,
  4809. 'user' => $user_info
  4810. ];
  4811. return api_format_data("lists", $type, ['lists' => $list]);
  4812. }
  4813. }
  4814. api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
  4815. /**
  4816. *
  4817. * @param string $type Return type (atom, rss, xml, json)
  4818. *
  4819. * @return array|string
  4820. */
  4821. function api_friendica_activity($type)
  4822. {
  4823. $a = \get_app();
  4824. if (api_user() === false) {
  4825. throw new ForbiddenException();
  4826. }
  4827. $verb = strtolower($a->argv[3]);
  4828. $verb = preg_replace("|\..*$|", "", $verb);
  4829. $id = defaults($_REQUEST, 'id', 0);
  4830. $res = Item::performLike($id, $verb);
  4831. if ($res) {
  4832. if ($type == "xml") {
  4833. $ok = "true";
  4834. } else {
  4835. $ok = "ok";
  4836. }
  4837. return api_format_data('ok', $type, ['ok' => $ok]);
  4838. } else {
  4839. throw new BadRequestException('Error adding activity');
  4840. }
  4841. }
  4842. /// @TODO move to top of file or somewhere better
  4843. api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
  4844. api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
  4845. api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
  4846. api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
  4847. api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
  4848. api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
  4849. api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
  4850. api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
  4851. api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
  4852. api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
  4853. /**
  4854. * @brief Returns notifications
  4855. *
  4856. * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  4857. * @return string|array
  4858. */
  4859. function api_friendica_notification($type)
  4860. {
  4861. $a = \get_app();
  4862. if (api_user() === false) {
  4863. throw new ForbiddenException();
  4864. }
  4865. if ($a->argc!==3) {
  4866. throw new BadRequestException("Invalid argument count");
  4867. }
  4868. $nm = new NotificationsManager();
  4869. $notes = $nm->getAll([], "+seen -date", 50);
  4870. if ($type == "xml") {
  4871. $xmlnotes = [];
  4872. if (!empty($notes)) {
  4873. foreach ($notes as $note) {
  4874. $xmlnotes[] = ["@attributes" => $note];
  4875. }
  4876. }
  4877. $notes = $xmlnotes;
  4878. }
  4879. return api_format_data("notes", $type, ['note' => $notes]);
  4880. }
  4881. /**
  4882. * POST request with 'id' param as notification id
  4883. *
  4884. * @brief Set notification as seen and returns associated item (if possible)
  4885. *
  4886. * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  4887. * @return string|array
  4888. */
  4889. function api_friendica_notification_seen($type)
  4890. {
  4891. $a = \get_app();
  4892. $user_info = api_get_user($a);
  4893. if (api_user() === false || $user_info === false) {
  4894. throw new ForbiddenException();
  4895. }
  4896. if ($a->argc!==4) {
  4897. throw new BadRequestException("Invalid argument count");
  4898. }
  4899. $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
  4900. $nm = new NotificationsManager();
  4901. $note = $nm->getByID($id);
  4902. if (is_null($note)) {
  4903. throw new BadRequestException("Invalid argument");
  4904. }
  4905. $nm->setSeen($note);
  4906. if ($note['otype']=='item') {
  4907. // would be really better with an ItemsManager and $im->getByID() :-P
  4908. $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
  4909. if (DBA::isResult($item)) {
  4910. // we found the item, return it to the user
  4911. $ret = api_format_items([$item], $user_info, false, $type);
  4912. $data = ['status' => $ret];
  4913. return api_format_data("status", $type, $data);
  4914. }
  4915. // the item can't be found, but we set the note as seen, so we count this as a success
  4916. }
  4917. return api_format_data('result', $type, ['result' => "success"]);
  4918. }
  4919. /// @TODO move to top of file or somewhere better
  4920. api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
  4921. api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
  4922. /**
  4923. * @brief update a direct_message to seen state
  4924. *
  4925. * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  4926. * @return string|array (success result=ok, error result=error with error message)
  4927. */
  4928. function api_friendica_direct_messages_setseen($type)
  4929. {
  4930. $a = \get_app();
  4931. if (api_user() === false) {
  4932. throw new ForbiddenException();
  4933. }
  4934. // params
  4935. $user_info = api_get_user($a);
  4936. $uid = $user_info['uid'];
  4937. $id = defaults($_REQUEST, 'id', 0);
  4938. // return error if id is zero
  4939. if ($id == "") {
  4940. $answer = ['result' => 'error', 'message' => 'message id not specified'];
  4941. return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
  4942. }
  4943. // error message if specified id is not in database
  4944. if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
  4945. $answer = ['result' => 'error', 'message' => 'message id not in database'];
  4946. return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
  4947. }
  4948. // update seen indicator
  4949. $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
  4950. if ($result) {
  4951. // return success
  4952. $answer = ['result' => 'ok', 'message' => 'message set to seen'];
  4953. return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
  4954. } else {
  4955. $answer = ['result' => 'error', 'message' => 'unknown error'];
  4956. return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
  4957. }
  4958. }
  4959. /// @TODO move to top of file or somewhere better
  4960. api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
  4961. /**
  4962. * @brief search for direct_messages containing a searchstring through api
  4963. *
  4964. * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  4965. * @param string $box
  4966. * @return string|array (success: success=true if found and search_result contains found messages,
  4967. * success=false if nothing was found, search_result='nothing found',
  4968. * error: result=error with error message)
  4969. */
  4970. function api_friendica_direct_messages_search($type, $box = "")
  4971. {
  4972. $a = \get_app();
  4973. if (api_user() === false) {
  4974. throw new ForbiddenException();
  4975. }
  4976. // params
  4977. $user_info = api_get_user($a);
  4978. $searchstring = defaults($_REQUEST, 'searchstring', "");
  4979. $uid = $user_info['uid'];
  4980. // error if no searchstring specified
  4981. if ($searchstring == "") {
  4982. $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
  4983. return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
  4984. }
  4985. // get data for the specified searchstring
  4986. $r = q(
  4987. "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND `body` LIKE '%s' ORDER BY `mail`.`id` DESC",
  4988. intval($uid),
  4989. DBA::escape('%'.$searchstring.'%')
  4990. );
  4991. $profile_url = $user_info["url"];
  4992. // message if nothing was found
  4993. if (!DBA::isResult($r)) {
  4994. $success = ['success' => false, 'search_results' => 'problem with query'];
  4995. } elseif (count($r) == 0) {
  4996. $success = ['success' => false, 'search_results' => 'nothing found'];
  4997. } else {
  4998. $ret = [];
  4999. foreach ($r as $item) {
  5000. if ($box == "inbox" || $item['from-url'] != $profile_url) {
  5001. $recipient = $user_info;
  5002. $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
  5003. } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
  5004. $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
  5005. $sender = $user_info;
  5006. }
  5007. if (isset($recipient) && isset($sender)) {
  5008. $ret[] = api_format_messages($item, $recipient, $sender);
  5009. }
  5010. }
  5011. $success = ['success' => true, 'search_results' => $ret];
  5012. }
  5013. return api_format_data("direct_message_search", $type, ['$result' => $success]);
  5014. }
  5015. /// @TODO move to top of file or somewhere better
  5016. api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
  5017. /**
  5018. * @brief return data of all the profiles a user has to the client
  5019. *
  5020. * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  5021. * @return string|array
  5022. */
  5023. function api_friendica_profile_show($type)
  5024. {
  5025. $a = \get_app();
  5026. if (api_user() === false) {
  5027. throw new ForbiddenException();
  5028. }
  5029. // input params
  5030. $profile_id = defaults($_REQUEST, 'profile_id', 0);
  5031. // retrieve general information about profiles for user
  5032. $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
  5033. $directory = Config::get('system', 'directory');
  5034. // get data of the specified profile id or all profiles of the user if not specified
  5035. if ($profile_id != 0) {
  5036. $r = q(
  5037. "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
  5038. intval(api_user()),
  5039. intval($profile_id)
  5040. );
  5041. // error message if specified gid is not in database
  5042. if (!DBA::isResult($r)) {
  5043. throw new BadRequestException("profile_id not available");
  5044. }
  5045. } else {
  5046. $r = q(
  5047. "SELECT * FROM `profile` WHERE `uid` = %d",
  5048. intval(api_user())
  5049. );
  5050. }
  5051. // loop through all returned profiles and retrieve data and users
  5052. $k = 0;
  5053. $profiles = [];
  5054. foreach ($r as $rr) {
  5055. $profile = api_format_items_profiles($rr);
  5056. // select all users from contact table, loop and prepare standard return for user data
  5057. $users = [];
  5058. $nurls = q(
  5059. "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
  5060. intval(api_user()),
  5061. intval($rr['id'])
  5062. );
  5063. foreach ($nurls as $nurl) {
  5064. $user = api_get_user($a, $nurl['nurl']);
  5065. ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
  5066. }
  5067. $profile['users'] = $users;
  5068. // add prepared profile data to array for final return
  5069. if ($type == "xml") {
  5070. $profiles[$k++ . ":profile"] = $profile;
  5071. } else {
  5072. $profiles[] = $profile;
  5073. }
  5074. }
  5075. // return settings, authenticated user and profiles data
  5076. $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
  5077. $result = ['multi_profiles' => $multi_profiles ? true : false,
  5078. 'global_dir' => $directory,
  5079. 'friendica_owner' => api_get_user($a, $self['nurl']),
  5080. 'profiles' => $profiles];
  5081. return api_format_data("friendica_profiles", $type, ['$result' => $result]);
  5082. }
  5083. api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
  5084. /**
  5085. * Returns a list of saved searches.
  5086. *
  5087. * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
  5088. *
  5089. * @param string $type Return format: json or xml
  5090. *
  5091. * @return string|array
  5092. */
  5093. function api_saved_searches_list($type)
  5094. {
  5095. $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
  5096. $result = [];
  5097. while ($term = $terms->fetch()) {
  5098. $result[] = [
  5099. 'created_at' => api_date(time()),
  5100. 'id' => intval($term['id']),
  5101. 'id_str' => $term['id'],
  5102. 'name' => $term['term'],
  5103. 'position' => null,
  5104. 'query' => $term['term']
  5105. ];
  5106. }
  5107. DBA::close($terms);
  5108. return api_format_data("terms", $type, ['terms' => $result]);
  5109. }
  5110. /// @TODO move to top of file or somewhere better
  5111. api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
  5112. /*
  5113. * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
  5114. *
  5115. * @brief Number of comments
  5116. *
  5117. * @param object $data [Status, Status]
  5118. *
  5119. * @return void
  5120. */
  5121. function bindComments(&$data)
  5122. {
  5123. if (count($data) == 0) {
  5124. return;
  5125. }
  5126. $ids = [];
  5127. $comments = [];
  5128. foreach ($data as $item) {
  5129. $ids[] = $item['id'];
  5130. }
  5131. $idStr = DBA::escape(implode(', ', $ids));
  5132. $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
  5133. $items = DBA::p($sql, 0, GRAVITY_COMMENT);
  5134. $itemsData = DBA::toArray($items);
  5135. foreach ($itemsData as $item) {
  5136. $comments[$item['parent']] = $item['comments'];
  5137. }
  5138. foreach ($data as $idx => $item) {
  5139. $id = $item['id'];
  5140. $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
  5141. }
  5142. }
  5143. /*
  5144. @TODO Maybe open to implement?
  5145. To.Do:
  5146. [pagename] => api/1.1/statuses/lookup.json
  5147. [id] => 605138389168451584
  5148. [include_cards] => true
  5149. [cards_platform] => Android-12
  5150. [include_entities] => true
  5151. [include_my_retweet] => 1
  5152. [include_rts] => 1
  5153. [include_reply_count] => true
  5154. [include_descendent_reply_count] => true
  5155. (?)
  5156. Not implemented by now:
  5157. statuses/retweets_of_me
  5158. friendships/create
  5159. friendships/destroy
  5160. friendships/exists
  5161. friendships/show
  5162. account/update_location
  5163. account/update_profile_background_image
  5164. blocks/create
  5165. blocks/destroy
  5166. friendica/profile/update
  5167. friendica/profile/create
  5168. friendica/profile/delete
  5169. Not implemented in status.net:
  5170. statuses/retweeted_to_me
  5171. statuses/retweeted_by_me
  5172. direct_messages/destroy
  5173. account/end_session
  5174. account/update_delivery_device
  5175. notifications/follow
  5176. notifications/leave
  5177. blocks/exists
  5178. blocks/blocking
  5179. lists
  5180. */