3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\Content\ContactSelector;
11 use Friendica\Content\Feature;
12 use Friendica\Content\Text\BBCode;
13 use Friendica\Content\Text\HTML;
14 use Friendica\Core\Addon;
15 use Friendica\Core\Config;
16 use Friendica\Core\L10n;
17 use Friendica\Core\NotificationsManager;
18 use Friendica\Core\PConfig;
19 use Friendica\Core\Protocol;
20 use Friendica\Core\System;
21 use Friendica\Core\Worker;
22 use Friendica\Database\DBA;
23 use Friendica\Model\Contact;
24 use Friendica\Model\Group;
25 use Friendica\Model\Item;
26 use Friendica\Model\Mail;
27 use Friendica\Model\Photo;
28 use Friendica\Model\User;
29 use Friendica\Network\FKOAuth1;
30 use Friendica\Network\HTTPException;
31 use Friendica\Network\HTTPException\BadRequestException;
32 use Friendica\Network\HTTPException\ForbiddenException;
33 use Friendica\Network\HTTPException\InternalServerErrorException;
34 use Friendica\Network\HTTPException\MethodNotAllowedException;
35 use Friendica\Network\HTTPException\NotFoundException;
36 use Friendica\Network\HTTPException\NotImplementedException;
37 use Friendica\Network\HTTPException\TooManyRequestsException;
38 use Friendica\Network\HTTPException\UnauthorizedException;
39 use Friendica\Object\Image;
40 use Friendica\Protocol\Diaspora;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\Network;
43 use Friendica\Util\Proxy as ProxyUtils;
44 use Friendica\Util\XML;
46 require_once 'include/conversation.php';
47 require_once 'mod/share.php';
48 require_once 'mod/item.php';
49 require_once 'include/security.php';
50 require_once 'mod/wall_upload.php';
52 define('API_METHOD_ANY', '*');
53 define('API_METHOD_GET', 'GET');
54 define('API_METHOD_POST', 'POST,PUT');
55 define('API_METHOD_DELETE', 'POST,DELETE');
61 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
62 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
63 * into a page, and visitors will post something without noticing it).
65 * @brief Auth API user
69 if (x($_SESSION, 'allow_api')) {
77 * Clients can send 'source' parameter to be show in post metadata
78 * as "sent via <source>".
79 * Some clients doesn't send a source param, we support ones we know
82 * @brief Get source name from API client
85 * Client source name, default to "api" if unset/unknown
89 if (requestdata('source')) {
90 return requestdata('source');
93 // Support for known clients that doesn't send a source name
94 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
95 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
99 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
101 logger("Empty user-agent", LOGGER_DEBUG);
108 * @brief Format date for API
110 * @param string $str Source date, as UTC
111 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
113 function api_date($str)
115 // Wed May 23 06:01:13 +0000 2007
116 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
120 * Register a function to be the endpoint for defined API path.
122 * @brief Register API endpoint
124 * @param string $path API URL path, relative to System::baseUrl()
125 * @param string $func Function name to call on path request
126 * @param bool $auth API need logged user
127 * @param string $method HTTP method reqiured to call this endpoint.
128 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
129 * Default to API_METHOD_ANY
131 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
141 // Workaround for hotot
142 $path = str_replace("api/", "api/1.1/", $path);
152 * Log in user via OAuth1 or Simple HTTP Auth.
153 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
155 * @brief Login API user
157 * @param object $a App
158 * @hook 'authenticate'
160 * 'username' => username from login form
161 * 'password' => password from login form
162 * 'authenticated' => return status,
163 * 'user_record' => return authenticated user record
165 * array $user logged user record
167 function api_login(App $a)
169 $oauth1 = new FKOAuth1();
172 $request = OAuthRequest::from_request();
173 list($consumer, $token) = $oauth1->verify_request($request);
174 if (!is_null($token)) {
175 $oauth1->loginUser($token->uid);
176 Addon::callHooks('logged_in', $a->user);
179 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
180 var_dump($consumer, $token);
182 } catch (Exception $e) {
186 // workaround for HTTP-auth in CGI mode
187 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
188 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
189 if (strlen($userpass)) {
190 list($name, $password) = explode(':', $userpass);
191 $_SERVER['PHP_AUTH_USER'] = $name;
192 $_SERVER['PHP_AUTH_PW'] = $password;
196 if (!x($_SERVER, 'PHP_AUTH_USER')) {
197 logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
198 header('WWW-Authenticate: Basic realm="Friendica"');
199 throw new UnauthorizedException("This API requires login");
202 $user = defaults($_SERVER, 'PHP_AUTH_USER', '');
203 $password = defaults($_SERVER, 'PHP_AUTH_PW', '');
205 // allow "user@server" login (but ignore 'server' part)
206 $at = strstr($user, "@", true);
211 // next code from mod/auth.php. needs better solution
215 'username' => trim($user),
216 'password' => trim($password),
217 'authenticated' => 0,
218 'user_record' => null,
222 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
223 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
224 * and later addons should not interfere with an earlier one that succeeded.
226 Addon::callHooks('authenticate', $addon_auth);
228 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
229 $record = $addon_auth['user_record'];
231 $user_id = User::authenticate(trim($user), trim($password));
232 if ($user_id !== false) {
233 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
237 if (!DBA::isResult($record)) {
238 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
239 header('WWW-Authenticate: Basic realm="Friendica"');
240 //header('HTTP/1.0 401 Unauthorized');
241 //die('This api requires login');
242 throw new UnauthorizedException("This API requires login");
245 authenticate_success($record);
247 $_SESSION["allow_api"] = true;
249 Addon::callHooks('logged_in', $a->user);
253 * API endpoints can define which HTTP method to accept when called.
254 * This function check the current HTTP method agains endpoint
257 * @brief Check HTTP method of called API
259 * @param string $method Required methods, uppercase, separated by comma
262 function api_check_method($method)
264 if ($method == "*") {
267 return (stripos($method, defaults($_SERVER, 'REQUEST_METHOD', 'GET')) !== false);
271 * Authenticate user, call registered API function, set HTTP headers
273 * @brief Main API entry point
275 * @param object $a App
276 * @return string|array API call result
278 function api_call(App $a)
280 global $API, $called_api;
283 if (strpos($a->query_string, ".xml") > 0) {
286 if (strpos($a->query_string, ".json") > 0) {
289 if (strpos($a->query_string, ".rss") > 0) {
292 if (strpos($a->query_string, ".atom") > 0) {
297 foreach ($API as $p => $info) {
298 if (strpos($a->query_string, $p) === 0) {
299 if (!api_check_method($info['method'])) {
300 throw new MethodNotAllowedException();
303 $called_api = explode("/", $p);
304 //unset($_SERVER['PHP_AUTH_USER']);
306 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
307 if (!empty($info['auth']) && api_user() === false) {
311 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
312 logger('API parameters: ' . print_r($_REQUEST, true));
314 $stamp = microtime(true);
315 $return = call_user_func($info['func'], $type);
316 $duration = (float) (microtime(true) - $stamp);
317 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
319 if (Config::get("system", "profiler")) {
320 $duration = microtime(true)-$a->performance["start"];
322 /// @TODO round() really everywhere?
324 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
325 "Database: %s/%s, Cache %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
326 round($a->performance["database"] - $a->performance["database_write"], 3),
327 round($a->performance["database_write"], 3),
328 round($a->performance["cache"], 3),
329 round($a->performance["cache_write"], 3),
330 round($a->performance["network"], 2),
331 round($a->performance["file"], 2),
332 round($duration - ($a->performance["database"]
333 + $a->performance["cache"] + $a->performance["cache_write"]
334 + $a->performance["network"] + $a->performance["file"]), 2),
340 if (Config::get("rendertime", "callstack")) {
341 $o = "Database Read:\n";
342 foreach ($a->callstack["database"] as $func => $time) {
343 $time = round($time, 3);
345 $o .= $func . ": " . $time . "\n";
348 $o .= "\nDatabase Write:\n";
349 foreach ($a->callstack["database_write"] as $func => $time) {
350 $time = round($time, 3);
352 $o .= $func . ": " . $time . "\n";
356 $o = "Cache Read:\n";
357 foreach ($a->callstack["cache"] as $func => $time) {
358 $time = round($time, 3);
360 $o .= $func . ": " . $time . "\n";
363 $o .= "\nCache Write:\n";
364 foreach ($a->callstack["cache_write"] as $func => $time) {
365 $time = round($time, 3);
367 $o .= $func . ": " . $time . "\n";
371 $o .= "\nNetwork:\n";
372 foreach ($a->callstack["network"] as $func => $time) {
373 $time = round($time, 3);
375 $o .= $func . ": " . $time . "\n";
378 logger($o, LOGGER_DEBUG);
382 if (false === $return) {
384 * api function returned false withour throw an
385 * exception. This should not happend, throw a 500
387 throw new InternalServerErrorException();
392 header("Content-Type: text/xml");
395 header("Content-Type: application/json");
396 $json = json_encode(end($return));
397 if (x($_GET, 'callback')) {
398 $json = $_GET['callback'] . "(" . $json . ")";
403 header("Content-Type: application/rss+xml");
404 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
407 header("Content-Type: application/atom+xml");
408 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
415 logger('API call not implemented: ' . $a->query_string);
416 throw new NotImplementedException();
417 } catch (HTTPException $e) {
418 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
419 return api_error($type, $e);
424 * @brief Format API error string
426 * @param string $type Return type (xml, json, rss, as)
427 * @param object $e HTTPException Error object
428 * @return string|array error message formatted as $type
430 function api_error($type, $e)
434 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
435 /// @TODO: https://dev.twitter.com/overview/api/response-codes
437 $error = ["error" => $error,
438 "code" => $e->httpcode . " " . $e->httpdesc,
439 "request" => $a->query_string];
441 $return = api_format_data('status', $type, ['status' => $error]);
445 header("Content-Type: text/xml");
448 header("Content-Type: application/json");
449 $return = json_encode($return);
452 header("Content-Type: application/rss+xml");
455 header("Content-Type: application/atom+xml");
463 * @brief Set values for RSS template
466 * @param array $arr Array to be passed to template
467 * @param array $user_info User info
469 * @todo find proper type-hints
471 function api_rss_extra(App $a, $arr, $user_info)
473 if (is_null($user_info)) {
474 $user_info = api_get_user($a);
477 $arr['$user'] = $user_info;
479 'alternate' => $user_info['url'],
480 'self' => System::baseUrl() . "/" . $a->query_string,
481 'base' => System::baseUrl(),
482 'updated' => api_date(null),
483 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
484 'language' => $user_info['lang'],
485 'logo' => System::baseUrl() . "/images/friendica-32.png",
493 * @brief Unique contact to contact url.
495 * @param int $id Contact id
496 * @return bool|string
497 * Contact url or False if contact id is unknown
499 function api_unique_id_to_nurl($id)
501 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
503 if (DBA::isResult($r)) {
511 * @brief Get user info array.
513 * @param object $a App
514 * @param int|string $contact_id Contact ID or URL
516 function api_get_user(App $a, $contact_id = null)
524 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
526 // Searching for contact URL
527 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
528 $user = DBA::escape(normalise_link($contact_id));
530 $extra_query = "AND `contact`.`nurl` = '%s' ";
531 if (api_user() !== false) {
532 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
536 // Searching for contact id with uid = 0
537 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
538 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
541 throw new BadRequestException("User ID ".$contact_id." not found.");
545 $extra_query = "AND `contact`.`nurl` = '%s' ";
546 if (api_user() !== false) {
547 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
551 if (is_null($user) && x($_GET, 'user_id')) {
552 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
555 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
559 $extra_query = "AND `contact`.`nurl` = '%s' ";
560 if (api_user() !== false) {
561 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
564 if (is_null($user) && x($_GET, 'screen_name')) {
565 $user = DBA::escape($_GET['screen_name']);
566 $extra_query = "AND `contact`.`nick` = '%s' ";
567 if (api_user() !== false) {
568 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
572 if (is_null($user) && x($_GET, 'profileurl')) {
573 $user = DBA::escape(normalise_link($_GET['profileurl']));
574 $extra_query = "AND `contact`.`nurl` = '%s' ";
575 if (api_user() !== false) {
576 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
580 // $called_api is the API path exploded on / and is expected to have at least 2 elements
581 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
582 $argid = count($called_api);
583 if (!empty($a->argv[$argid])) {
584 list($user, $null) = explode(".", $a->argv[$argid]);
586 if (is_numeric($user)) {
587 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
591 $extra_query = "AND `contact`.`nurl` = '%s' ";
592 if (api_user() !== false) {
593 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
597 $user = DBA::escape($user);
598 $extra_query = "AND `contact`.`nick` = '%s' ";
599 if (api_user() !== false) {
600 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
605 logger("api_get_user: user ".$user, LOGGER_DEBUG);
608 if (api_user() === false) {
612 $user = $_SESSION['uid'];
613 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
617 logger('api_user: ' . $extra_query . ', user: ' . $user);
621 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
627 // Selecting the id by priority, friendica first
628 if (is_array($uinfo)) {
629 api_best_nickname($uinfo);
632 // if the contact wasn't found, fetch it from the contacts with uid = 0
633 if (!DBA::isResult($uinfo)) {
635 throw new BadRequestException("User not found.");
638 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => normalise_link($url)]);
640 if (DBA::isResult($contact)) {
641 $network_name = ContactSelector::networkToName($contact['network'], $contact['url']);
643 // If no nick where given, extract it from the address
644 if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
645 $contact['nick'] = api_get_nick($contact["url"]);
649 'id' => $contact["id"],
650 'id_str' => (string) $contact["id"],
651 'name' => $contact["name"],
652 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
653 'location' => ($contact["location"] != "") ? $contact["location"] : $network_name,
654 'description' => $contact["about"],
655 'profile_image_url' => $contact["micro"],
656 'profile_image_url_https' => $contact["micro"],
657 'profile_image_url_profile_size' => $contact["thumb"],
658 'profile_image_url_large' => $contact["photo"],
659 'url' => $contact["url"],
660 'protected' => false,
661 'followers_count' => 0,
662 'friends_count' => 0,
664 'created_at' => api_date($contact["created"]),
665 'favourites_count' => 0,
667 'time_zone' => 'UTC',
668 'geo_enabled' => false,
670 'statuses_count' => 0,
672 'contributors_enabled' => false,
673 'is_translator' => false,
674 'is_translation_enabled' => false,
675 'following' => false,
676 'follow_request_sent' => false,
677 'statusnet_blocking' => false,
678 'notifications' => false,
679 'statusnet_profile_url' => $contact["url"],
681 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
682 'pid' => Contact::getIdForURL($contact["url"], 0, true),
684 'network' => $contact["network"],
689 throw new BadRequestException("User ".$url." not found.");
693 if ($uinfo[0]['self']) {
694 if ($uinfo[0]['network'] == "") {
695 $uinfo[0]['network'] = Protocol::DFRN;
698 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
699 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
706 // Add a nick if it isn't present there
707 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
708 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
711 $network_name = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
713 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
715 if (!empty($profile['about'])) {
716 $description = $profile['about'];
718 $description = $uinfo[0]["about"];
721 if (!empty($usr['default-location'])) {
722 $location = $usr['default-location'];
723 } elseif (!empty($uinfo[0]["location"])) {
724 $location = $uinfo[0]["location"];
726 $location = $network_name;
730 'id' => intval($pcontact_id),
731 'id_str' => (string) intval($pcontact_id),
732 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
733 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
734 'location' => $location,
735 'description' => $description,
736 'profile_image_url' => $uinfo[0]['micro'],
737 'profile_image_url_https' => $uinfo[0]['micro'],
738 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
739 'profile_image_url_large' => $uinfo[0]["photo"],
740 'url' => $uinfo[0]['url'],
741 'protected' => false,
742 'followers_count' => intval($countfollowers),
743 'friends_count' => intval($countfriends),
745 'created_at' => api_date($uinfo[0]['created']),
746 'favourites_count' => intval($starred),
748 'time_zone' => 'UTC',
749 'geo_enabled' => false,
751 'statuses_count' => intval($countitems),
753 'contributors_enabled' => false,
754 'is_translator' => false,
755 'is_translation_enabled' => false,
756 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
757 'follow_request_sent' => false,
758 'statusnet_blocking' => false,
759 'notifications' => false,
761 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
762 'statusnet_profile_url' => $uinfo[0]['url'],
763 'uid' => intval($uinfo[0]['uid']),
764 'cid' => intval($uinfo[0]['cid']),
765 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
766 'self' => $uinfo[0]['self'],
767 'network' => $uinfo[0]['network'],
770 // If this is a local user and it uses Frio, we can get its color preferences.
772 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
773 if ($theme_info['theme'] === 'frio') {
774 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
776 if ($schema && ($schema != '---')) {
777 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
778 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
779 require_once $schemefile;
782 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
783 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
784 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
786 if (empty($nav_bg)) {
789 if (empty($link_color)) {
790 $link_color = "#6fdbe8";
792 if (empty($bgcolor)) {
793 $bgcolor = "#ededed";
796 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
797 $ret['profile_link_color'] = str_replace('#', '', $link_color);
798 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
806 * @brief return api-formatted array for item's author and owner
808 * @param object $a App
809 * @param array $item item from db
810 * @return array(array:author, array:owner)
812 function api_item_get_user(App $a, $item)
814 $status_user = api_get_user($a, defaults($item, 'author-id', null));
816 $status_user["protected"] = defaults($item, 'private', 0);
818 if (defaults($item, 'thr-parent', '') == defaults($item, 'uri', '')) {
819 $owner_user = api_get_user($a, defaults($item, 'author-id', null));
821 $owner_user = $status_user;
824 return ([$status_user, $owner_user]);
828 * @brief walks recursively through an array with the possibility to change value and key
830 * @param array $array The array to walk through
831 * @param string $callback The callback function
833 * @return array the transformed array
835 function api_walk_recursive(array &$array, callable $callback)
839 foreach ($array as $k => $v) {
841 if ($callback($v, $k)) {
842 $new_array[$k] = api_walk_recursive($v, $callback);
845 if ($callback($v, $k)) {
856 * @brief Callback function to transform the array in an array that can be transformed in a XML file
858 * @param mixed $item Array item value
859 * @param string $key Array key
861 * @return boolean Should the array item be deleted?
863 function api_reformat_xml(&$item, &$key)
865 if (is_bool($item)) {
866 $item = ($item ? "true" : "false");
869 if (substr($key, 0, 10) == "statusnet_") {
870 $key = "statusnet:".substr($key, 10);
871 } elseif (substr($key, 0, 10) == "friendica_") {
872 $key = "friendica:".substr($key, 10);
874 /// @TODO old-lost code?
876 // $key = "default:".$key;
882 * @brief Creates the XML from a JSON style array
884 * @param array $data JSON style array
885 * @param string $root_element Name of the root element
887 * @return string The XML data
889 function api_create_xml(array $data, $root_element)
891 $childname = key($data);
892 $data2 = array_pop($data);
894 $namespaces = ["" => "http://api.twitter.com",
895 "statusnet" => "http://status.net/schema/api/1/",
896 "friendica" => "http://friendi.ca/schema/api/1/",
897 "georss" => "http://www.georss.org/georss"];
899 /// @todo Auto detection of needed namespaces
900 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
904 if (is_array($data2)) {
906 api_walk_recursive($data2, "api_reformat_xml");
912 foreach ($data2 as $item) {
913 $data4[$i++ . ":" . $childname] = $item;
920 $data3 = [$root_element => $data2];
922 $ret = XML::fromArray($data3, $xml, false, $namespaces);
927 * @brief Formats the data according to the data type
929 * @param string $root_element Name of the root element
930 * @param string $type Return type (atom, rss, xml, json)
931 * @param array $data JSON style array
933 * @return (string|array) XML data or JSON data
935 function api_format_data($root_element, $type, $data)
941 $ret = api_create_xml($data, $root_element);
957 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
958 * returns a 401 status code and an error message if not.
959 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
961 * @param string $type Return type (atom, rss, xml, json)
963 function api_account_verify_credentials($type)
968 if (api_user() === false) {
969 throw new ForbiddenException();
972 unset($_REQUEST["user_id"]);
973 unset($_GET["user_id"]);
975 unset($_REQUEST["screen_name"]);
976 unset($_GET["screen_name"]);
978 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
980 $user_info = api_get_user($a);
982 // "verified" isn't used here in the standard
983 unset($user_info["verified"]);
985 // - Adding last status
987 $user_info["status"] = api_status_show("raw");
988 if (!count($user_info["status"])) {
989 unset($user_info["status"]);
991 unset($user_info["status"]["user"]);
995 // "uid" and "self" are only needed for some internal stuff, so remove it from here
996 unset($user_info["uid"]);
997 unset($user_info["self"]);
999 return api_format_data("user", $type, ['user' => $user_info]);
1002 /// @TODO move to top of file or somewhere better
1003 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1006 * Get data from $_POST or $_GET
1010 function requestdata($k)
1012 if (x($_POST, $k)) {
1022 * Deprecated function to upload media.
1024 * @param string $type Return type (atom, rss, xml, json)
1026 * @return array|string
1028 function api_statuses_mediap($type)
1032 if (api_user() === false) {
1033 logger('api_statuses_update: no user');
1034 throw new ForbiddenException();
1036 $user_info = api_get_user($a);
1038 $_REQUEST['profile_uid'] = api_user();
1039 $_REQUEST['api_source'] = true;
1040 $txt = requestdata('status');
1041 /// @TODO old-lost code?
1042 //$txt = urldecode(requestdata('status'));
1044 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1045 $txt = html2bb_video($txt);
1046 $config = HTMLPurifier_Config::createDefault();
1047 $config->set('Cache.DefinitionImpl', null);
1048 $purifier = new HTMLPurifier($config);
1049 $txt = $purifier->purify($txt);
1051 $txt = HTML::toBBCode($txt);
1053 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1055 $picture = wall_upload_post($a, false);
1057 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1058 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1061 // this should output the last post (the one we just posted).
1062 return api_status_show($type);
1065 /// @TODO move this to top of file or somewhere better!
1066 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1069 * Updates the user’s current status.
1071 * @param string $type Return type (atom, rss, xml, json)
1073 * @return array|string
1074 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1076 function api_statuses_update($type)
1081 if (api_user() === false) {
1082 logger('api_statuses_update: no user');
1083 throw new ForbiddenException();
1088 // convert $_POST array items to the form we use for web posts.
1089 if (requestdata('htmlstatus')) {
1090 $txt = requestdata('htmlstatus');
1091 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1092 $txt = html2bb_video($txt);
1094 $config = HTMLPurifier_Config::createDefault();
1095 $config->set('Cache.DefinitionImpl', null);
1097 $purifier = new HTMLPurifier($config);
1098 $txt = $purifier->purify($txt);
1100 $_REQUEST['body'] = HTML::toBBCode($txt);
1103 $_REQUEST['body'] = requestdata('status');
1106 $_REQUEST['title'] = requestdata('title');
1108 $parent = requestdata('in_reply_to_status_id');
1110 // Twidere sends "-1" if it is no reply ...
1111 if ($parent == -1) {
1115 if (ctype_digit($parent)) {
1116 $_REQUEST['parent'] = $parent;
1118 $_REQUEST['parent_uri'] = $parent;
1121 if (requestdata('lat') && requestdata('long')) {
1122 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1124 $_REQUEST['profile_uid'] = api_user();
1127 // Check for throttling (maximum posts per day, week and month)
1128 $throttle_day = Config::get('system', 'throttle_limit_day');
1129 if ($throttle_day > 0) {
1130 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1132 $condition = ["`uid` = ? AND `wall` AND `created` > ? AND `id` = `parent`", api_user(), $datefrom];
1133 $posts_day = DBA::count('item', $condition);
1135 if ($posts_day > $throttle_day) {
1136 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1137 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1138 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));
1142 $throttle_week = Config::get('system', 'throttle_limit_week');
1143 if ($throttle_week > 0) {
1144 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1146 $condition = ["`uid` = ? AND `wall` AND `created` > ? AND `id` = `parent`", api_user(), $datefrom];
1147 $posts_week = DBA::count('item', $condition);
1149 if ($posts_week > $throttle_week) {
1150 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1151 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1152 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));
1156 $throttle_month = Config::get('system', 'throttle_limit_month');
1157 if ($throttle_month > 0) {
1158 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1160 $condition = ["`uid` = ? AND `wall` AND `created` > ? AND `id` = `parent`", api_user(), $datefrom];
1161 $posts_month = DBA::count('item', $condition);
1163 if ($posts_month > $throttle_month) {
1164 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1165 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1166 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));
1171 if (x($_FILES, 'media')) {
1172 // upload the image if we have one
1173 $picture = wall_upload_post($a, false);
1174 if (is_array($picture)) {
1175 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1179 // To-Do: Multiple IDs
1180 if (requestdata('media_ids')) {
1182 "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",
1183 intval(requestdata('media_ids')),
1186 if (DBA::isResult($r)) {
1187 $phototypes = Image::supportedTypes();
1188 $ext = $phototypes[$r[0]['type']];
1189 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1190 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1194 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1196 $_REQUEST['api_source'] = true;
1198 if (!x($_REQUEST, "source")) {
1199 $_REQUEST["source"] = api_source();
1202 // call out normal post function
1205 // this should output the last post (the one we just posted).
1206 return api_status_show($type);
1209 /// @TODO move to top of file or somewhere better
1210 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1211 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1214 * Uploads an image to Friendica.
1217 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1219 function api_media_upload()
1223 if (api_user() === false) {
1225 throw new ForbiddenException();
1230 if (!x($_FILES, 'media')) {
1232 throw new BadRequestException("No media.");
1235 $media = wall_upload_post($a, false);
1238 throw new InternalServerErrorException();
1242 $returndata["media_id"] = $media["id"];
1243 $returndata["media_id_string"] = (string)$media["id"];
1244 $returndata["size"] = $media["size"];
1245 $returndata["image"] = ["w" => $media["width"],
1246 "h" => $media["height"],
1247 "image_type" => $media["type"]];
1249 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1251 return ["media" => $returndata];
1254 /// @TODO move to top of file or somewhere better
1255 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1259 * @param string $type Return type (atom, rss, xml, json)
1261 * @return array|string
1263 function api_status_show($type)
1267 $user_info = api_get_user($a);
1269 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1271 if ($type == "raw") {
1272 $privacy_sql = "AND NOT `private`";
1277 // get last public wall message
1278 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1279 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1280 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1282 if (DBA::isResult($lastwall)) {
1283 $in_reply_to = api_in_reply_to($lastwall);
1285 $converted = api_convert_item($lastwall);
1287 if ($type == "xml") {
1288 $geo = "georss:point";
1294 'created_at' => api_date($lastwall['created']),
1295 'id' => intval($lastwall['id']),
1296 'id_str' => (string) $lastwall['id'],
1297 'text' => $converted["text"],
1298 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1299 'truncated' => false,
1300 'in_reply_to_status_id' => $in_reply_to['status_id'],
1301 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1302 'in_reply_to_user_id' => $in_reply_to['user_id'],
1303 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1304 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1305 'user' => $user_info,
1307 'coordinates' => '',
1309 'contributors' => '',
1310 'is_quote_status' => false,
1311 'retweet_count' => 0,
1312 'favorite_count' => 0,
1313 'favorited' => $lastwall['starred'] ? true : false,
1314 'retweeted' => false,
1315 'possibly_sensitive' => false,
1317 'statusnet_html' => $converted["html"],
1318 'statusnet_conversation_id' => $lastwall['parent'],
1319 'external_url' => System::baseUrl() . '/display/' . $lastwall['guid'],
1322 if (count($converted["attachments"]) > 0) {
1323 $status_info["attachments"] = $converted["attachments"];
1326 if (count($converted["entities"]) > 0) {
1327 $status_info["entities"] = $converted["entities"];
1330 if ($status_info["source"] == 'web') {
1331 $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $user_info['url']);
1332 } elseif (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $status_info["source"]) {
1333 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $user_info['url']).')');
1336 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1337 unset($status_info["user"]["uid"]);
1338 unset($status_info["user"]["self"]);
1340 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1342 if ($type == "raw") {
1343 return $status_info;
1346 return api_format_data("statuses", $type, ['status' => $status_info]);
1351 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1352 * The author's most recent status will be returned inline.
1354 * @param string $type Return type (atom, rss, xml, json)
1355 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1357 function api_users_show($type)
1361 $user_info = api_get_user($a);
1363 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1364 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'private' => false];
1365 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1367 if (DBA::isResult($lastwall)) {
1368 $in_reply_to = api_in_reply_to($lastwall);
1370 $converted = api_convert_item($lastwall);
1372 if ($type == "xml") {
1373 $geo = "georss:point";
1378 $user_info['status'] = [
1379 'text' => $converted["text"],
1380 'truncated' => false,
1381 'created_at' => api_date($lastwall['created']),
1382 'in_reply_to_status_id' => $in_reply_to['status_id'],
1383 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1384 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1385 'id' => intval($lastwall['contact-id']),
1386 'id_str' => (string) $lastwall['contact-id'],
1387 'in_reply_to_user_id' => $in_reply_to['user_id'],
1388 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1389 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1391 'favorited' => $lastwall['starred'] ? true : false,
1392 'statusnet_html' => $converted["html"],
1393 'statusnet_conversation_id' => $lastwall['parent'],
1394 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1397 if (count($converted["attachments"]) > 0) {
1398 $user_info["status"]["attachments"] = $converted["attachments"];
1401 if (count($converted["entities"]) > 0) {
1402 $user_info["status"]["entities"] = $converted["entities"];
1405 if ($user_info["status"]["source"] == 'web') {
1406 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $user_info['url']);
1409 if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
1410 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $user_info['url']) . ')');
1414 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1415 unset($user_info["uid"]);
1416 unset($user_info["self"]);
1418 return api_format_data("user", $type, ['user' => $user_info]);
1421 /// @TODO move to top of file or somewhere better
1422 api_register_func('api/users/show', 'api_users_show');
1423 api_register_func('api/externalprofile/show', 'api_users_show');
1426 * Search a public user account.
1428 * @param string $type Return type (atom, rss, xml, json)
1430 * @return array|string
1431 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1433 function api_users_search($type)
1439 if (x($_GET, 'q')) {
1440 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1442 if (!DBA::isResult($r)) {
1443 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1446 if (DBA::isResult($r)) {
1448 foreach ($r as $user) {
1449 $user_info = api_get_user($a, $user["id"]);
1451 if ($type == "xml") {
1452 $userlist[$k++.":user"] = $user_info;
1454 $userlist[] = $user_info;
1457 $userlist = ["users" => $userlist];
1459 throw new BadRequestException("User ".$_GET["q"]." not found.");
1462 throw new BadRequestException("No user specified.");
1465 return api_format_data("users", $type, $userlist);
1468 /// @TODO move to top of file or somewhere better
1469 api_register_func('api/users/search', 'api_users_search');
1472 * Return user objects
1474 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1476 * @param string $type Return format: json or xml
1478 * @return array|string
1479 * @throws NotFoundException if the results are empty.
1481 function api_users_lookup($type)
1485 if (!empty($_REQUEST['user_id'])) {
1486 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1488 $users[] = api_get_user(get_app(), $id);
1493 if (empty($users)) {
1494 throw new NotFoundException;
1497 return api_format_data("users", $type, ['users' => $users]);
1500 /// @TODO move to top of file or somewhere better
1501 api_register_func('api/users/lookup', 'api_users_lookup', true);
1504 * Returns statuses that match a specified query.
1506 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1508 * @param string $type Return format: json, xml, atom, rss
1510 * @return array|string
1511 * @throws BadRequestException if the "q" parameter is missing.
1513 function api_search($type)
1516 $user_info = api_get_user($a);
1518 if (api_user() === false || $user_info === false) {
1519 throw new ForbiddenException();
1524 if (!x($_REQUEST, 'q')) {
1525 throw new BadRequestException("q parameter is required.");
1528 if (x($_REQUEST, 'rpp')) {
1529 $count = $_REQUEST['rpp'];
1530 } elseif (x($_REQUEST, 'count')) {
1531 $count = $_REQUEST['count'];
1536 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1537 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1538 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1540 $start = $page * $count;
1542 $condition = ["`gravity` IN (?, ?) AND `item`.`id` > ?
1543 AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1544 AND `item`.`body` LIKE CONCAT('%',?,'%')",
1545 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, api_user(), $_REQUEST['q']];
1548 $condition[0] .= " AND `item`.`id` <= ?";
1549 $condition[] = $max_id;
1552 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1553 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1555 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1557 return api_format_data("statuses", $type, $data);
1560 /// @TODO move to top of file or somewhere better
1561 api_register_func('api/search/tweets', 'api_search', true);
1562 api_register_func('api/search', 'api_search', true);
1565 * Returns the most recent statuses posted by the user and the users they follow.
1567 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1569 * @param string $type Return type (atom, rss, xml, json)
1571 * @todo Optional parameters
1572 * @todo Add reply info
1574 function api_statuses_home_timeline($type)
1577 $user_info = api_get_user($a);
1579 if (api_user() === false || $user_info === false) {
1580 throw new ForbiddenException();
1583 unset($_REQUEST["user_id"]);
1584 unset($_GET["user_id"]);
1586 unset($_REQUEST["screen_name"]);
1587 unset($_GET["screen_name"]);
1589 // get last network messages
1592 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1593 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1597 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1598 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1599 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1600 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1601 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1603 $start = $page * $count;
1605 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1606 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1609 $condition[0] .= " AND `item`.`id` <= ?";
1610 $condition[] = $max_id;
1612 if ($exclude_replies > 0) {
1613 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1615 if ($conversation_id > 0) {
1616 $condition[0] .= " AND `item`.`parent` = ?";
1617 $condition[] = $conversation_id;
1620 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1621 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1623 $items = Item::inArray($statuses);
1625 $ret = api_format_items($items, $user_info, false, $type);
1627 // Set all posts from the query above to seen
1629 foreach ($items as $item) {
1630 $idarray[] = intval($item["id"]);
1633 if (!empty($idarray)) {
1634 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1636 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1640 $data = ['status' => $ret];
1644 $data = api_rss_extra($a, $data, $user_info);
1648 return api_format_data("statuses", $type, $data);
1651 /// @TODO move to top of file or somewhere better
1652 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1653 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1656 * Returns the most recent statuses from public users.
1658 * @param string $type Return type (atom, rss, xml, json)
1660 * @return array|string
1662 function api_statuses_public_timeline($type)
1665 $user_info = api_get_user($a);
1667 if (api_user() === false || $user_info === false) {
1668 throw new ForbiddenException();
1671 // get last network messages
1674 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1675 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1679 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1680 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1681 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1682 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1683 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1685 $start = $page * $count;
1688 if ($exclude_replies && !$conversation_id) {
1689 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall`",
1690 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1693 $condition[0] .= " AND `thread`.`iid` <= ?";
1694 $condition[] = $max_id;
1697 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1698 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1700 $r = Item::inArray($statuses);
1702 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin`",
1703 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1706 $condition[0] .= " AND `item`.`id` <= ?";
1707 $condition[] = $max_id;
1709 if ($conversation_id > 0) {
1710 $condition[0] .= " AND `item`.`parent` = ?";
1711 $condition[] = $conversation_id;
1714 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1715 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1717 $r = Item::inArray($statuses);
1720 $ret = api_format_items($r, $user_info, false, $type);
1722 $data = ['status' => $ret];
1726 $data = api_rss_extra($a, $data, $user_info);
1730 return api_format_data("statuses", $type, $data);
1733 /// @TODO move to top of file or somewhere better
1734 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1737 * Returns the most recent statuses posted by users this node knows about.
1739 * @brief Returns the list of public federated posts this node knows about
1741 * @param string $type Return format: json, xml, atom, rss
1742 * @return array|string
1743 * @throws ForbiddenException
1745 function api_statuses_networkpublic_timeline($type)
1748 $user_info = api_get_user($a);
1750 if (api_user() === false || $user_info === false) {
1751 throw new ForbiddenException();
1754 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1755 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1758 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1759 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1763 $start = ($page - 1) * $count;
1765 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1766 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1769 $condition[0] .= " AND `thread`.`iid` <= ?";
1770 $condition[] = $max_id;
1773 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1774 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1776 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1778 $data = ['status' => $ret];
1782 $data = api_rss_extra($a, $data, $user_info);
1786 return api_format_data("statuses", $type, $data);
1789 /// @TODO move to top of file or somewhere better
1790 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1793 * Returns a single status.
1795 * @param string $type Return type (atom, rss, xml, json)
1797 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1799 function api_statuses_show($type)
1802 $user_info = api_get_user($a);
1804 if (api_user() === false || $user_info === false) {
1805 throw new ForbiddenException();
1809 $id = intval(defaults($a->argv, 3, 0));
1812 $id = intval(defaults($_REQUEST, 'id', 0));
1817 $id = intval(defaults($a->argv, 4, 0));
1820 logger('API: api_statuses_show: ' . $id);
1822 $conversation = !empty($_REQUEST['conversation']);
1824 // try to fetch the item for the local user - or the public item, if there is no local one
1825 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1826 if (!DBA::isResult($uri_item)) {
1827 throw new BadRequestException("There is no status with this id.");
1830 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1831 if (!DBA::isResult($item)) {
1832 throw new BadRequestException("There is no status with this id.");
1837 if ($conversation) {
1838 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1839 $params = ['order' => ['id' => true]];
1841 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1845 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1847 /// @TODO How about copying this to above methods which don't check $r ?
1848 if (!DBA::isResult($statuses)) {
1849 throw new BadRequestException("There is no status with this id.");
1852 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1854 if ($conversation) {
1855 $data = ['status' => $ret];
1856 return api_format_data("statuses", $type, $data);
1858 $data = ['status' => $ret[0]];
1859 return api_format_data("status", $type, $data);
1863 /// @TODO move to top of file or somewhere better
1864 api_register_func('api/statuses/show', 'api_statuses_show', true);
1868 * @param string $type Return type (atom, rss, xml, json)
1870 * @todo nothing to say?
1872 function api_conversation_show($type)
1875 $user_info = api_get_user($a);
1877 if (api_user() === false || $user_info === false) {
1878 throw new ForbiddenException();
1882 $id = intval(defaults($a->argv , 3 , 0));
1883 $since_id = intval(defaults($_REQUEST, 'since_id', 0));
1884 $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
1885 $count = intval(defaults($_REQUEST, 'count' , 20));
1886 $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
1891 $start = $page * $count;
1894 $id = intval(defaults($_REQUEST, 'id', 0));
1899 $id = intval(defaults($a->argv, 4, 0));
1902 logger('API: api_conversation_show: '.$id);
1904 // try to fetch the item for the local user - or the public item, if there is no local one
1905 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1906 if (!DBA::isResult($item)) {
1907 throw new BadRequestException("There is no status with this id.");
1910 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1911 if (!DBA::isResult($parent)) {
1912 throw new BadRequestException("There is no status with this id.");
1915 $id = $parent['id'];
1917 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1918 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1921 $condition[0] .= " AND `item`.`id` <= ?";
1922 $condition[] = $max_id;
1925 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1926 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1928 if (!DBA::isResult($statuses)) {
1929 throw new BadRequestException("There is no status with id $id.");
1932 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1934 $data = ['status' => $ret];
1935 return api_format_data("statuses", $type, $data);
1938 /// @TODO move to top of file or somewhere better
1939 api_register_func('api/conversation/show', 'api_conversation_show', true);
1940 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1945 * @param string $type Return type (atom, rss, xml, json)
1947 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1949 function api_statuses_repeat($type)
1955 if (api_user() === false) {
1956 throw new ForbiddenException();
1962 $id = intval(defaults($a->argv, 3, 0));
1965 $id = intval(defaults($_REQUEST, 'id', 0));
1970 $id = intval(defaults($a->argv, 4, 0));
1973 logger('API: api_statuses_repeat: '.$id);
1975 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1976 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
1978 if (DBA::isResult($item) && $item['body'] != "") {
1979 if (strpos($item['body'], "[/share]") !== false) {
1980 $pos = strpos($item['body'], "[share");
1981 $post = substr($item['body'], $pos);
1983 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
1985 $post .= $item['body'];
1986 $post .= "[/share]";
1988 $_REQUEST['body'] = $post;
1989 $_REQUEST['profile_uid'] = api_user();
1990 $_REQUEST['api_source'] = true;
1992 if (!x($_REQUEST, "source")) {
1993 $_REQUEST["source"] = api_source();
1998 throw new ForbiddenException();
2001 // this should output the last post (the one we just posted).
2003 return api_status_show($type);
2006 /// @TODO move to top of file or somewhere better
2007 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2010 * Destroys a specific status.
2012 * @param string $type Return type (atom, rss, xml, json)
2014 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2016 function api_statuses_destroy($type)
2020 if (api_user() === false) {
2021 throw new ForbiddenException();
2027 $id = intval(defaults($a->argv, 3, 0));
2030 $id = intval(defaults($_REQUEST, 'id', 0));
2035 $id = intval(defaults($a->argv, 4, 0));
2038 logger('API: api_statuses_destroy: '.$id);
2040 $ret = api_statuses_show($type);
2042 Item::deleteForUser(['id' => $id], api_user());
2047 /// @TODO move to top of file or somewhere better
2048 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2051 * Returns the most recent mentions.
2053 * @param string $type Return type (atom, rss, xml, json)
2055 * @see http://developer.twitter.com/doc/get/statuses/mentions
2057 function api_statuses_mentions($type)
2060 $user_info = api_get_user($a);
2062 if (api_user() === false || $user_info === false) {
2063 throw new ForbiddenException();
2066 unset($_REQUEST["user_id"]);
2067 unset($_GET["user_id"]);
2069 unset($_REQUEST["screen_name"]);
2070 unset($_GET["screen_name"]);
2072 // get last network messages
2075 $since_id = defaults($_REQUEST, 'since_id', 0);
2076 $max_id = defaults($_REQUEST, 'max_id' , 0);
2077 $count = defaults($_REQUEST, 'count' , 20);
2078 $page = defaults($_REQUEST, 'page' , 1);
2083 $start = ($page - 1) * $count;
2085 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2086 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2087 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2090 $condition[0] .= " AND `item`.`id` <= ?";
2091 $condition[] = $max_id;
2094 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2095 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2097 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2099 $data = ['status' => $ret];
2103 $data = api_rss_extra($a, $data, $user_info);
2107 return api_format_data("statuses", $type, $data);
2110 /// @TODO move to top of file or somewhere better
2111 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2112 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2115 * Returns the most recent statuses posted by the user.
2117 * @brief Returns a user's public timeline
2119 * @param string $type Either "json" or "xml"
2120 * @return string|array
2121 * @throws ForbiddenException
2122 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2124 function api_statuses_user_timeline($type)
2127 $user_info = api_get_user($a);
2129 if (api_user() === false || $user_info === false) {
2130 throw new ForbiddenException();
2134 "api_statuses_user_timeline: api_user: ". api_user() .
2135 "\nuser_info: ".print_r($user_info, true) .
2136 "\n_REQUEST: ".print_r($_REQUEST, true),
2140 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2141 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2142 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2143 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2146 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2147 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2151 $start = ($page - 1) * $count;
2153 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2154 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2156 if ($user_info['self'] == 1) {
2157 $condition[0] .= ' AND `item`.`wall` ';
2160 if ($exclude_replies > 0) {
2161 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2164 if ($conversation_id > 0) {
2165 $condition[0] .= " AND `item`.`parent` = ?";
2166 $condition[] = $conversation_id;
2170 $condition[0] .= " AND `item`.`id` <= ?";
2171 $condition[] = $max_id;
2174 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2175 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2177 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2179 $data = ['status' => $ret];
2183 $data = api_rss_extra($a, $data, $user_info);
2187 return api_format_data("statuses", $type, $data);
2190 /// @TODO move to top of file or somewhere better
2191 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2194 * Star/unstar an item.
2195 * param: id : id of the item
2197 * @param string $type Return type (atom, rss, xml, json)
2199 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2201 function api_favorites_create_destroy($type)
2205 if (api_user() === false) {
2206 throw new ForbiddenException();
2209 // for versioned api.
2210 /// @TODO We need a better global soluton
2211 $action_argv_id = 2;
2212 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2213 $action_argv_id = 3;
2216 if ($a->argc <= $action_argv_id) {
2217 throw new BadRequestException("Invalid request.");
2219 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2220 if ($a->argc == $action_argv_id + 2) {
2221 $itemid = intval(defaults($a->argv, $action_argv_id + 1, 0));
2223 $itemid = intval(defaults($_REQUEST, 'id', 0));
2226 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2228 if (!DBA::isResult($item)) {
2229 throw new BadRequestException("Invalid item.");
2234 $item['starred'] = 1;
2237 $item['starred'] = 0;
2240 throw new BadRequestException("Invalid action ".$action);
2243 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2246 throw new InternalServerErrorException("DB error");
2250 $user_info = api_get_user($a);
2251 $rets = api_format_items([$item], $user_info, false, $type);
2254 $data = ['status' => $ret];
2258 $data = api_rss_extra($a, $data, $user_info);
2261 return api_format_data("status", $type, $data);
2264 /// @TODO move to top of file or somewhere better
2265 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2266 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2269 * Returns the most recent favorite statuses.
2271 * @param string $type Return type (atom, rss, xml, json)
2273 * @return string|array
2275 function api_favorites($type)
2280 $user_info = api_get_user($a);
2282 if (api_user() === false || $user_info === false) {
2283 throw new ForbiddenException();
2288 // in friendica starred item are private
2289 // return favorites only for self
2290 logger('api_favorites: self:' . $user_info['self']);
2292 if ($user_info['self'] == 0) {
2296 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2297 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2298 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2299 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2304 $start = $page*$count;
2306 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2307 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2309 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2312 $condition[0] .= " AND `item`.`id` <= ?";
2313 $condition[] = $max_id;
2316 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2318 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2321 $data = ['status' => $ret];
2325 $data = api_rss_extra($a, $data, $user_info);
2328 return api_format_data("statuses", $type, $data);
2331 /// @TODO move to top of file or somewhere better
2332 api_register_func('api/favorites', 'api_favorites', true);
2336 * @param array $item
2337 * @param array $recipient
2338 * @param array $sender
2342 function api_format_messages($item, $recipient, $sender)
2344 // standard meta information
2346 'id' => $item['id'],
2347 'sender_id' => $sender['id'] ,
2349 'recipient_id' => $recipient['id'],
2350 'created_at' => api_date(defaults($item, 'created', DateTimeFormat::utcNow())),
2351 'sender_screen_name' => $sender['screen_name'],
2352 'recipient_screen_name' => $recipient['screen_name'],
2353 'sender' => $sender,
2354 'recipient' => $recipient,
2356 'friendica_seen' => defaults($item, 'seen', 0),
2357 'friendica_parent_uri' => defaults($item, 'parent-uri', ''),
2360 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2361 if (isset($ret['sender']['uid'])) {
2362 unset($ret['sender']['uid']);
2364 if (isset($ret['sender']['self'])) {
2365 unset($ret['sender']['self']);
2367 if (isset($ret['recipient']['uid'])) {
2368 unset($ret['recipient']['uid']);
2370 if (isset($ret['recipient']['self'])) {
2371 unset($ret['recipient']['self']);
2374 //don't send title to regular StatusNET requests to avoid confusing these apps
2375 if (x($_GET, 'getText')) {
2376 $ret['title'] = $item['title'];
2377 if ($_GET['getText'] == 'html') {
2378 $ret['text'] = BBCode::convert($item['body'], false);
2379 } elseif ($_GET['getText'] == 'plain') {
2380 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2383 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2385 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2386 unset($ret['sender']);
2387 unset($ret['recipient']);
2395 * @param array $item
2399 function api_convert_item($item)
2401 $body = $item['body'];
2402 $attachments = api_get_attachments($body);
2404 // Workaround for ostatus messages where the title is identically to the body
2405 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2406 $statusbody = trim(HTML::toPlaintext($html, 0));
2408 // handle data: images
2409 $statusbody = api_format_items_embeded_images($item, $statusbody);
2411 $statustitle = trim($item['title']);
2413 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2414 $statustext = trim($statusbody);
2416 $statustext = trim($statustitle."\n\n".$statusbody);
2419 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($statustext)> 1000)) {
2420 $statustext = substr($statustext, 0, 1000) . "... \n" . defaults($item, 'plink', '');
2423 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2425 // Workaround for clients with limited HTML parser functionality
2426 $search = ["<br>", "<blockquote>", "</blockquote>",
2427 "<h1>", "</h1>", "<h2>", "</h2>",
2428 "<h3>", "</h3>", "<h4>", "</h4>",
2429 "<h5>", "</h5>", "<h6>", "</h6>"];
2430 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2431 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2432 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2433 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2434 $statushtml = str_replace($search, $replace, $statushtml);
2436 if ($item['title'] != "") {
2437 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2441 $oldtext = $statushtml;
2442 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2443 } while ($oldtext != $statushtml);
2445 if (substr($statushtml, 0, 4) == '<br>') {
2446 $statushtml = substr($statushtml, 4);
2449 if (substr($statushtml, 0, -4) == '<br>') {
2450 $statushtml = substr($statushtml, -4);
2453 // feeds without body should contain the link
2454 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2455 $statushtml .= BBCode::convert($item['plink']);
2458 $entities = api_get_entitities($statustext, $body);
2461 "text" => $statustext,
2462 "html" => $statushtml,
2463 "attachments" => $attachments,
2464 "entities" => $entities
2470 * @param string $body
2474 function api_get_attachments(&$body)
2477 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2479 $URLSearchString = "^\[\]";
2480 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2488 foreach ($images[1] as $image) {
2489 $imagedata = Image::getInfoFromURL($image);
2492 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2496 if (strstr(defaults($_SERVER, 'HTTP_USER_AGENT', ''), "AndStatus")) {
2497 foreach ($images[0] as $orig) {
2498 $body = str_replace($orig, "", $body);
2502 return $attachments;
2507 * @param string $text
2508 * @param string $bbcode
2511 * @todo Links at the first character of the post
2513 function api_get_entitities(&$text, $bbcode)
2515 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2517 if ($include_entities != "true") {
2518 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2520 foreach ($images[1] as $image) {
2521 $replace = ProxyUtils::proxifyUrl($image);
2522 $text = str_replace($image, $replace, $text);
2527 $bbcode = BBCode::cleanPictureLinks($bbcode);
2529 // Change pure links in text to bbcode uris
2530 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2533 $entities["hashtags"] = [];
2534 $entities["symbols"] = [];
2535 $entities["urls"] = [];
2536 $entities["user_mentions"] = [];
2538 $URLSearchString = "^\[\]";
2540 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2542 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2543 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2544 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2546 $bbcode = preg_replace(
2547 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2548 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2551 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2553 $bbcode = preg_replace(
2554 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2555 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2558 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2560 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2562 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2563 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2566 foreach ($urls[1] as $id => $url) {
2567 //$start = strpos($text, $url, $offset);
2568 $start = iconv_strpos($text, $url, 0, "UTF-8");
2569 if (!($start === false)) {
2570 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2574 ksort($ordered_urls);
2577 //foreach ($urls[1] AS $id=>$url) {
2578 foreach ($ordered_urls as $url) {
2579 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2580 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2582 $display_url = $url["title"];
2584 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2585 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2587 if (strlen($display_url) > 26) {
2588 $display_url = substr($display_url, 0, 25)."…";
2592 //$start = strpos($text, $url, $offset);
2593 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2594 if (!($start === false)) {
2595 $entities["urls"][] = ["url" => $url["url"],
2596 "expanded_url" => $url["url"],
2597 "display_url" => $display_url,
2598 "indices" => [$start, $start+strlen($url["url"])]];
2599 $offset = $start + 1;
2603 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2604 $ordered_images = [];
2605 foreach ($images[1] as $image) {
2606 //$start = strpos($text, $url, $offset);
2607 $start = iconv_strpos($text, $image, 0, "UTF-8");
2608 if (!($start === false)) {
2609 $ordered_images[$start] = $image;
2612 //$entities["media"] = array();
2615 foreach ($ordered_images as $url) {
2616 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2617 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2619 if (strlen($display_url) > 26) {
2620 $display_url = substr($display_url, 0, 25)."…";
2623 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2624 if (!($start === false)) {
2625 $image = Image::getInfoFromURL($url);
2627 // If image cache is activated, then use the following sizes:
2628 // thumb (150), small (340), medium (600) and large (1024)
2629 if (!Config::get("system", "proxy_disabled")) {
2630 $media_url = ProxyUtils::proxifyUrl($url);
2633 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2634 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2636 if (($image[0] > 150) || ($image[1] > 150)) {
2637 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2638 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2641 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2642 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2644 if (($image[0] > 600) || ($image[1] > 600)) {
2645 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2646 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2650 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2653 $entities["media"][] = [
2655 "id_str" => (string)$start+1,
2656 "indices" => [$start, $start+strlen($url)],
2657 "media_url" => normalise_link($media_url),
2658 "media_url_https" => $media_url,
2660 "display_url" => $display_url,
2661 "expanded_url" => $url,
2665 $offset = $start + 1;
2674 * @param array $item
2675 * @param string $text
2679 function api_format_items_embeded_images($item, $text)
2681 $text = preg_replace_callback(
2682 '|data:image/([^;]+)[^=]+=*|m',
2683 function () use ($item) {
2684 return System::baseUrl() . '/display/' . $item['guid'];
2692 * @brief return <a href='url'>name</a> as array
2694 * @param string $txt text
2699 function api_contactlink_to_array($txt)
2702 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2703 if ($r && count($match)==3) {
2705 'name' => $match[2],
2719 * @brief return likes, dislikes and attend status for item
2721 * @param array $item array
2722 * @param string $type Return type (atom, rss, xml, json)
2725 * likes => int count,
2726 * dislikes => int count
2728 function api_format_items_activities(&$item, $type = "json")
2737 'attendmaybe' => [],
2740 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2741 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2743 while ($item = Item::fetch($ret)) {
2744 // not used as result should be structured like other user data
2745 //builtin_activity_puller($i, $activities);
2747 // get user data and add it to the array of the activity
2748 $user = api_get_user($a, $item['author-id']);
2749 switch ($item['verb']) {
2751 $activities['like'][] = $user;
2753 case ACTIVITY_DISLIKE:
2754 $activities['dislike'][] = $user;
2756 case ACTIVITY_ATTEND:
2757 $activities['attendyes'][] = $user;
2759 case ACTIVITY_ATTENDNO:
2760 $activities['attendno'][] = $user;
2762 case ACTIVITY_ATTENDMAYBE:
2763 $activities['attendmaybe'][] = $user;
2772 if ($type == "xml") {
2773 $xml_activities = [];
2774 foreach ($activities as $k => $v) {
2775 // change xml element from "like" to "friendica:like"
2776 $xml_activities["friendica:".$k] = $v;
2777 // add user data into xml output
2779 foreach ($v as $user) {
2780 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2783 $activities = $xml_activities;
2791 * @brief return data from profiles
2793 * @param array $profile_row array containing data from db table 'profile'
2796 function api_format_items_profiles($profile_row)
2799 'profile_id' => $profile_row['id'],
2800 'profile_name' => $profile_row['profile-name'],
2801 'is_default' => $profile_row['is-default'] ? true : false,
2802 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2803 'profile_photo' => $profile_row['photo'],
2804 'profile_thumb' => $profile_row['thumb'],
2805 'publish' => $profile_row['publish'] ? true : false,
2806 'net_publish' => $profile_row['net-publish'] ? true : false,
2807 'description' => $profile_row['pdesc'],
2808 'date_of_birth' => $profile_row['dob'],
2809 'address' => $profile_row['address'],
2810 'city' => $profile_row['locality'],
2811 'region' => $profile_row['region'],
2812 'postal_code' => $profile_row['postal-code'],
2813 'country' => $profile_row['country-name'],
2814 'hometown' => $profile_row['hometown'],
2815 'gender' => $profile_row['gender'],
2816 'marital' => $profile_row['marital'],
2817 'marital_with' => $profile_row['with'],
2818 'marital_since' => $profile_row['howlong'],
2819 'sexual' => $profile_row['sexual'],
2820 'politic' => $profile_row['politic'],
2821 'religion' => $profile_row['religion'],
2822 'public_keywords' => $profile_row['pub_keywords'],
2823 'private_keywords' => $profile_row['prv_keywords'],
2824 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2825 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2826 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2827 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2828 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2829 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2830 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2831 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2832 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2833 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2834 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2835 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2836 'homepage' => $profile_row['homepage'],
2843 * @brief format items to be returned by api
2845 * @param array $r array of items
2846 * @param array $user_info
2847 * @param bool $filter_user filter items by $user_info
2848 * @param string $type Return type (atom, rss, xml, json)
2850 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2856 foreach ($r as $item) {
2857 localize_item($item);
2858 list($status_user, $owner_user) = api_item_get_user($a, $item);
2860 // Look if the posts are matching if they should be filtered by user id
2861 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2865 $in_reply_to = api_in_reply_to($item);
2867 $converted = api_convert_item($item);
2869 if ($type == "xml") {
2870 $geo = "georss:point";
2876 'text' => $converted["text"],
2877 'truncated' => false,
2878 'created_at'=> api_date($item['created']),
2879 'in_reply_to_status_id' => $in_reply_to['status_id'],
2880 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2881 'source' => (($item['app']) ? $item['app'] : 'web'),
2882 'id' => intval($item['id']),
2883 'id_str' => (string) intval($item['id']),
2884 'in_reply_to_user_id' => $in_reply_to['user_id'],
2885 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2886 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2888 'favorited' => $item['starred'] ? true : false,
2889 'user' => $status_user ,
2890 'friendica_owner' => $owner_user,
2891 'friendica_private' => $item['private'] == 1,
2892 //'entities' => NULL,
2893 'statusnet_html' => $converted["html"],
2894 'statusnet_conversation_id' => $item['parent'],
2895 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2896 'friendica_activities' => api_format_items_activities($item, $type),
2899 if (count($converted["attachments"]) > 0) {
2900 $status["attachments"] = $converted["attachments"];
2903 if (count($converted["entities"]) > 0) {
2904 $status["entities"] = $converted["entities"];
2907 if ($status["source"] == 'web') {
2908 $status["source"] = ContactSelector::networkToName($item['network'], $user_info['url']);
2909 } elseif (ContactSelector::networkToName($item['network'], $user_info['url']) != $status["source"]) {
2910 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $user_info['url']).')');
2913 if ($item["id"] == $item["parent"]) {
2914 $retweeted_item = api_share_as_retweet($item);
2915 if ($retweeted_item !== false) {
2916 $retweeted_status = $status;
2918 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
2919 } catch (BadRequestException $e) {
2920 // user not found. should be found?
2921 /// @todo check if the user should be always found
2922 $retweeted_status["user"] = [];
2925 $rt_converted = api_convert_item($retweeted_item);
2927 $retweeted_status['text'] = $rt_converted["text"];
2928 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2929 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2930 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2931 $status['retweeted_status'] = $retweeted_status;
2935 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2936 unset($status["user"]["uid"]);
2937 unset($status["user"]["self"]);
2939 if ($item["coord"] != "") {
2940 $coords = explode(' ', $item["coord"]);
2941 if (count($coords) == 2) {
2942 if ($type == "json") {
2943 $status["geo"] = ['type' => 'Point',
2944 'coordinates' => [(float) $coords[0],
2945 (float) $coords[1]]];
2946 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2947 $status["georss:point"] = $item["coord"];
2957 * Returns the remaining number of API requests available to the user before the API limit is reached.
2959 * @param string $type Return type (atom, rss, xml, json)
2961 * @return array|string
2963 function api_account_rate_limit_status($type)
2965 if ($type == "xml") {
2967 'remaining-hits' => '150',
2968 '@attributes' => ["type" => "integer"],
2969 'hourly-limit' => '150',
2970 '@attributes2' => ["type" => "integer"],
2971 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
2972 '@attributes3' => ["type" => "datetime"],
2973 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2974 '@attributes4' => ["type" => "integer"],
2978 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2979 'remaining_hits' => '150',
2980 'hourly_limit' => '150',
2981 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
2985 return api_format_data('hash', $type, ['hash' => $hash]);
2988 /// @TODO move to top of file or somewhere better
2989 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
2992 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
2994 * @param string $type Return type (atom, rss, xml, json)
2996 * @return array|string
2998 function api_help_test($type)
3000 if ($type == 'xml') {
3006 return api_format_data('ok', $type, ["ok" => $ok]);
3009 /// @TODO move to top of file or somewhere better
3010 api_register_func('api/help/test', 'api_help_test', false);
3013 * Returns all lists the user subscribes to.
3015 * @param string $type Return type (atom, rss, xml, json)
3017 * @return array|string
3018 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3020 function api_lists_list($type)
3023 /// @TODO $ret is not filled here?
3024 return api_format_data('lists', $type, ["lists_list" => $ret]);
3027 /// @TODO move to top of file or somewhere better
3028 api_register_func('api/lists/list', 'api_lists_list', true);
3029 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3032 * Returns all groups the user owns.
3034 * @param string $type Return type (atom, rss, xml, json)
3036 * @return array|string
3037 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3039 function api_lists_ownerships($type)
3043 if (api_user() === false) {
3044 throw new ForbiddenException();
3048 $user_info = api_get_user($a);
3049 $uid = $user_info['uid'];
3051 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3053 // loop through all groups
3055 foreach ($groups as $group) {
3056 if ($group['visible']) {
3062 'name' => $group['name'],
3063 'id' => intval($group['id']),
3064 'id_str' => (string) $group['id'],
3065 'user' => $user_info,
3069 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3072 /// @TODO move to top of file or somewhere better
3073 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3076 * Returns recent statuses from users in the specified group.
3078 * @param string $type Return type (atom, rss, xml, json)
3080 * @return array|string
3081 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3083 function api_lists_statuses($type)
3087 $user_info = api_get_user($a);
3088 if (api_user() === false || $user_info === false) {
3089 throw new ForbiddenException();
3092 unset($_REQUEST["user_id"]);
3093 unset($_GET["user_id"]);
3095 unset($_REQUEST["screen_name"]);
3096 unset($_GET["screen_name"]);
3098 if (empty($_REQUEST['list_id'])) {
3099 throw new BadRequestException('list_id not specified');
3103 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
3104 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
3108 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3109 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3110 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
3111 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
3113 $start = $page * $count;
3115 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3116 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3119 $condition[0] .= " AND `item`.`id` <= ?";
3120 $condition[] = $max_id;
3122 if ($exclude_replies > 0) {
3123 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3125 if ($conversation_id > 0) {
3126 $condition[0] .= " AND `item`.`parent` = ?";
3127 $condition[] = $conversation_id;
3130 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3131 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3133 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3135 $data = ['status' => $items];
3139 $data = api_rss_extra($a, $data, $user_info);
3143 return api_format_data("statuses", $type, $data);
3146 /// @TODO move to top of file or somewhere better
3147 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3150 * Considers friends and followers lists to be private and won't return
3151 * anything if any user_id parameter is passed.
3153 * @brief Returns either the friends of the follower list
3155 * @param string $qtype Either "friends" or "followers"
3156 * @return boolean|array
3157 * @throws ForbiddenException
3159 function api_statuses_f($qtype)
3163 if (api_user() === false) {
3164 throw new ForbiddenException();
3168 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3169 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3173 $start = ($page - 1) * $count;
3175 $user_info = api_get_user($a);
3177 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3178 /* this is to stop Hotot to load friends multiple times
3179 * I'm not sure if I'm missing return something or
3180 * is a bug in hotot. Workaround, meantime
3184 return array('$users' => $ret);*/
3189 if ($qtype == 'friends') {
3190 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3191 } elseif ($qtype == 'followers') {
3192 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3195 // friends and followers only for self
3196 if ($user_info['self'] == 0) {
3197 $sql_extra = " AND false ";
3200 if ($qtype == 'blocks') {
3201 $sql_filter = 'AND `blocked` AND NOT `pending`';
3202 } elseif ($qtype == 'incoming') {
3203 $sql_filter = 'AND `pending`';
3205 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3223 foreach ($r as $cid) {
3224 $user = api_get_user($a, $cid['nurl']);
3225 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3226 unset($user["uid"]);
3227 unset($user["self"]);
3234 return ['user' => $ret];
3239 * Returns the user's friends.
3241 * @brief Returns the list of friends of the provided user
3243 * @deprecated By Twitter API in favor of friends/list
3245 * @param string $type Either "json" or "xml"
3246 * @return boolean|string|array
3248 function api_statuses_friends($type)
3250 $data = api_statuses_f("friends");
3251 if ($data === false) {
3254 return api_format_data("users", $type, $data);
3258 * Returns the user's followers.
3260 * @brief Returns the list of followers of the provided user
3262 * @deprecated By Twitter API in favor of friends/list
3264 * @param string $type Either "json" or "xml"
3265 * @return boolean|string|array
3267 function api_statuses_followers($type)
3269 $data = api_statuses_f("followers");
3270 if ($data === false) {
3273 return api_format_data("users", $type, $data);
3276 /// @TODO move to top of file or somewhere better
3277 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3278 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3281 * Returns the list of blocked users
3283 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3285 * @param string $type Either "json" or "xml"
3287 * @return boolean|string|array
3289 function api_blocks_list($type)
3291 $data = api_statuses_f('blocks');
3292 if ($data === false) {
3295 return api_format_data("users", $type, $data);
3298 /// @TODO move to top of file or somewhere better
3299 api_register_func('api/blocks/list', 'api_blocks_list', true);
3302 * Returns the list of pending users IDs
3304 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3306 * @param string $type Either "json" or "xml"
3308 * @return boolean|string|array
3310 function api_friendships_incoming($type)
3312 $data = api_statuses_f('incoming');
3313 if ($data === false) {
3318 foreach ($data['user'] as $user) {
3319 $ids[] = $user['id'];
3322 return api_format_data("ids", $type, ['id' => $ids]);
3325 /// @TODO move to top of file or somewhere better
3326 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3329 * Returns the instance's configuration information.
3331 * @param string $type Return type (atom, rss, xml, json)
3333 * @return array|string
3335 function api_statusnet_config($type)
3339 $name = Config::get('config', 'sitename');
3340 $server = $a->get_hostname();
3341 $logo = System::baseUrl() . '/images/friendica-64.png';
3342 $email = Config::get('config', 'admin_email');
3343 $closed = intval(Config::get('config', 'register_policy')) === REGISTER_CLOSED ? 'true' : 'false';
3344 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3345 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3346 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3347 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3350 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3351 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3352 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3353 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3354 'shorturllength' => '30',
3356 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3357 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3358 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3359 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3364 return api_format_data('config', $type, ['config' => $config]);
3367 /// @TODO move to top of file or somewhere better
3368 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3369 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3373 * @param string $type Return type (atom, rss, xml, json)
3375 * @return array|string
3377 function api_statusnet_version($type)
3380 $fake_statusnet_version = "0.9.7";
3382 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3385 /// @TODO move to top of file or somewhere better
3386 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3387 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3391 * @param string $type Return type (atom, rss, xml, json)
3393 * @todo use api_format_data() to return data
3395 function api_ff_ids($type)
3398 throw new ForbiddenException();
3405 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3408 "SELECT `pcontact`.`id` FROM `contact`
3409 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3410 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3413 if (!DBA::isResult($r)) {
3418 foreach ($r as $rr) {
3419 if ($stringify_ids) {
3422 $ids[] = intval($rr['id']);
3426 return api_format_data("ids", $type, ['id' => $ids]);
3430 * Returns the ID of every user the user is following.
3432 * @param string $type Return type (atom, rss, xml, json)
3434 * @return array|string
3435 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3437 function api_friends_ids($type)
3439 return api_ff_ids($type);
3443 * Returns the ID of every user following the user.
3445 * @param string $type Return type (atom, rss, xml, json)
3447 * @return array|string
3448 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3450 function api_followers_ids($type)
3452 return api_ff_ids($type);
3455 /// @TODO move to top of file or somewhere better
3456 api_register_func('api/friends/ids', 'api_friends_ids', true);
3457 api_register_func('api/followers/ids', 'api_followers_ids', true);
3460 * Sends a new direct message.
3462 * @param string $type Return type (atom, rss, xml, json)
3464 * @return array|string
3465 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3467 function api_direct_messages_new($type)
3471 if (api_user() === false) {
3472 throw new ForbiddenException();
3475 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3479 $sender = api_get_user($a);
3482 if (!empty($_POST['screen_name'])) {
3484 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3486 DBA::escape($_POST['screen_name'])
3489 if (DBA::isResult($r)) {
3490 // Selecting the id by priority, friendica first
3491 api_best_nickname($r);
3493 $recipient = api_get_user($a, $r[0]['nurl']);
3496 $recipient = api_get_user($a, $_POST['user_id']);
3499 if (empty($recipient)) {
3500 throw new NotFoundException('Recipient not found');
3505 if (x($_REQUEST, 'replyto')) {
3507 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3509 intval($_REQUEST['replyto'])
3511 $replyto = $r[0]['parent-uri'];
3512 $sub = $r[0]['title'];
3514 if (x($_REQUEST, 'title')) {
3515 $sub = $_REQUEST['title'];
3517 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3521 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3524 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3525 $ret = api_format_messages($r[0], $recipient, $sender);
3527 $ret = ["error"=>$id];
3530 $data = ['direct_message'=>$ret];
3535 $data = api_rss_extra($a, $data, $sender);
3538 return api_format_data("direct-messages", $type, $data);
3541 /// @TODO move to top of file or somewhere better
3542 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3545 * Destroys a direct message.
3547 * @brief delete a direct_message from mail table through api
3549 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3550 * @return string|array
3551 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3553 function api_direct_messages_destroy($type)
3557 if (api_user() === false) {
3558 throw new ForbiddenException();
3562 $user_info = api_get_user($a);
3564 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3566 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3567 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3568 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3570 $uid = $user_info['uid'];
3571 // error if no id or parenturi specified (for clients posting parent-uri as well)
3572 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3573 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3574 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3577 // BadRequestException if no id specified (for clients using Twitter API)
3579 throw new BadRequestException('Message id not specified');
3582 // add parent-uri to sql command if specified by calling app
3583 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3585 // get data of the specified message id
3587 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3592 // error message if specified id is not in database
3593 if (!DBA::isResult($r)) {
3594 if ($verbose == "true") {
3595 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3596 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3598 /// @todo BadRequestException ok for Twitter API clients?
3599 throw new BadRequestException('message id not in database');
3604 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3609 if ($verbose == "true") {
3612 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3613 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3615 $answer = ['result' => 'error', 'message' => 'unknown error'];
3616 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3619 /// @todo return JSON data like Twitter API not yet implemented
3622 /// @TODO move to top of file or somewhere better
3623 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3627 * @param string $type Return type (atom, rss, xml, json)
3628 * @param string $box
3629 * @param string $verbose
3631 * @return array|string
3633 function api_direct_messages_box($type, $box, $verbose)
3636 if (api_user() === false) {
3637 throw new ForbiddenException();
3640 $count = defaults($_GET, 'count', 20);
3641 $page = defaults($_REQUEST, 'page', 1) - 1;
3646 $since_id = defaults($_REQUEST, 'since_id', 0);
3647 $max_id = defaults($_REQUEST, 'max_id', 0);
3649 $user_id = defaults($_REQUEST, 'user_id', '');
3650 $screen_name = defaults($_REQUEST, 'screen_name', '');
3653 unset($_REQUEST["user_id"]);
3654 unset($_GET["user_id"]);
3656 unset($_REQUEST["screen_name"]);
3657 unset($_GET["screen_name"]);
3659 $user_info = api_get_user($a);
3660 if ($user_info === false) {
3661 throw new ForbiddenException();
3663 $profile_url = $user_info["url"];
3666 $start = $page * $count;
3671 if ($box=="sentbox") {
3672 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3673 } elseif ($box == "conversation") {
3674 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape(defaults($_GET, 'uri', '')) . "'";
3675 } elseif ($box == "all") {
3676 $sql_extra = "true";
3677 } elseif ($box == "inbox") {
3678 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3682 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3685 if ($user_id != "") {
3686 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3687 } elseif ($screen_name !="") {
3688 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3692 "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",
3698 if ($verbose == "true" && !DBA::isResult($r)) {
3699 $answer = ['result' => 'error', 'message' => 'no mails available'];
3700 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3704 foreach ($r as $item) {
3705 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3706 $recipient = $user_info;
3707 $sender = api_get_user($a, normalise_link($item['contact-url']));
3708 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3709 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3710 $sender = $user_info;
3713 if (isset($recipient) && isset($sender)) {
3714 $ret[] = api_format_messages($item, $recipient, $sender);
3719 $data = ['direct_message' => $ret];
3723 $data = api_rss_extra($a, $data, $user_info);
3726 return api_format_data("direct-messages", $type, $data);
3730 * Returns the most recent direct messages sent by the user.
3732 * @param string $type Return type (atom, rss, xml, json)
3734 * @return array|string
3735 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3737 function api_direct_messages_sentbox($type)
3739 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3740 return api_direct_messages_box($type, "sentbox", $verbose);
3744 * Returns the most recent direct messages sent to the user.
3746 * @param string $type Return type (atom, rss, xml, json)
3748 * @return array|string
3749 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3751 function api_direct_messages_inbox($type)
3753 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3754 return api_direct_messages_box($type, "inbox", $verbose);
3759 * @param string $type Return type (atom, rss, xml, json)
3761 * @return array|string
3763 function api_direct_messages_all($type)
3765 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3766 return api_direct_messages_box($type, "all", $verbose);
3771 * @param string $type Return type (atom, rss, xml, json)
3773 * @return array|string
3775 function api_direct_messages_conversation($type)
3777 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3778 return api_direct_messages_box($type, "conversation", $verbose);
3781 /// @TODO move to top of file or somewhere better
3782 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3783 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3784 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3785 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3788 * Returns an OAuth Request Token.
3790 * @see https://oauth.net/core/1.0/#auth_step1
3792 function api_oauth_request_token()
3794 $oauth1 = new FKOAuth1();
3796 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3797 } catch (Exception $e) {
3798 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3806 * Returns an OAuth Access Token.
3808 * @return array|string
3809 * @see https://oauth.net/core/1.0/#auth_step3
3811 function api_oauth_access_token()
3813 $oauth1 = new FKOAuth1();
3815 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3816 } catch (Exception $e) {
3817 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3824 /// @TODO move to top of file or somewhere better
3825 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3826 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3830 * @brief delete a complete photoalbum with all containing photos from database through api
3832 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3833 * @return string|array
3835 function api_fr_photoalbum_delete($type)
3837 if (api_user() === false) {
3838 throw new ForbiddenException();
3841 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3843 // we do not allow calls without album string
3845 throw new BadRequestException("no albumname specified");
3847 // check if album is existing
3849 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3853 if (!DBA::isResult($r)) {
3854 throw new BadRequestException("album not available");
3857 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3858 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3859 foreach ($r as $rr) {
3860 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
3861 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
3863 if (!DBA::isResult($photo_item)) {
3864 throw new InternalServerErrorException("problem with deleting items occured");
3866 Item::deleteForUser(['id' => $photo_item['id']], api_user());
3869 // now let's delete all photos from the album
3870 $result = DBA::delete('photo', ['uid' => api_user(), 'album' => $album]);
3872 // return success of deletion or error message
3874 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
3875 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
3877 throw new InternalServerErrorException("unknown error - deleting from database failed");
3882 * @brief update the name of the album for all photos of an album
3884 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3885 * @return string|array
3887 function api_fr_photoalbum_update($type)
3889 if (api_user() === false) {
3890 throw new ForbiddenException();
3893 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3894 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3896 // we do not allow calls without album string
3898 throw new BadRequestException("no albumname specified");
3900 if ($album_new == "") {
3901 throw new BadRequestException("no new albumname specified");
3903 // check if album is existing
3904 if (!DBA::exists('photo', ['uid' => api_user(), 'album' => $album])) {
3905 throw new BadRequestException("album not available");
3907 // now let's update all photos to the albumname
3908 $result = DBA::update('photo', ['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
3910 // return success of updating or error message
3912 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
3913 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
3915 throw new InternalServerErrorException("unknown error - updating in database failed");
3921 * @brief list all photos of the authenticated user
3923 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3924 * @return string|array
3926 function api_fr_photos_list($type)
3928 if (api_user() === false) {
3929 throw new ForbiddenException();
3932 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3933 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3934 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3935 intval(local_user())
3938 'image/jpeg' => 'jpg',
3939 'image/png' => 'png',
3940 'image/gif' => 'gif'
3942 $data = ['photo'=>[]];
3943 if (DBA::isResult($r)) {
3944 foreach ($r as $rr) {
3946 $photo['id'] = $rr['resource-id'];
3947 $photo['album'] = $rr['album'];
3948 $photo['filename'] = $rr['filename'];
3949 $photo['type'] = $rr['type'];
3950 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3951 $photo['created'] = $rr['created'];
3952 $photo['edited'] = $rr['edited'];
3953 $photo['desc'] = $rr['desc'];
3955 if ($type == "xml") {
3956 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3958 $photo['thumb'] = $thumb;
3959 $data['photo'][] = $photo;
3963 return api_format_data("photos", $type, $data);
3967 * @brief upload a new photo or change an existing photo
3969 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3970 * @return string|array
3972 function api_fr_photo_create_update($type)
3974 if (api_user() === false) {
3975 throw new ForbiddenException();
3978 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3979 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3980 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3981 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3982 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3983 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3984 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3985 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3986 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3988 // do several checks on input parameters
3989 // we do not allow calls without album string
3990 if ($album == null) {
3991 throw new BadRequestException("no albumname specified");
3993 // if photo_id == null --> we are uploading a new photo
3994 if ($photo_id == null) {
3997 // error if no media posted in create-mode
3998 if (!x($_FILES, 'media')) {
4000 throw new BadRequestException("no media data submitted");
4003 // album_new will be ignored in create-mode
4008 // check if photo is existing in database
4010 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4012 DBA::escape($photo_id),
4015 if (!DBA::isResult($r)) {
4016 throw new BadRequestException("photo not available");
4020 // checks on acl strings provided by clients
4021 $acl_input_error = false;
4022 $acl_input_error |= check_acl_input($allow_cid);
4023 $acl_input_error |= check_acl_input($deny_cid);
4024 $acl_input_error |= check_acl_input($allow_gid);
4025 $acl_input_error |= check_acl_input($deny_gid);
4026 if ($acl_input_error) {
4027 throw new BadRequestException("acl data invalid");
4029 // now let's upload the new media in create-mode
4030 if ($mode == "create") {
4031 $media = $_FILES['media'];
4032 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4034 // return success of updating or error message
4035 if (!is_null($data)) {
4036 return api_format_data("photo_create", $type, $data);
4038 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4042 // now let's do the changes in update-mode
4043 if ($mode == "update") {
4046 if (!is_null($desc)) {
4047 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4050 if (!is_null($album_new)) {
4051 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4054 if (!is_null($allow_cid)) {
4055 $allow_cid = trim($allow_cid);
4056 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4059 if (!is_null($deny_cid)) {
4060 $deny_cid = trim($deny_cid);
4061 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4064 if (!is_null($allow_gid)) {
4065 $allow_gid = trim($allow_gid);
4066 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4069 if (!is_null($deny_gid)) {
4070 $deny_gid = trim($deny_gid);
4071 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4075 if ($sql_extra != "") {
4076 $nothingtodo = false;
4078 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4080 DateTimeFormat::utcNow(), // update edited timestamp
4082 DBA::escape($photo_id),
4086 $nothingtodo = true;
4089 if (x($_FILES, 'media')) {
4090 $nothingtodo = false;
4091 $media = $_FILES['media'];
4092 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4093 if (!is_null($data)) {
4094 return api_format_data("photo_update", $type, $data);
4098 // return success of updating or error message
4100 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4101 return api_format_data("photo_update", $type, ['$result' => $answer]);
4104 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4105 return api_format_data("photo_update", $type, ['$result' => $answer]);
4107 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4110 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4114 * @brief delete a single photo from the database through api
4116 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4117 * @return string|array
4119 function api_fr_photo_delete($type)
4121 if (api_user() === false) {
4122 throw new ForbiddenException();
4125 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4127 // do several checks on input parameters
4128 // we do not allow calls without photo id
4129 if ($photo_id == null) {
4130 throw new BadRequestException("no photo_id specified");
4132 // check if photo is existing in database
4134 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4136 DBA::escape($photo_id)
4138 if (!DBA::isResult($r)) {
4139 throw new BadRequestException("photo not available");
4141 // now we can perform on the deletion of the photo
4142 $result = DBA::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4144 // return success of deletion or error message
4146 // retrieve the id of the parent element (the photo element)
4147 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4148 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4150 if (!DBA::isResult($photo_item)) {
4151 throw new InternalServerErrorException("problem with deleting items occured");
4153 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4154 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4155 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4157 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4158 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4160 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4166 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4168 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4169 * @return string|array
4171 function api_fr_photo_detail($type)
4173 if (api_user() === false) {
4174 throw new ForbiddenException();
4176 if (!x($_REQUEST, 'photo_id')) {
4177 throw new BadRequestException("No photo id.");
4180 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4181 $photo_id = $_REQUEST['photo_id'];
4183 // prepare json/xml output with data from database for the requested photo
4184 $data = prepare_photo_data($type, $scale, $photo_id);
4186 return api_format_data("photo_detail", $type, $data);
4191 * Updates the user’s profile image.
4193 * @brief updates the profile image for the user (either a specified profile or the default profile)
4195 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4197 * @return string|array
4198 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4200 function api_account_update_profile_image($type)
4202 if (api_user() === false) {
4203 throw new ForbiddenException();
4206 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4208 // error if image data is missing
4209 if (!x($_FILES, 'image')) {
4210 throw new BadRequestException("no media data submitted");
4213 // check if specified profile id is valid
4214 if ($profile_id != 0) {
4215 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4216 // error message if specified profile id is not in database
4217 if (!DBA::isResult($profile)) {
4218 throw new BadRequestException("profile_id not available");
4220 $is_default_profile = $profile['is-default'];
4222 $is_default_profile = 1;
4225 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4227 if (x($_FILES, 'image')) {
4228 $media = $_FILES['image'];
4229 } elseif (x($_FILES, 'media')) {
4230 $media = $_FILES['media'];
4232 // save new profile image
4233 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4236 if (is_array($media['type'])) {
4237 $filetype = $media['type'][0];
4239 $filetype = $media['type'];
4241 if ($filetype == "image/jpeg") {
4243 } elseif ($filetype == "image/png") {
4246 throw new InternalServerErrorException('Unsupported filetype');
4249 // change specified profile or all profiles to the new resource-id
4250 if ($is_default_profile) {
4251 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4252 DBA::update('photo', ['profile' => false], $condition);
4254 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype,
4255 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype];
4256 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4259 Contact::updateSelfFromUserID(api_user(), true);
4261 // Update global directory in background
4262 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4263 if ($url && strlen(Config::get('system', 'directory'))) {
4264 Worker::add(PRIORITY_LOW, "Directory", $url);
4267 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4269 // output for client
4271 return api_account_verify_credentials($type);
4273 // SaveMediaToDatabase failed for some reason
4274 throw new InternalServerErrorException("image upload failed");
4278 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4279 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4280 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4281 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4282 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4283 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4284 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4285 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4286 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4289 * Update user profile
4291 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4293 * @return array|string
4295 function api_account_update_profile($type)
4297 $local_user = api_user();
4298 $api_user = api_get_user(get_app());
4300 if (!empty($_POST['name'])) {
4301 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4302 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4303 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4304 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4307 if (isset($_POST['description'])) {
4308 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4309 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4310 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4313 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4314 // Update global directory in background
4315 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4316 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4319 return api_account_verify_credentials($type);
4322 /// @TODO move to top of file or somewhere better
4323 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4327 * @param string $acl_string
4329 function check_acl_input($acl_string)
4331 if ($acl_string == null || $acl_string == " ") {
4334 $contact_not_found = false;
4336 // split <x><y><z> into array of cid's
4337 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4339 // check for each cid if it is available on server
4340 $cid_array = $array[0];
4341 foreach ($cid_array as $cid) {
4342 $cid = str_replace("<", "", $cid);
4343 $cid = str_replace(">", "", $cid);
4344 $condition = ['id' => $cid, 'uid' => api_user()];
4345 $contact_not_found |= !DBA::exists('contact', $condition);
4347 return $contact_not_found;
4352 * @param string $mediatype
4353 * @param array $media
4354 * @param string $type
4355 * @param string $album
4356 * @param string $allow_cid
4357 * @param string $deny_cid
4358 * @param string $allow_gid
4359 * @param string $deny_gid
4360 * @param string $desc
4361 * @param integer $profile
4362 * @param boolean $visibility
4363 * @param string $photo_id
4365 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)
4373 if (is_array($media)) {
4374 if (is_array($media['tmp_name'])) {
4375 $src = $media['tmp_name'][0];
4377 $src = $media['tmp_name'];
4379 if (is_array($media['name'])) {
4380 $filename = basename($media['name'][0]);
4382 $filename = basename($media['name']);
4384 if (is_array($media['size'])) {
4385 $filesize = intval($media['size'][0]);
4387 $filesize = intval($media['size']);
4389 if (is_array($media['type'])) {
4390 $filetype = $media['type'][0];
4392 $filetype = $media['type'];
4396 if ($filetype == "") {
4397 $filetype=Image::guessType($filename);
4399 $imagedata = getimagesize($src);
4401 $filetype = $imagedata['mime'];
4404 "File upload src: " . $src . " - filename: " . $filename .
4405 " - size: " . $filesize . " - type: " . $filetype,
4409 // check if there was a php upload error
4410 if ($filesize == 0 && $media['error'] == 1) {
4411 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4413 // check against max upload size within Friendica instance
4414 $maximagesize = Config::get('system', 'maximagesize');
4415 if ($maximagesize && ($filesize > $maximagesize)) {
4416 $formattedBytes = formatBytes($maximagesize);
4417 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4420 // create Photo instance with the data of the image
4421 $imagedata = @file_get_contents($src);
4422 $Image = new Image($imagedata, $filetype);
4423 if (! $Image->isValid()) {
4424 throw new InternalServerErrorException("unable to process image data");
4427 // check orientation of image
4428 $Image->orient($src);
4431 // check max length of images on server
4432 $max_length = Config::get('system', 'max_image_length');
4433 if (! $max_length) {
4434 $max_length = MAX_IMAGE_LENGTH;
4436 if ($max_length > 0) {
4437 $Image->scaleDown($max_length);
4438 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4440 $width = $Image->getWidth();
4441 $height = $Image->getHeight();
4443 // create a new resource-id if not already provided
4444 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4446 if ($mediatype == "photo") {
4447 // upload normal image (scales 0, 1, 2)
4448 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4450 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4452 logger("photo upload: image upload with scale 0 (original size) failed");
4454 if ($width > 640 || $height > 640) {
4455 $Image->scaleDown(640);
4456 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4458 logger("photo upload: image upload with scale 1 (640x640) failed");
4462 if ($width > 320 || $height > 320) {
4463 $Image->scaleDown(320);
4464 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4466 logger("photo upload: image upload with scale 2 (320x320) failed");
4469 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4470 } elseif ($mediatype == "profileimage") {
4471 // upload profile image (scales 4, 5, 6)
4472 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4474 if ($width > 175 || $height > 175) {
4475 $Image->scaleDown(175);
4476 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4478 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4482 if ($width > 80 || $height > 80) {
4483 $Image->scaleDown(80);
4484 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4486 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4490 if ($width > 48 || $height > 48) {
4491 $Image->scaleDown(48);
4492 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4494 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4497 $Image->__destruct();
4498 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4501 if (isset($r) && $r) {
4502 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4503 if ($photo_id == null && $mediatype == "photo") {
4504 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4506 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4507 return prepare_photo_data($type, false, $hash);
4509 throw new InternalServerErrorException("image upload failed");
4515 * @param string $hash
4516 * @param string $allow_cid
4517 * @param string $deny_cid
4518 * @param string $allow_gid
4519 * @param string $deny_gid
4520 * @param string $filetype
4521 * @param boolean $visibility
4523 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4525 // get data about the api authenticated user
4526 $uri = Item::newURI(intval(api_user()));
4527 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4530 $arr['guid'] = System::createGUID(32);
4531 $arr['uid'] = intval(api_user());
4533 $arr['parent-uri'] = $uri;
4534 $arr['type'] = 'photo';
4536 $arr['resource-id'] = $hash;
4537 $arr['contact-id'] = $owner_record['id'];
4538 $arr['owner-name'] = $owner_record['name'];
4539 $arr['owner-link'] = $owner_record['url'];
4540 $arr['owner-avatar'] = $owner_record['thumb'];
4541 $arr['author-name'] = $owner_record['name'];
4542 $arr['author-link'] = $owner_record['url'];
4543 $arr['author-avatar'] = $owner_record['thumb'];
4545 $arr['allow_cid'] = $allow_cid;
4546 $arr['allow_gid'] = $allow_gid;
4547 $arr['deny_cid'] = $deny_cid;
4548 $arr['deny_gid'] = $deny_gid;
4549 $arr['visible'] = $visibility;
4553 'image/jpeg' => 'jpg',
4554 'image/png' => 'png',
4555 'image/gif' => 'gif'
4558 // adds link to the thumbnail scale photo
4559 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4560 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4563 // do the magic for storing the item in the database and trigger the federation to other contacts
4569 * @param string $type
4571 * @param string $photo_id
4575 function prepare_photo_data($type, $scale, $photo_id)
4578 $user_info = api_get_user($a);
4580 if ($user_info === false) {
4581 throw new ForbiddenException();
4584 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4585 $data_sql = ($scale === false ? "" : "data, ");
4587 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4588 // clients needs to convert this in their way for further processing
4590 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4591 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4592 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4593 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4595 intval(local_user()),
4596 DBA::escape($photo_id),
4601 'image/jpeg' => 'jpg',
4602 'image/png' => 'png',
4603 'image/gif' => 'gif'
4606 // prepare output data for photo
4607 if (DBA::isResult($r)) {
4608 $data = ['photo' => $r[0]];
4609 $data['photo']['id'] = $data['photo']['resource-id'];
4610 if ($scale !== false) {
4611 $data['photo']['data'] = base64_encode($data['photo']['data']);
4613 unset($data['photo']['datasize']); //needed only with scale param
4615 if ($type == "xml") {
4616 $data['photo']['links'] = [];
4617 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4618 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4620 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4623 $data['photo']['link'] = [];
4624 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4626 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4627 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4631 unset($data['photo']['resource-id']);
4632 unset($data['photo']['minscale']);
4633 unset($data['photo']['maxscale']);
4635 throw new NotFoundException();
4638 // retrieve item element for getting activities (like, dislike etc.) related to photo
4639 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4640 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4642 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4644 // retrieve comments on photo
4645 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4646 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4648 $statuses = Item::selectForUser(api_user(), [], $condition);
4650 // prepare output of comments
4651 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
4653 if ($type == "xml") {
4655 foreach ($commentData as $comment) {
4656 $comments[$k++ . ":comment"] = $comment;
4659 foreach ($commentData as $comment) {
4660 $comments[] = $comment;
4663 $data['photo']['friendica_comments'] = $comments;
4665 // include info if rights on photo and rights on item are mismatching
4666 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4667 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4668 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4669 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4670 $data['photo']['rights_mismatch'] = $rights_mismatch;
4677 * Similar as /mod/redir.php
4678 * redirect to 'url' after dfrn auth
4680 * Why this when there is mod/redir.php already?
4681 * This use api_user() and api_login()
4684 * c_url: url of remote contact to auth to
4685 * url: string, url to redirect after auth
4687 function api_friendica_remoteauth()
4689 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4690 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4692 if ($url === '' || $c_url === '') {
4693 throw new BadRequestException("Wrong parameters.");
4696 $c_url = normalise_link($c_url);
4700 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4702 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
4703 throw new BadRequestException("Unknown contact");
4706 $cid = $contact['id'];
4708 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4710 if ($contact['duplex'] && $contact['issued-id']) {
4711 $orig_id = $contact['issued-id'];
4712 $dfrn_id = '1:' . $orig_id;
4714 if ($contact['duplex'] && $contact['dfrn-id']) {
4715 $orig_id = $contact['dfrn-id'];
4716 $dfrn_id = '0:' . $orig_id;
4719 $sec = random_string();
4721 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4722 'sec' => $sec, 'expire' => time() + 45];
4723 DBA::insert('profile_check', $fields);
4725 logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
4726 $dest = ($url ? '&destination_url=' . $url : '');
4728 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4729 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4730 . '&type=profile&sec=' . $sec . $dest
4733 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4736 * @brief Return the item shared, if the item contains only the [share] tag
4738 * @param array $item Sharer item
4739 * @return array|false Shared item or false if not a reshare
4741 function api_share_as_retweet(&$item)
4743 $body = trim($item["body"]);
4745 if (Diaspora::isReshare($body, false)===false) {
4749 /// @TODO "$1" should maybe mean '$1' ?
4750 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4752 * Skip if there is no shared message in there
4753 * we already checked this in diaspora::isReshare()
4754 * but better one more than one less...
4756 if ($body == $attributes) {
4761 // build the fake reshared item
4762 $reshared_item = $item;
4765 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4766 if ($matches[1] != "") {
4767 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4770 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4771 if ($matches[1] != "") {
4772 $author = $matches[1];
4776 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4777 if ($matches[1] != "") {
4778 $profile = $matches[1];
4781 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4782 if ($matches[1] != "") {
4783 $profile = $matches[1];
4787 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4788 if ($matches[1] != "") {
4789 $avatar = $matches[1];
4792 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4793 if ($matches[1] != "") {
4794 $avatar = $matches[1];
4798 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4799 if ($matches[1] != "") {
4800 $link = $matches[1];
4803 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4804 if ($matches[1] != "") {
4805 $link = $matches[1];
4809 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4810 if ($matches[1] != "") {
4811 $posted = $matches[1];
4814 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4815 if ($matches[1] != "") {
4816 $posted = $matches[1];
4819 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4821 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4825 $reshared_item["body"] = $shared_body;
4826 $reshared_item["author-name"] = $author;
4827 $reshared_item["author-link"] = $profile;
4828 $reshared_item["author-avatar"] = $avatar;
4829 $reshared_item["plink"] = $link;
4830 $reshared_item["created"] = $posted;
4831 $reshared_item["edited"] = $posted;
4833 return $reshared_item;
4838 * @param string $profile
4840 * @return string|false
4841 * @todo remove trailing junk from profile url
4842 * @todo pump.io check has to check the website
4844 function api_get_nick($profile)
4849 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4850 DBA::escape(normalise_link($profile))
4853 if (DBA::isResult($r)) {
4854 $nick = $r[0]["nick"];
4859 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4860 DBA::escape(normalise_link($profile))
4863 if (DBA::isResult($r)) {
4864 $nick = $r[0]["nick"];
4869 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4870 if ($friendica != $profile) {
4876 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4877 if ($diaspora != $profile) {
4883 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4884 if ($twitter != $profile) {
4891 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4892 if ($StatusnetHost != $profile) {
4893 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4894 if ($StatusnetUser != $profile) {
4895 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4896 $user = json_decode($UserData);
4898 $nick = $user->screen_name;
4904 // To-Do: look at the page if its really a pumpio site
4905 //if (!$nick == "") {
4906 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4907 // if ($pumpio != $profile)
4909 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4922 * @param array $item
4926 function api_in_reply_to($item)
4930 $in_reply_to['status_id'] = null;
4931 $in_reply_to['user_id'] = null;
4932 $in_reply_to['status_id_str'] = null;
4933 $in_reply_to['user_id_str'] = null;
4934 $in_reply_to['screen_name'] = null;
4936 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4937 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
4938 if (DBA::isResult($parent)) {
4939 $in_reply_to['status_id'] = intval($parent['id']);
4941 $in_reply_to['status_id'] = intval($item['parent']);
4944 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4946 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
4947 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
4949 if (DBA::isResult($parent)) {
4950 if ($parent['author-nick'] == "") {
4951 $parent['author-nick'] = api_get_nick($parent['author-link']);
4954 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
4955 $in_reply_to['user_id'] = intval($parent['author-id']);
4956 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
4959 // There seems to be situation, where both fields are identical:
4960 // https://github.com/friendica/friendica/issues/1010
4961 // This is a bugfix for that.
4962 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4963 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4964 $in_reply_to['status_id'] = null;
4965 $in_reply_to['user_id'] = null;
4966 $in_reply_to['status_id_str'] = null;
4967 $in_reply_to['user_id_str'] = null;
4968 $in_reply_to['screen_name'] = null;
4972 return $in_reply_to;
4977 * @param string $text
4981 function api_clean_plain_items($text)
4983 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4985 $text = BBCode::cleanPictureLinks($text);
4986 $URLSearchString = "^\[\]";
4988 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4990 if ($include_entities == "true") {
4991 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4994 // Simplify "attachment" element
4995 $text = api_clean_attachments($text);
5001 * @brief Removes most sharing information for API text export
5003 * @param string $body The original body
5005 * @return string Cleaned body
5007 function api_clean_attachments($body)
5009 $data = BBCode::getAttachmentData($body);
5016 if (isset($data["text"])) {
5017 $body = $data["text"];
5019 if (($body == "") && isset($data["title"])) {
5020 $body = $data["title"];
5022 if (isset($data["url"])) {
5023 $body .= "\n".$data["url"];
5025 $body .= $data["after"];
5032 * @param array $contacts
5036 function api_best_nickname(&$contacts)
5040 if (count($contacts) == 0) {
5044 foreach ($contacts as $contact) {
5045 if ($contact["network"] == "") {
5046 $contact["network"] = "dfrn";
5047 $best_contact = [$contact];
5051 if (sizeof($best_contact) == 0) {
5052 foreach ($contacts as $contact) {
5053 if ($contact["network"] == "dfrn") {
5054 $best_contact = [$contact];
5059 if (sizeof($best_contact) == 0) {
5060 foreach ($contacts as $contact) {
5061 if ($contact["network"] == "dspr") {
5062 $best_contact = [$contact];
5067 if (sizeof($best_contact) == 0) {
5068 foreach ($contacts as $contact) {
5069 if ($contact["network"] == "stat") {
5070 $best_contact = [$contact];
5075 if (sizeof($best_contact) == 0) {
5076 foreach ($contacts as $contact) {
5077 if ($contact["network"] == "pump") {
5078 $best_contact = [$contact];
5083 if (sizeof($best_contact) == 0) {
5084 foreach ($contacts as $contact) {
5085 if ($contact["network"] == "twit") {
5086 $best_contact = [$contact];
5091 if (sizeof($best_contact) == 1) {
5092 $contacts = $best_contact;
5094 $contacts = [$contacts[0]];
5099 * Return all or a specified group of the user with the containing contacts.
5101 * @param string $type Return type (atom, rss, xml, json)
5103 * @return array|string
5105 function api_friendica_group_show($type)
5109 if (api_user() === false) {
5110 throw new ForbiddenException();
5114 $user_info = api_get_user($a);
5115 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5116 $uid = $user_info['uid'];
5118 // get data of the specified group id or all groups if not specified
5121 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5125 // error message if specified gid is not in database
5126 if (!DBA::isResult($r)) {
5127 throw new BadRequestException("gid not available");
5131 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5136 // loop through all groups and retrieve all members for adding data in the user array
5138 foreach ($r as $rr) {
5139 $members = Contact::getByGroupId($rr['id']);
5142 if ($type == "xml") {
5143 $user_element = "users";
5145 foreach ($members as $member) {
5146 $user = api_get_user($a, $member['nurl']);
5147 $users[$k++.":user"] = $user;
5150 $user_element = "user";
5151 foreach ($members as $member) {
5152 $user = api_get_user($a, $member['nurl']);
5156 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5158 return api_format_data("groups", $type, ['group' => $grps]);
5160 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5164 * Delete the specified group of the user.
5166 * @param string $type Return type (atom, rss, xml, json)
5168 * @return array|string
5170 function api_friendica_group_delete($type)
5174 if (api_user() === false) {
5175 throw new ForbiddenException();
5179 $user_info = api_get_user($a);
5180 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5181 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5182 $uid = $user_info['uid'];
5184 // error if no gid specified
5185 if ($gid == 0 || $name == "") {
5186 throw new BadRequestException('gid or name not specified');
5189 // get data of the specified group id
5191 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5195 // error message if specified gid is not in database
5196 if (!DBA::isResult($r)) {
5197 throw new BadRequestException('gid not available');
5200 // get data of the specified group id and group name
5202 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5207 // error message if specified gid is not in database
5208 if (!DBA::isResult($rname)) {
5209 throw new BadRequestException('wrong group name');
5213 $ret = Group::removeByName($uid, $name);
5216 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5217 return api_format_data("group_delete", $type, ['result' => $success]);
5219 throw new BadRequestException('other API error');
5222 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5227 * @param string $type Return type (atom, rss, xml, json)
5229 * @return array|string
5230 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5232 function api_lists_destroy($type)
5236 if (api_user() === false) {
5237 throw new ForbiddenException();
5241 $user_info = api_get_user($a);
5242 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5243 $uid = $user_info['uid'];
5245 // error if no gid specified
5247 throw new BadRequestException('gid not specified');
5250 // get data of the specified group id
5251 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5252 // error message if specified gid is not in database
5254 throw new BadRequestException('gid not available');
5257 if (Group::remove($gid)) {
5259 'name' => $group['name'],
5260 'id' => intval($gid),
5261 'id_str' => (string) $gid,
5262 'user' => $user_info
5265 return api_format_data("lists", $type, ['lists' => $list]);
5268 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5271 * Add a new group to the database.
5273 * @param string $name Group name
5274 * @param int $uid User ID
5275 * @param array $users List of users to add to the group
5279 function group_create($name, $uid, $users = [])
5281 // error if no name specified
5283 throw new BadRequestException('group name not specified');
5286 // get data of the specified group name
5288 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5292 // error message if specified group name already exists
5293 if (DBA::isResult($rname)) {
5294 throw new BadRequestException('group name already exists');
5297 // check if specified group name is a deleted group
5299 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5303 // error message if specified group name already exists
5304 if (DBA::isResult($rname)) {
5305 $reactivate_group = true;
5309 $ret = Group::create($uid, $name);
5311 $gid = Group::getIdByName($uid, $name);
5313 throw new BadRequestException('other API error');
5317 $erroraddinguser = false;
5319 foreach ($users as $user) {
5320 $cid = $user['cid'];
5321 // check if user really exists as contact
5323 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5327 if (count($contact)) {
5328 Group::addMember($gid, $cid);
5330 $erroraddinguser = true;
5331 $errorusers[] = $cid;
5335 // return success message incl. missing users in array
5336 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5338 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5342 * Create the specified group with the posted array of contacts.
5344 * @param string $type Return type (atom, rss, xml, json)
5346 * @return array|string
5348 function api_friendica_group_create($type)
5352 if (api_user() === false) {
5353 throw new ForbiddenException();
5357 $user_info = api_get_user($a);
5358 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5359 $uid = $user_info['uid'];
5360 $json = json_decode($_POST['json'], true);
5361 $users = $json['user'];
5363 $success = group_create($name, $uid, $users);
5365 return api_format_data("group_create", $type, ['result' => $success]);
5367 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5370 * Create a new group.
5372 * @param string $type Return type (atom, rss, xml, json)
5374 * @return array|string
5375 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5377 function api_lists_create($type)
5381 if (api_user() === false) {
5382 throw new ForbiddenException();
5386 $user_info = api_get_user($a);
5387 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5388 $uid = $user_info['uid'];
5390 $success = group_create($name, $uid);
5391 if ($success['success']) {
5393 'name' => $success['name'],
5394 'id' => intval($success['gid']),
5395 'id_str' => (string) $success['gid'],
5396 'user' => $user_info
5399 return api_format_data("lists", $type, ['lists'=>$grp]);
5402 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5405 * Update the specified group with the posted array of contacts.
5407 * @param string $type Return type (atom, rss, xml, json)
5409 * @return array|string
5411 function api_friendica_group_update($type)
5415 if (api_user() === false) {
5416 throw new ForbiddenException();
5420 $user_info = api_get_user($a);
5421 $uid = $user_info['uid'];
5422 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5423 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5424 $json = json_decode($_POST['json'], true);
5425 $users = $json['user'];
5427 // error if no name specified
5429 throw new BadRequestException('group name not specified');
5432 // error if no gid specified
5434 throw new BadRequestException('gid not specified');
5438 $members = Contact::getByGroupId($gid);
5439 foreach ($members as $member) {
5440 $cid = $member['id'];
5441 foreach ($users as $user) {
5442 $found = ($user['cid'] == $cid ? true : false);
5444 if (!isset($found) || !$found) {
5445 Group::removeMemberByName($uid, $name, $cid);
5450 $erroraddinguser = false;
5452 foreach ($users as $user) {
5453 $cid = $user['cid'];
5454 // check if user really exists as contact
5456 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5461 if (count($contact)) {
5462 Group::addMember($gid, $cid);
5464 $erroraddinguser = true;
5465 $errorusers[] = $cid;
5469 // return success message incl. missing users in array
5470 $status = ($erroraddinguser ? "missing user" : "ok");
5471 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5472 return api_format_data("group_update", $type, ['result' => $success]);
5475 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5478 * Update information about a group.
5480 * @param string $type Return type (atom, rss, xml, json)
5482 * @return array|string
5483 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5485 function api_lists_update($type)
5489 if (api_user() === false) {
5490 throw new ForbiddenException();
5494 $user_info = api_get_user($a);
5495 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5496 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5497 $uid = $user_info['uid'];
5499 // error if no gid specified
5501 throw new BadRequestException('gid not specified');
5504 // get data of the specified group id
5505 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5506 // error message if specified gid is not in database
5508 throw new BadRequestException('gid not available');
5511 if (Group::update($gid, $name)) {
5514 'id' => intval($gid),
5515 'id_str' => (string) $gid,
5516 'user' => $user_info
5519 return api_format_data("lists", $type, ['lists' => $list]);
5523 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5527 * @param string $type Return type (atom, rss, xml, json)
5529 * @return array|string
5531 function api_friendica_activity($type)
5535 if (api_user() === false) {
5536 throw new ForbiddenException();
5538 $verb = strtolower($a->argv[3]);
5539 $verb = preg_replace("|\..*$|", "", $verb);
5541 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5543 $res = Item::performLike($id, $verb);
5546 if ($type == "xml") {
5551 return api_format_data('ok', $type, ['ok' => $ok]);
5553 throw new BadRequestException('Error adding activity');
5557 /// @TODO move to top of file or somewhere better
5558 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5559 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5560 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5561 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5562 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5563 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5564 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5565 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5566 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5567 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5570 * @brief Returns notifications
5572 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5573 * @return string|array
5575 function api_friendica_notification($type)
5579 if (api_user() === false) {
5580 throw new ForbiddenException();
5583 throw new BadRequestException("Invalid argument count");
5585 $nm = new NotificationsManager();
5587 $notes = $nm->getAll([], "+seen -date", 50);
5589 if ($type == "xml") {
5591 if (!empty($notes)) {
5592 foreach ($notes as $note) {
5593 $xmlnotes[] = ["@attributes" => $note];
5600 return api_format_data("notes", $type, ['note' => $notes]);
5604 * POST request with 'id' param as notification id
5606 * @brief Set notification as seen and returns associated item (if possible)
5608 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5609 * @return string|array
5611 function api_friendica_notification_seen($type)
5614 $user_info = api_get_user($a);
5616 if (api_user() === false || $user_info === false) {
5617 throw new ForbiddenException();
5620 throw new BadRequestException("Invalid argument count");
5623 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5625 $nm = new NotificationsManager();
5626 $note = $nm->getByID($id);
5627 if (is_null($note)) {
5628 throw new BadRequestException("Invalid argument");
5631 $nm->setSeen($note);
5632 if ($note['otype']=='item') {
5633 // would be really better with an ItemsManager and $im->getByID() :-P
5634 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5635 if (DBA::isResult($item)) {
5636 // we found the item, return it to the user
5637 $ret = api_format_items([$item], $user_info, false, $type);
5638 $data = ['status' => $ret];
5639 return api_format_data("status", $type, $data);
5641 // the item can't be found, but we set the note as seen, so we count this as a success
5643 return api_format_data('result', $type, ['result' => "success"]);
5646 /// @TODO move to top of file or somewhere better
5647 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5648 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5651 * @brief update a direct_message to seen state
5653 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5654 * @return string|array (success result=ok, error result=error with error message)
5656 function api_friendica_direct_messages_setseen($type)
5659 if (api_user() === false) {
5660 throw new ForbiddenException();
5664 $user_info = api_get_user($a);
5665 $uid = $user_info['uid'];
5666 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5668 // return error if id is zero
5670 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5671 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5674 // error message if specified id is not in database
5675 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5676 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5677 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5680 // update seen indicator
5681 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5685 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5686 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5688 $answer = ['result' => 'error', 'message' => 'unknown error'];
5689 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5693 /// @TODO move to top of file or somewhere better
5694 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5697 * @brief search for direct_messages containing a searchstring through api
5699 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5700 * @param string $box
5701 * @return string|array (success: success=true if found and search_result contains found messages,
5702 * success=false if nothing was found, search_result='nothing found',
5703 * error: result=error with error message)
5705 function api_friendica_direct_messages_search($type, $box = "")
5709 if (api_user() === false) {
5710 throw new ForbiddenException();
5714 $user_info = api_get_user($a);
5715 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5716 $uid = $user_info['uid'];
5718 // error if no searchstring specified
5719 if ($searchstring == "") {
5720 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5721 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5724 // get data for the specified searchstring
5726 "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",
5728 DBA::escape('%'.$searchstring.'%')
5731 $profile_url = $user_info["url"];
5733 // message if nothing was found
5734 if (!DBA::isResult($r)) {
5735 $success = ['success' => false, 'search_results' => 'problem with query'];
5736 } elseif (count($r) == 0) {
5737 $success = ['success' => false, 'search_results' => 'nothing found'];
5740 foreach ($r as $item) {
5741 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5742 $recipient = $user_info;
5743 $sender = api_get_user($a, normalise_link($item['contact-url']));
5744 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5745 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5746 $sender = $user_info;
5749 if (isset($recipient) && isset($sender)) {
5750 $ret[] = api_format_messages($item, $recipient, $sender);
5753 $success = ['success' => true, 'search_results' => $ret];
5756 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5759 /// @TODO move to top of file or somewhere better
5760 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5763 * @brief return data of all the profiles a user has to the client
5765 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5766 * @return string|array
5768 function api_friendica_profile_show($type)
5772 if (api_user() === false) {
5773 throw new ForbiddenException();
5777 $profile_id = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5779 // retrieve general information about profiles for user
5780 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5781 $directory = Config::get('system', 'directory');
5783 // get data of the specified profile id or all profiles of the user if not specified
5784 if ($profile_id != 0) {
5786 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5791 // error message if specified gid is not in database
5792 if (!DBA::isResult($r)) {
5793 throw new BadRequestException("profile_id not available");
5797 "SELECT * FROM `profile` WHERE `uid` = %d",
5801 // loop through all returned profiles and retrieve data and users
5804 foreach ($r as $rr) {
5805 $profile = api_format_items_profiles($rr);
5807 // select all users from contact table, loop and prepare standard return for user data
5810 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5815 foreach ($nurls as $nurl) {
5816 $user = api_get_user($a, $nurl['nurl']);
5817 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5819 $profile['users'] = $users;
5821 // add prepared profile data to array for final return
5822 if ($type == "xml") {
5823 $profiles[$k++ . ":profile"] = $profile;
5825 $profiles[] = $profile;
5829 // return settings, authenticated user and profiles data
5830 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
5832 $result = ['multi_profiles' => $multi_profiles ? true : false,
5833 'global_dir' => $directory,
5834 'friendica_owner' => api_get_user($a, $self['nurl']),
5835 'profiles' => $profiles];
5836 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5838 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5841 * Returns a list of saved searches.
5843 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5845 * @param string $type Return format: json or xml
5847 * @return string|array
5849 function api_saved_searches_list($type)
5851 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
5854 while ($term = $terms->fetch()) {
5856 'created_at' => api_date(time()),
5857 'id' => intval($term['id']),
5858 'id_str' => $term['id'],
5859 'name' => $term['term'],
5861 'query' => $term['term']
5867 return api_format_data("terms", $type, ['terms' => $result]);
5870 /// @TODO move to top of file or somewhere better
5871 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5874 @TODO Maybe open to implement?
5876 [pagename] => api/1.1/statuses/lookup.json
5877 [id] => 605138389168451584
5878 [include_cards] => true
5879 [cards_platform] => Android-12
5880 [include_entities] => true
5881 [include_my_retweet] => 1
5883 [include_reply_count] => true
5884 [include_descendent_reply_count] => true
5888 Not implemented by now:
5889 statuses/retweets_of_me
5894 account/update_location
5895 account/update_profile_background_image
5898 friendica/profile/update
5899 friendica/profile/create
5900 friendica/profile/delete
5902 Not implemented in status.net:
5903 statuses/retweeted_to_me
5904 statuses/retweeted_by_me
5905 direct_messages/destroy
5907 account/update_delivery_device
5908 notifications/follow