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.

6023 lines
171KB

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