Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6075 lines
173KB

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