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\Authentication;
16 use Friendica\Core\Config;
17 use Friendica\Core\L10n;
18 use Friendica\Core\Logger;
19 use Friendica\Core\NotificationsManager;
20 use Friendica\Core\PConfig;
21 use Friendica\Core\Protocol;
22 use Friendica\Core\System;
23 use Friendica\Core\Worker;
24 use Friendica\Database\DBA;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Group;
27 use Friendica\Model\Item;
28 use Friendica\Model\Mail;
29 use Friendica\Model\Photo;
30 use Friendica\Model\User;
31 use Friendica\Network\FKOAuth1;
32 use Friendica\Network\HTTPException;
33 use Friendica\Network\HTTPException\BadRequestException;
34 use Friendica\Network\HTTPException\ForbiddenException;
35 use Friendica\Network\HTTPException\InternalServerErrorException;
36 use Friendica\Network\HTTPException\MethodNotAllowedException;
37 use Friendica\Network\HTTPException\NotFoundException;
38 use Friendica\Network\HTTPException\NotImplementedException;
39 use Friendica\Network\HTTPException\TooManyRequestsException;
40 use Friendica\Network\HTTPException\UnauthorizedException;
41 use Friendica\Object\Image;
42 use Friendica\Protocol\Diaspora;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\Network;
45 use Friendica\Util\Proxy as ProxyUtils;
46 use Friendica\Util\Strings;
47 use Friendica\Util\XML;
49 require_once 'mod/share.php';
50 require_once 'mod/item.php';
51 require_once 'mod/wall_upload.php';
53 define('API_METHOD_ANY', '*');
54 define('API_METHOD_GET', 'GET');
55 define('API_METHOD_POST', 'POST,PUT');
56 define('API_METHOD_DELETE', 'POST,DELETE');
62 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
63 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
64 * into a page, and visitors will post something without noticing it).
66 * @brief Auth API user
70 if (!empty($_SESSION['allow_api'])) {
78 * Clients can send 'source' parameter to be show in post metadata
79 * as "sent via <source>".
80 * Some clients doesn't send a source param, we support ones we know
83 * @brief Get source name from API client
86 * Client source name, default to "api" if unset/unknown
90 if (requestdata('source')) {
91 return requestdata('source');
94 // Support for known clients that doesn't send a source name
95 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
96 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
100 Logger::log("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], Logger::DEBUG);
102 Logger::log("Empty user-agent", Logger::DEBUG);
109 * @brief Format date for API
111 * @param string $str Source date, as UTC
112 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
114 function api_date($str)
116 // Wed May 23 06:01:13 +0000 2007
117 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
121 * Register a function to be the endpoint for defined API path.
123 * @brief Register API endpoint
125 * @param string $path API URL path, relative to System::baseUrl()
126 * @param string $func Function name to call on path request
127 * @param bool $auth API need logged user
128 * @param string $method HTTP method reqiured to call this endpoint.
129 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
130 * Default to API_METHOD_ANY
132 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
142 // Workaround for hotot
143 $path = str_replace("api/", "api/1.1/", $path);
153 * Log in user via OAuth1 or Simple HTTP Auth.
154 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
156 * @brief Login API user
158 * @param object $a App
159 * @hook 'authenticate'
161 * 'username' => username from login form
162 * 'password' => password from login form
163 * 'authenticated' => return status,
164 * 'user_record' => return authenticated user record
166 * array $user logged user record
168 function api_login(App $a)
170 $oauth1 = new FKOAuth1();
173 $request = OAuthRequest::from_request();
174 list($consumer, $token) = $oauth1->verify_request($request);
175 if (!is_null($token)) {
176 $oauth1->loginUser($token->uid);
177 Addon::callHooks('logged_in', $a->user);
180 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
181 var_dump($consumer, $token);
183 } catch (Exception $e) {
187 // workaround for HTTP-auth in CGI mode
188 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
189 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
190 if (strlen($userpass)) {
191 list($name, $password) = explode(':', $userpass);
192 $_SERVER['PHP_AUTH_USER'] = $name;
193 $_SERVER['PHP_AUTH_PW'] = $password;
197 if (empty($_SERVER['PHP_AUTH_USER'])) {
198 Logger::log('API_login: ' . print_r($_SERVER, true), Logger::DEBUG);
199 header('WWW-Authenticate: Basic realm="Friendica"');
200 throw new UnauthorizedException("This API requires login");
203 $user = defaults($_SERVER, 'PHP_AUTH_USER', '');
204 $password = defaults($_SERVER, 'PHP_AUTH_PW', '');
206 // allow "user@server" login (but ignore 'server' part)
207 $at = strstr($user, "@", true);
212 // next code from mod/auth.php. needs better solution
216 'username' => trim($user),
217 'password' => trim($password),
218 'authenticated' => 0,
219 'user_record' => null,
223 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
224 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
225 * and later addons should not interfere with an earlier one that succeeded.
227 Addon::callHooks('authenticate', $addon_auth);
229 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
230 $record = $addon_auth['user_record'];
232 $user_id = User::authenticate(trim($user), trim($password));
233 if ($user_id !== false) {
234 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
238 if (!DBA::isResult($record)) {
239 Logger::log('API_login failure: ' . print_r($_SERVER, true), Logger::DEBUG);
240 header('WWW-Authenticate: Basic realm="Friendica"');
241 //header('HTTP/1.0 401 Unauthorized');
242 //die('This api requires login');
243 throw new UnauthorizedException("This API requires login");
246 Authentication::setAuthenticatedSessionForUser($record);
248 $_SESSION["allow_api"] = true;
250 Addon::callHooks('logged_in', $a->user);
254 * API endpoints can define which HTTP method to accept when called.
255 * This function check the current HTTP method agains endpoint
258 * @brief Check HTTP method of called API
260 * @param string $method Required methods, uppercase, separated by comma
263 function api_check_method($method)
265 if ($method == "*") {
268 return (stripos($method, defaults($_SERVER, 'REQUEST_METHOD', 'GET')) !== false);
272 * Authenticate user, call registered API function, set HTTP headers
274 * @brief Main API entry point
276 * @param object $a App
277 * @return string|array API call result
279 function api_call(App $a)
281 global $API, $called_api;
284 if (strpos($a->query_string, ".xml") > 0) {
287 if (strpos($a->query_string, ".json") > 0) {
290 if (strpos($a->query_string, ".rss") > 0) {
293 if (strpos($a->query_string, ".atom") > 0) {
298 foreach ($API as $p => $info) {
299 if (strpos($a->query_string, $p) === 0) {
300 if (!api_check_method($info['method'])) {
301 throw new MethodNotAllowedException();
304 $called_api = explode("/", $p);
305 //unset($_SERVER['PHP_AUTH_USER']);
307 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
308 if (!empty($info['auth']) && api_user() === false) {
312 Logger::log('API call for ' . $a->user['username'] . ': ' . $a->query_string);
313 Logger::log('API parameters: ' . print_r($_REQUEST, true));
315 $stamp = microtime(true);
316 $return = call_user_func($info['func'], $type);
317 $duration = (float) (microtime(true) - $stamp);
318 Logger::log("API call duration: " . round($duration, 2) . "\t" . $a->query_string, Logger::DEBUG);
320 if (Config::get("system", "profiler")) {
321 $duration = microtime(true)-$a->performance["start"];
323 /// @TODO round() really everywhere?
325 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
326 "Database: %s/%s, Cache %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
327 round($a->performance["database"] - $a->performance["database_write"], 3),
328 round($a->performance["database_write"], 3),
329 round($a->performance["cache"], 3),
330 round($a->performance["cache_write"], 3),
331 round($a->performance["network"], 2),
332 round($a->performance["file"], 2),
333 round($duration - ($a->performance["database"]
334 + $a->performance["cache"] + $a->performance["cache_write"]
335 + $a->performance["network"] + $a->performance["file"]), 2),
341 if (Config::get("rendertime", "callstack")) {
342 $o = "Database Read:\n";
343 foreach ($a->callstack["database"] as $func => $time) {
344 $time = round($time, 3);
346 $o .= $func . ": " . $time . "\n";
349 $o .= "\nDatabase Write:\n";
350 foreach ($a->callstack["database_write"] as $func => $time) {
351 $time = round($time, 3);
353 $o .= $func . ": " . $time . "\n";
357 $o = "Cache Read:\n";
358 foreach ($a->callstack["cache"] as $func => $time) {
359 $time = round($time, 3);
361 $o .= $func . ": " . $time . "\n";
364 $o .= "\nCache Write:\n";
365 foreach ($a->callstack["cache_write"] as $func => $time) {
366 $time = round($time, 3);
368 $o .= $func . ": " . $time . "\n";
372 $o .= "\nNetwork:\n";
373 foreach ($a->callstack["network"] as $func => $time) {
374 $time = round($time, 3);
376 $o .= $func . ": " . $time . "\n";
379 Logger::log($o, Logger::DEBUG);
383 if (false === $return) {
385 * api function returned false withour throw an
386 * exception. This should not happend, throw a 500
388 throw new InternalServerErrorException();
393 header("Content-Type: text/xml");
396 header("Content-Type: application/json");
397 $json = json_encode(end($return));
398 if (!empty($_GET['callback'])) {
399 $json = $_GET['callback'] . "(" . $json . ")";
404 header("Content-Type: application/rss+xml");
405 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
408 header("Content-Type: application/atom+xml");
409 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
416 Logger::log('API call not implemented: ' . $a->query_string);
417 throw new NotImplementedException();
418 } catch (HTTPException $e) {
419 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
420 return api_error($type, $e);
425 * @brief Format API error string
427 * @param string $type Return type (xml, json, rss, as)
428 * @param object $e HTTPException Error object
429 * @return string|array error message formatted as $type
431 function api_error($type, $e)
435 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
436 /// @TODO: https://dev.twitter.com/overview/api/response-codes
438 $error = ["error" => $error,
439 "code" => $e->httpcode . " " . $e->httpdesc,
440 "request" => $a->query_string];
442 $return = api_format_data('status', $type, ['status' => $error]);
446 header("Content-Type: text/xml");
449 header("Content-Type: application/json");
450 $return = json_encode($return);
453 header("Content-Type: application/rss+xml");
456 header("Content-Type: application/atom+xml");
464 * @brief Set values for RSS template
467 * @param array $arr Array to be passed to template
468 * @param array $user_info User info
470 * @todo find proper type-hints
472 function api_rss_extra(App $a, $arr, $user_info)
474 if (is_null($user_info)) {
475 $user_info = api_get_user($a);
478 $arr['$user'] = $user_info;
480 'alternate' => $user_info['url'],
481 'self' => System::baseUrl() . "/" . $a->query_string,
482 'base' => System::baseUrl(),
483 'updated' => api_date(null),
484 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
485 'language' => $user_info['lang'],
486 'logo' => System::baseUrl() . "/images/friendica-32.png",
494 * @brief Unique contact to contact url.
496 * @param int $id Contact id
497 * @return bool|string
498 * Contact url or False if contact id is unknown
500 function api_unique_id_to_nurl($id)
502 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
504 if (DBA::isResult($r)) {
512 * @brief Get user info array.
514 * @param object $a App
515 * @param int|string $contact_id Contact ID or URL
517 function api_get_user(App $a, $contact_id = null)
525 Logger::log("api_get_user: Fetching user data for user ".$contact_id, Logger::DEBUG);
527 // Searching for contact URL
528 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
529 $user = DBA::escape(Strings::normaliseLink($contact_id));
531 $extra_query = "AND `contact`.`nurl` = '%s' ";
532 if (api_user() !== false) {
533 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
537 // Searching for contact id with uid = 0
538 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
539 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
542 throw new BadRequestException("User ID ".$contact_id." not found.");
546 $extra_query = "AND `contact`.`nurl` = '%s' ";
547 if (api_user() !== false) {
548 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
552 if (is_null($user) && !empty($_GET['user_id'])) {
553 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
556 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
560 $extra_query = "AND `contact`.`nurl` = '%s' ";
561 if (api_user() !== false) {
562 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
565 if (is_null($user) && !empty($_GET['screen_name'])) {
566 $user = DBA::escape($_GET['screen_name']);
567 $extra_query = "AND `contact`.`nick` = '%s' ";
568 if (api_user() !== false) {
569 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
573 if (is_null($user) && !empty($_GET['profileurl'])) {
574 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
575 $extra_query = "AND `contact`.`nurl` = '%s' ";
576 if (api_user() !== false) {
577 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
581 // $called_api is the API path exploded on / and is expected to have at least 2 elements
582 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
583 $argid = count($called_api);
584 if (!empty($a->argv[$argid])) {
585 $data = explode(".", $a->argv[$argid]);
586 if (count($data) > 1) {
587 list($user, $null) = $data;
590 if (is_numeric($user)) {
591 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
595 $extra_query = "AND `contact`.`nurl` = '%s' ";
596 if (api_user() !== false) {
597 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
601 $user = DBA::escape($user);
602 $extra_query = "AND `contact`.`nick` = '%s' ";
603 if (api_user() !== false) {
604 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
609 Logger::log("api_get_user: user ".$user, Logger::DEBUG);
612 if (api_user() === false) {
616 $user = $_SESSION['uid'];
617 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
621 Logger::log('api_user: ' . $extra_query . ', user: ' . $user);
625 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
631 // Selecting the id by priority, friendica first
632 if (is_array($uinfo)) {
633 api_best_nickname($uinfo);
636 // if the contact wasn't found, fetch it from the contacts with uid = 0
637 if (!DBA::isResult($uinfo)) {
639 throw new BadRequestException("User not found.");
642 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
644 if (DBA::isResult($contact)) {
645 // If no nick where given, extract it from the address
646 if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
647 $contact['nick'] = api_get_nick($contact["url"]);
651 'id' => $contact["id"],
652 'id_str' => (string) $contact["id"],
653 'name' => $contact["name"],
654 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
655 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url']),
656 'description' => $contact["about"],
657 'profile_image_url' => $contact["micro"],
658 'profile_image_url_https' => $contact["micro"],
659 'profile_image_url_profile_size' => $contact["thumb"],
660 'profile_image_url_large' => $contact["photo"],
661 'url' => $contact["url"],
662 'protected' => false,
663 'followers_count' => 0,
664 'friends_count' => 0,
666 'created_at' => api_date($contact["created"]),
667 'favourites_count' => 0,
669 'time_zone' => 'UTC',
670 'geo_enabled' => false,
672 'statuses_count' => 0,
674 'contributors_enabled' => false,
675 'is_translator' => false,
676 'is_translation_enabled' => false,
677 'following' => false,
678 'follow_request_sent' => false,
679 'statusnet_blocking' => false,
680 'notifications' => false,
681 'statusnet_profile_url' => $contact["url"],
683 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
684 'pid' => Contact::getIdForURL($contact["url"], 0, true),
686 'network' => $contact["network"],
691 throw new BadRequestException("User ".$url." not found.");
695 if ($uinfo[0]['self']) {
696 if ($uinfo[0]['network'] == "") {
697 $uinfo[0]['network'] = Protocol::DFRN;
700 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
701 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
708 // Add a nick if it isn't present there
709 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
710 $uinfo[0]['nick'] = api_get_nick($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 = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
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()."/contact/".$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, 'owner-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 = defaults($_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 (!empty($_POST[$k])) {
1015 if (!empty($_GET[$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::log('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 = HTML::toBBCodeVideo($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]";
1059 $item_id = item_post($a);
1061 // output the post that we just posted.
1062 return api_status_show($type, $item_id);
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)
1080 if (api_user() === false) {
1081 Logger::log('api_statuses_update: no user');
1082 throw new ForbiddenException();
1087 // convert $_POST array items to the form we use for web posts.
1088 if (requestdata('htmlstatus')) {
1089 $txt = requestdata('htmlstatus');
1090 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1091 $txt = HTML::toBBCodeVideo($txt);
1093 $config = HTMLPurifier_Config::createDefault();
1094 $config->set('Cache.DefinitionImpl', null);
1096 $purifier = new HTMLPurifier($config);
1097 $txt = $purifier->purify($txt);
1099 $_REQUEST['body'] = HTML::toBBCode($txt);
1102 $_REQUEST['body'] = requestdata('status');
1105 $_REQUEST['title'] = requestdata('title');
1107 $parent = requestdata('in_reply_to_status_id');
1109 // Twidere sends "-1" if it is no reply ...
1110 if ($parent == -1) {
1114 if (ctype_digit($parent)) {
1115 $_REQUEST['parent'] = $parent;
1117 $_REQUEST['parent_uri'] = $parent;
1120 if (requestdata('lat') && requestdata('long')) {
1121 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1123 $_REQUEST['profile_uid'] = api_user();
1126 // Check for throttling (maximum posts per day, week and month)
1127 $throttle_day = Config::get('system', 'throttle_limit_day');
1128 if ($throttle_day > 0) {
1129 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1131 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1132 $posts_day = DBA::count('thread', $condition);
1134 if ($posts_day > $throttle_day) {
1135 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1136 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1137 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));
1141 $throttle_week = Config::get('system', 'throttle_limit_week');
1142 if ($throttle_week > 0) {
1143 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1145 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1146 $posts_week = DBA::count('thread', $condition);
1148 if ($posts_week > $throttle_week) {
1149 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1150 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1151 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));
1155 $throttle_month = Config::get('system', 'throttle_limit_month');
1156 if ($throttle_month > 0) {
1157 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1159 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1160 $posts_month = DBA::count('thread', $condition);
1162 if ($posts_month > $throttle_month) {
1163 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1164 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1165 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));
1170 if (!empty($_FILES['media'])) {
1171 // upload the image if we have one
1172 $picture = wall_upload_post($a, false);
1173 if (is_array($picture)) {
1174 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1178 // To-Do: Multiple IDs
1179 if (requestdata('media_ids')) {
1181 "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",
1182 intval(requestdata('media_ids')),
1185 if (DBA::isResult($r)) {
1186 $phototypes = Image::supportedTypes();
1187 $ext = $phototypes[$r[0]['type']];
1188 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1189 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1193 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1195 $_REQUEST['api_source'] = true;
1197 if (empty($_REQUEST['source'])) {
1198 $_REQUEST["source"] = api_source();
1201 // call out normal post function
1202 $item_id = item_post($a);
1204 // output the post that we just posted.
1205 return api_status_show($type, $item_id);
1208 /// @TODO move to top of file or somewhere better
1209 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1210 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1213 * Uploads an image to Friendica.
1216 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1218 function api_media_upload()
1222 if (api_user() === false) {
1223 Logger::log('no user');
1224 throw new ForbiddenException();
1229 if (empty($_FILES['media'])) {
1231 throw new BadRequestException("No media.");
1234 $media = wall_upload_post($a, false);
1237 throw new InternalServerErrorException();
1241 $returndata["media_id"] = $media["id"];
1242 $returndata["media_id_string"] = (string)$media["id"];
1243 $returndata["size"] = $media["size"];
1244 $returndata["image"] = ["w" => $media["width"],
1245 "h" => $media["height"],
1246 "image_type" => $media["type"],
1247 "preview" => $media["preview"]];
1249 Logger::log("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, $item_id = 0)
1267 $user_info = api_get_user($a);
1269 Logger::log('api_status_show: user_info: '.print_r($user_info, true), Logger::DEBUG);
1271 if ($type == "raw") {
1272 $privacy_sql = "AND NOT `private`";
1277 if (!empty($item_id)) {
1278 // Get the item with the given id
1279 $condition = ['id' => $item_id];
1281 // get last public wall message
1282 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1283 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1285 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1287 if (DBA::isResult($lastwall)) {
1288 $in_reply_to = api_in_reply_to($lastwall);
1290 $converted = api_convert_item($lastwall);
1292 if ($type == "xml") {
1293 $geo = "georss:point";
1299 'created_at' => api_date($lastwall['created']),
1300 'id' => intval($lastwall['id']),
1301 'id_str' => (string) $lastwall['id'],
1302 'text' => $converted["text"],
1303 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1304 'truncated' => false,
1305 'in_reply_to_status_id' => $in_reply_to['status_id'],
1306 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1307 'in_reply_to_user_id' => $in_reply_to['user_id'],
1308 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1309 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1310 'user' => $user_info,
1312 'coordinates' => '',
1314 'contributors' => '',
1315 'is_quote_status' => false,
1316 'retweet_count' => 0,
1317 'favorite_count' => 0,
1318 'favorited' => $lastwall['starred'] ? true : false,
1319 'retweeted' => false,
1320 'possibly_sensitive' => false,
1322 'statusnet_html' => $converted["html"],
1323 'statusnet_conversation_id' => $lastwall['parent'],
1324 'external_url' => System::baseUrl() . '/display/' . $lastwall['guid'],
1327 if (count($converted["attachments"]) > 0) {
1328 $status_info["attachments"] = $converted["attachments"];
1331 if (count($converted["entities"]) > 0) {
1332 $status_info["entities"] = $converted["entities"];
1335 if ($status_info["source"] == 'web') {
1336 $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1337 } elseif (ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) != $status_info["source"]) {
1338 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']).')');
1341 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1342 unset($status_info["user"]["uid"]);
1343 unset($status_info["user"]["self"]);
1345 Logger::log('status_info: '.print_r($status_info, true), Logger::DEBUG);
1347 if ($type == "raw") {
1348 return $status_info;
1351 return api_format_data("statuses", $type, ['status' => $status_info]);
1356 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1357 * The author's most recent status will be returned inline.
1359 * @param string $type Return type (atom, rss, xml, json)
1360 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1362 function api_users_show($type)
1366 $user_info = api_get_user($a);
1368 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1369 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'private' => false];
1370 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1372 if (DBA::isResult($lastwall)) {
1373 $in_reply_to = api_in_reply_to($lastwall);
1375 $converted = api_convert_item($lastwall);
1377 if ($type == "xml") {
1378 $geo = "georss:point";
1383 $user_info['status'] = [
1384 'text' => $converted["text"],
1385 'truncated' => false,
1386 'created_at' => api_date($lastwall['created']),
1387 'in_reply_to_status_id' => $in_reply_to['status_id'],
1388 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1389 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1390 'id' => intval($lastwall['contact-id']),
1391 'id_str' => (string) $lastwall['contact-id'],
1392 'in_reply_to_user_id' => $in_reply_to['user_id'],
1393 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1394 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1396 'favorited' => $lastwall['starred'] ? true : false,
1397 'statusnet_html' => $converted["html"],
1398 'statusnet_conversation_id' => $lastwall['parent'],
1399 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1402 if (count($converted["attachments"]) > 0) {
1403 $user_info["status"]["attachments"] = $converted["attachments"];
1406 if (count($converted["entities"]) > 0) {
1407 $user_info["status"]["entities"] = $converted["entities"];
1410 if ($user_info["status"]["source"] == 'web') {
1411 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1414 if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
1415 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) . ')');
1419 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1420 unset($user_info["uid"]);
1421 unset($user_info["self"]);
1423 return api_format_data("user", $type, ['user' => $user_info]);
1426 /// @TODO move to top of file or somewhere better
1427 api_register_func('api/users/show', 'api_users_show');
1428 api_register_func('api/externalprofile/show', 'api_users_show');
1431 * Search a public user account.
1433 * @param string $type Return type (atom, rss, xml, json)
1435 * @return array|string
1436 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1438 function api_users_search($type)
1444 if (!empty($_GET['q'])) {
1445 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1447 if (!DBA::isResult($r)) {
1448 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1451 if (DBA::isResult($r)) {
1453 foreach ($r as $user) {
1454 $user_info = api_get_user($a, $user["id"]);
1456 if ($type == "xml") {
1457 $userlist[$k++.":user"] = $user_info;
1459 $userlist[] = $user_info;
1462 $userlist = ["users" => $userlist];
1464 throw new BadRequestException("User ".$_GET["q"]." not found.");
1467 throw new BadRequestException("No user specified.");
1470 return api_format_data("users", $type, $userlist);
1473 /// @TODO move to top of file or somewhere better
1474 api_register_func('api/users/search', 'api_users_search');
1477 * Return user objects
1479 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1481 * @param string $type Return format: json or xml
1483 * @return array|string
1484 * @throws NotFoundException if the results are empty.
1486 function api_users_lookup($type)
1490 if (!empty($_REQUEST['user_id'])) {
1491 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1493 $users[] = api_get_user(get_app(), $id);
1498 if (empty($users)) {
1499 throw new NotFoundException;
1502 return api_format_data("users", $type, ['users' => $users]);
1505 /// @TODO move to top of file or somewhere better
1506 api_register_func('api/users/lookup', 'api_users_lookup', true);
1509 * Returns statuses that match a specified query.
1511 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1513 * @param string $type Return format: json, xml, atom, rss
1515 * @return array|string
1516 * @throws BadRequestException if the "q" parameter is missing.
1518 function api_search($type)
1521 $user_info = api_get_user($a);
1523 if (api_user() === false || $user_info === false) {
1524 throw new ForbiddenException();
1529 if (empty($_REQUEST['q'])) {
1530 throw new BadRequestException("q parameter is required.");
1533 if (!empty($_REQUEST['rpp'])) {
1534 $count = $_REQUEST['rpp'];
1535 } elseif (!empty($_REQUEST['count'])) {
1536 $count = $_REQUEST['count'];
1541 $since_id = defaults($_REQUEST, 'since_id', 0);
1542 $max_id = defaults($_REQUEST, 'max_id', 0);
1543 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1545 $start = $page * $count;
1547 $condition = ["`gravity` IN (?, ?) AND `item`.`id` > ?
1548 AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1549 AND `item`.`body` LIKE CONCAT('%',?,'%')",
1550 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, api_user(), $_REQUEST['q']];
1553 $condition[0] .= " AND `item`.`id` <= ?";
1554 $condition[] = $max_id;
1557 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1558 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1560 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1562 return api_format_data("statuses", $type, $data);
1565 /// @TODO move to top of file or somewhere better
1566 api_register_func('api/search/tweets', 'api_search', true);
1567 api_register_func('api/search', 'api_search', true);
1570 * Returns the most recent statuses posted by the user and the users they follow.
1572 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1574 * @param string $type Return type (atom, rss, xml, json)
1576 * @todo Optional parameters
1577 * @todo Add reply info
1579 function api_statuses_home_timeline($type)
1582 $user_info = api_get_user($a);
1584 if (api_user() === false || $user_info === false) {
1585 throw new ForbiddenException();
1588 unset($_REQUEST["user_id"]);
1589 unset($_GET["user_id"]);
1591 unset($_REQUEST["screen_name"]);
1592 unset($_GET["screen_name"]);
1594 // get last network messages
1597 $count = defaults($_REQUEST, 'count', 20);
1598 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1602 $since_id = defaults($_REQUEST, 'since_id', 0);
1603 $max_id = defaults($_REQUEST, 'max_id', 0);
1604 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1605 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1607 $start = $page * $count;
1609 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1610 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1613 $condition[0] .= " AND `item`.`id` <= ?";
1614 $condition[] = $max_id;
1616 if ($exclude_replies) {
1617 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1619 if ($conversation_id > 0) {
1620 $condition[0] .= " AND `item`.`parent` = ?";
1621 $condition[] = $conversation_id;
1624 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1625 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1627 $items = Item::inArray($statuses);
1629 $ret = api_format_items($items, $user_info, false, $type);
1631 // Set all posts from the query above to seen
1633 foreach ($items as $item) {
1634 $idarray[] = intval($item["id"]);
1637 if (!empty($idarray)) {
1638 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1640 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1644 $data = ['status' => $ret];
1649 $data = api_rss_extra($a, $data, $user_info);
1653 return api_format_data("statuses", $type, $data);
1656 /// @TODO move to top of file or somewhere better
1657 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1658 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1661 * Returns the most recent statuses from public users.
1663 * @param string $type Return type (atom, rss, xml, json)
1665 * @return array|string
1667 function api_statuses_public_timeline($type)
1670 $user_info = api_get_user($a);
1672 if (api_user() === false || $user_info === false) {
1673 throw new ForbiddenException();
1676 // get last network messages
1679 $count = defaults($_REQUEST, 'count', 20);
1680 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
1684 $since_id = defaults($_REQUEST, 'since_id', 0);
1685 $max_id = defaults($_REQUEST, 'max_id', 0);
1686 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1687 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1689 $start = $page * $count;
1691 if ($exclude_replies && !$conversation_id) {
1692 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall`",
1693 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1696 $condition[0] .= " AND `thread`.`iid` <= ?";
1697 $condition[] = $max_id;
1700 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1701 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1703 $r = Item::inArray($statuses);
1705 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin`",
1706 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1709 $condition[0] .= " AND `item`.`id` <= ?";
1710 $condition[] = $max_id;
1712 if ($conversation_id > 0) {
1713 $condition[0] .= " AND `item`.`parent` = ?";
1714 $condition[] = $conversation_id;
1717 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1718 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1720 $r = Item::inArray($statuses);
1723 $ret = api_format_items($r, $user_info, false, $type);
1725 $data = ['status' => $ret];
1730 $data = api_rss_extra($a, $data, $user_info);
1734 return api_format_data("statuses", $type, $data);
1737 /// @TODO move to top of file or somewhere better
1738 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1741 * Returns the most recent statuses posted by users this node knows about.
1743 * @brief Returns the list of public federated posts this node knows about
1745 * @param string $type Return format: json, xml, atom, rss
1746 * @return array|string
1747 * @throws ForbiddenException
1749 function api_statuses_networkpublic_timeline($type)
1752 $user_info = api_get_user($a);
1754 if (api_user() === false || $user_info === false) {
1755 throw new ForbiddenException();
1758 $since_id = defaults($_REQUEST, 'since_id', 0);
1759 $max_id = defaults($_REQUEST, 'max_id', 0);
1762 $count = defaults($_REQUEST, 'count', 20);
1763 $page = defaults($_REQUEST, 'page', 1);
1767 $start = ($page - 1) * $count;
1769 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1770 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1773 $condition[0] .= " AND `thread`.`iid` <= ?";
1774 $condition[] = $max_id;
1777 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1778 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1780 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1782 $data = ['status' => $ret];
1787 $data = api_rss_extra($a, $data, $user_info);
1791 return api_format_data("statuses", $type, $data);
1794 /// @TODO move to top of file or somewhere better
1795 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1798 * Returns a single status.
1800 * @param string $type Return type (atom, rss, xml, json)
1802 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1804 function api_statuses_show($type)
1807 $user_info = api_get_user($a);
1809 if (api_user() === false || $user_info === false) {
1810 throw new ForbiddenException();
1814 $id = intval(defaults($a->argv, 3, 0));
1817 $id = intval(defaults($_REQUEST, 'id', 0));
1822 $id = intval(defaults($a->argv, 4, 0));
1825 Logger::log('API: api_statuses_show: ' . $id);
1827 $conversation = !empty($_REQUEST['conversation']);
1829 // try to fetch the item for the local user - or the public item, if there is no local one
1830 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1831 if (!DBA::isResult($uri_item)) {
1832 throw new BadRequestException("There is no status with this id.");
1835 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1836 if (!DBA::isResult($item)) {
1837 throw new BadRequestException("There is no status with this id.");
1842 if ($conversation) {
1843 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1844 $params = ['order' => ['id' => true]];
1846 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1850 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1852 /// @TODO How about copying this to above methods which don't check $r ?
1853 if (!DBA::isResult($statuses)) {
1854 throw new BadRequestException("There is no status with this id.");
1857 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1859 if ($conversation) {
1860 $data = ['status' => $ret];
1861 return api_format_data("statuses", $type, $data);
1863 $data = ['status' => $ret[0]];
1864 return api_format_data("status", $type, $data);
1868 /// @TODO move to top of file or somewhere better
1869 api_register_func('api/statuses/show', 'api_statuses_show', true);
1873 * @param string $type Return type (atom, rss, xml, json)
1875 * @todo nothing to say?
1877 function api_conversation_show($type)
1880 $user_info = api_get_user($a);
1882 if (api_user() === false || $user_info === false) {
1883 throw new ForbiddenException();
1887 $id = intval(defaults($a->argv , 3 , 0));
1888 $since_id = intval(defaults($_REQUEST, 'since_id', 0));
1889 $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
1890 $count = intval(defaults($_REQUEST, 'count' , 20));
1891 $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
1896 $start = $page * $count;
1899 $id = intval(defaults($_REQUEST, 'id', 0));
1904 $id = intval(defaults($a->argv, 4, 0));
1907 Logger::log('API: api_conversation_show: '.$id);
1909 // try to fetch the item for the local user - or the public item, if there is no local one
1910 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1911 if (!DBA::isResult($item)) {
1912 throw new BadRequestException("There is no status with this id.");
1915 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1916 if (!DBA::isResult($parent)) {
1917 throw new BadRequestException("There is no status with this id.");
1920 $id = $parent['id'];
1922 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1923 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1926 $condition[0] .= " AND `item`.`id` <= ?";
1927 $condition[] = $max_id;
1930 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1931 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1933 if (!DBA::isResult($statuses)) {
1934 throw new BadRequestException("There is no status with id $id.");
1937 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1939 $data = ['status' => $ret];
1940 return api_format_data("statuses", $type, $data);
1943 /// @TODO move to top of file or somewhere better
1944 api_register_func('api/conversation/show', 'api_conversation_show', true);
1945 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1950 * @param string $type Return type (atom, rss, xml, json)
1952 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1954 function api_statuses_repeat($type)
1960 if (api_user() === false) {
1961 throw new ForbiddenException();
1967 $id = intval(defaults($a->argv, 3, 0));
1970 $id = intval(defaults($_REQUEST, 'id', 0));
1975 $id = intval(defaults($a->argv, 4, 0));
1978 Logger::log('API: api_statuses_repeat: '.$id);
1980 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1981 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
1983 if (DBA::isResult($item) && $item['body'] != "") {
1984 if (strpos($item['body'], "[/share]") !== false) {
1985 $pos = strpos($item['body'], "[share");
1986 $post = substr($item['body'], $pos);
1988 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
1990 $post .= $item['body'];
1991 $post .= "[/share]";
1993 $_REQUEST['body'] = $post;
1994 $_REQUEST['profile_uid'] = api_user();
1995 $_REQUEST['api_source'] = true;
1997 if (empty($_REQUEST['source'])) {
1998 $_REQUEST["source"] = api_source();
2001 $item_id = item_post($a);
2003 throw new ForbiddenException();
2006 // output the post that we just posted.
2008 return api_status_show($type, $item_id);
2011 /// @TODO move to top of file or somewhere better
2012 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2015 * Destroys a specific status.
2017 * @param string $type Return type (atom, rss, xml, json)
2019 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2021 function api_statuses_destroy($type)
2025 if (api_user() === false) {
2026 throw new ForbiddenException();
2032 $id = intval(defaults($a->argv, 3, 0));
2035 $id = intval(defaults($_REQUEST, 'id', 0));
2040 $id = intval(defaults($a->argv, 4, 0));
2043 Logger::log('API: api_statuses_destroy: '.$id);
2045 $ret = api_statuses_show($type);
2047 Item::deleteForUser(['id' => $id], api_user());
2052 /// @TODO move to top of file or somewhere better
2053 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2056 * Returns the most recent mentions.
2058 * @param string $type Return type (atom, rss, xml, json)
2060 * @see http://developer.twitter.com/doc/get/statuses/mentions
2062 function api_statuses_mentions($type)
2065 $user_info = api_get_user($a);
2067 if (api_user() === false || $user_info === false) {
2068 throw new ForbiddenException();
2071 unset($_REQUEST["user_id"]);
2072 unset($_GET["user_id"]);
2074 unset($_REQUEST["screen_name"]);
2075 unset($_GET["screen_name"]);
2077 // get last network messages
2080 $since_id = defaults($_REQUEST, 'since_id', 0);
2081 $max_id = defaults($_REQUEST, 'max_id' , 0);
2082 $count = defaults($_REQUEST, 'count' , 20);
2083 $page = defaults($_REQUEST, 'page' , 1);
2088 $start = ($page - 1) * $count;
2090 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2091 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2092 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2095 $condition[0] .= " AND `item`.`id` <= ?";
2096 $condition[] = $max_id;
2099 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2100 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2102 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2104 $data = ['status' => $ret];
2109 $data = api_rss_extra($a, $data, $user_info);
2113 return api_format_data("statuses", $type, $data);
2116 /// @TODO move to top of file or somewhere better
2117 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2118 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2121 * Returns the most recent statuses posted by the user.
2123 * @brief Returns a user's public timeline
2125 * @param string $type Either "json" or "xml"
2126 * @return string|array
2127 * @throws ForbiddenException
2128 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2130 function api_statuses_user_timeline($type)
2133 $user_info = api_get_user($a);
2135 if (api_user() === false || $user_info === false) {
2136 throw new ForbiddenException();
2140 "api_statuses_user_timeline: api_user: ". api_user() .
2141 "\nuser_info: ".print_r($user_info, true) .
2142 "\n_REQUEST: ".print_r($_REQUEST, true),
2146 $since_id = defaults($_REQUEST, 'since_id', 0);
2147 $max_id = defaults($_REQUEST, 'max_id', 0);
2148 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2149 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
2152 $count = defaults($_REQUEST, 'count', 20);
2153 $page = defaults($_REQUEST, 'page', 1);
2157 $start = ($page - 1) * $count;
2159 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2160 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2162 if ($user_info['self'] == 1) {
2163 $condition[0] .= ' AND `item`.`wall` ';
2166 if ($exclude_replies) {
2167 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2170 if ($conversation_id > 0) {
2171 $condition[0] .= " AND `item`.`parent` = ?";
2172 $condition[] = $conversation_id;
2176 $condition[0] .= " AND `item`.`id` <= ?";
2177 $condition[] = $max_id;
2180 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2181 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2183 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2185 $data = ['status' => $ret];
2190 $data = api_rss_extra($a, $data, $user_info);
2194 return api_format_data("statuses", $type, $data);
2197 /// @TODO move to top of file or somewhere better
2198 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2201 * Star/unstar an item.
2202 * param: id : id of the item
2204 * @param string $type Return type (atom, rss, xml, json)
2206 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2208 function api_favorites_create_destroy($type)
2212 if (api_user() === false) {
2213 throw new ForbiddenException();
2216 // for versioned api.
2217 /// @TODO We need a better global soluton
2218 $action_argv_id = 2;
2219 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2220 $action_argv_id = 3;
2223 if ($a->argc <= $action_argv_id) {
2224 throw new BadRequestException("Invalid request.");
2226 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2227 if ($a->argc == $action_argv_id + 2) {
2228 $itemid = intval(defaults($a->argv, $action_argv_id + 1, 0));
2230 $itemid = intval(defaults($_REQUEST, 'id', 0));
2233 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2235 if (!DBA::isResult($item)) {
2236 throw new BadRequestException("Invalid item.");
2241 $item['starred'] = 1;
2244 $item['starred'] = 0;
2247 throw new BadRequestException("Invalid action ".$action);
2250 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2253 throw new InternalServerErrorException("DB error");
2257 $user_info = api_get_user($a);
2258 $rets = api_format_items([$item], $user_info, false, $type);
2261 $data = ['status' => $ret];
2266 $data = api_rss_extra($a, $data, $user_info);
2270 return api_format_data("status", $type, $data);
2273 /// @TODO move to top of file or somewhere better
2274 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2275 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2278 * Returns the most recent favorite statuses.
2280 * @param string $type Return type (atom, rss, xml, json)
2282 * @return string|array
2284 function api_favorites($type)
2289 $user_info = api_get_user($a);
2291 if (api_user() === false || $user_info === false) {
2292 throw new ForbiddenException();
2297 // in friendica starred item are private
2298 // return favorites only for self
2299 Logger::log('api_favorites: self:' . $user_info['self']);
2301 if ($user_info['self'] == 0) {
2305 $since_id = defaults($_REQUEST, 'since_id', 0);
2306 $max_id = defaults($_REQUEST, 'max_id', 0);
2307 $count = defaults($_GET, 'count', 20);
2308 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
2313 $start = $page*$count;
2315 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2316 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2318 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2321 $condition[0] .= " AND `item`.`id` <= ?";
2322 $condition[] = $max_id;
2325 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2327 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2330 $data = ['status' => $ret];
2335 $data = api_rss_extra($a, $data, $user_info);
2339 return api_format_data("statuses", $type, $data);
2342 /// @TODO move to top of file or somewhere better
2343 api_register_func('api/favorites', 'api_favorites', true);
2347 * @param array $item
2348 * @param array $recipient
2349 * @param array $sender
2353 function api_format_messages($item, $recipient, $sender)
2355 // standard meta information
2357 'id' => $item['id'],
2358 'sender_id' => $sender['id'],
2360 'recipient_id' => $recipient['id'],
2361 'created_at' => api_date(defaults($item, 'created', DateTimeFormat::utcNow())),
2362 'sender_screen_name' => $sender['screen_name'],
2363 'recipient_screen_name' => $recipient['screen_name'],
2364 'sender' => $sender,
2365 'recipient' => $recipient,
2367 'friendica_seen' => defaults($item, 'seen', 0),
2368 'friendica_parent_uri' => defaults($item, 'parent-uri', ''),
2371 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2372 if (isset($ret['sender']['uid'])) {
2373 unset($ret['sender']['uid']);
2375 if (isset($ret['sender']['self'])) {
2376 unset($ret['sender']['self']);
2378 if (isset($ret['recipient']['uid'])) {
2379 unset($ret['recipient']['uid']);
2381 if (isset($ret['recipient']['self'])) {
2382 unset($ret['recipient']['self']);
2385 //don't send title to regular StatusNET requests to avoid confusing these apps
2386 if (!empty($_GET['getText'])) {
2387 $ret['title'] = $item['title'];
2388 if ($_GET['getText'] == 'html') {
2389 $ret['text'] = BBCode::convert($item['body'], false);
2390 } elseif ($_GET['getText'] == 'plain') {
2391 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2394 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2396 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2397 unset($ret['sender']);
2398 unset($ret['recipient']);
2406 * @param array $item
2410 function api_convert_item($item)
2412 $body = $item['body'];
2413 $attachments = api_get_attachments($body);
2415 // Workaround for ostatus messages where the title is identically to the body
2416 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2417 $statusbody = trim(HTML::toPlaintext($html, 0));
2419 // handle data: images
2420 $statusbody = api_format_items_embeded_images($item, $statusbody);
2422 $statustitle = trim($item['title']);
2424 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2425 $statustext = trim($statusbody);
2427 $statustext = trim($statustitle."\n\n".$statusbody);
2430 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($statustext)> 1000)) {
2431 $statustext = substr($statustext, 0, 1000) . "... \n" . defaults($item, 'plink', '');
2434 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2436 // Workaround for clients with limited HTML parser functionality
2437 $search = ["<br>", "<blockquote>", "</blockquote>",
2438 "<h1>", "</h1>", "<h2>", "</h2>",
2439 "<h3>", "</h3>", "<h4>", "</h4>",
2440 "<h5>", "</h5>", "<h6>", "</h6>"];
2441 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2442 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2443 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2444 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2445 $statushtml = str_replace($search, $replace, $statushtml);
2447 if ($item['title'] != "") {
2448 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2452 $oldtext = $statushtml;
2453 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2454 } while ($oldtext != $statushtml);
2456 if (substr($statushtml, 0, 4) == '<br>') {
2457 $statushtml = substr($statushtml, 4);
2460 if (substr($statushtml, 0, -4) == '<br>') {
2461 $statushtml = substr($statushtml, -4);
2464 // feeds without body should contain the link
2465 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2466 $statushtml .= BBCode::convert($item['plink']);
2469 $entities = api_get_entitities($statustext, $body);
2472 "text" => $statustext,
2473 "html" => $statushtml,
2474 "attachments" => $attachments,
2475 "entities" => $entities
2481 * @param string $body
2485 function api_get_attachments(&$body)
2488 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2490 $URLSearchString = "^\[\]";
2491 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2499 foreach ($images[1] as $image) {
2500 $imagedata = Image::getInfoFromURL($image);
2503 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2507 if (strstr(defaults($_SERVER, 'HTTP_USER_AGENT', ''), "AndStatus")) {
2508 foreach ($images[0] as $orig) {
2509 $body = str_replace($orig, "", $body);
2513 return $attachments;
2518 * @param string $text
2519 * @param string $bbcode
2522 * @todo Links at the first character of the post
2524 function api_get_entitities(&$text, $bbcode)
2526 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
2528 if ($include_entities != "true") {
2529 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2531 foreach ($images[1] as $image) {
2532 $replace = ProxyUtils::proxifyUrl($image);
2533 $text = str_replace($image, $replace, $text);
2538 $bbcode = BBCode::cleanPictureLinks($bbcode);
2540 // Change pure links in text to bbcode uris
2541 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2544 $entities["hashtags"] = [];
2545 $entities["symbols"] = [];
2546 $entities["urls"] = [];
2547 $entities["user_mentions"] = [];
2549 $URLSearchString = "^\[\]";
2551 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2553 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2554 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2555 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2557 $bbcode = preg_replace(
2558 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2559 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2562 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2564 $bbcode = preg_replace(
2565 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2566 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2569 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2571 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2573 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2574 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2577 foreach ($urls[1] as $id => $url) {
2578 //$start = strpos($text, $url, $offset);
2579 $start = iconv_strpos($text, $url, 0, "UTF-8");
2580 if (!($start === false)) {
2581 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2585 ksort($ordered_urls);
2588 //foreach ($urls[1] AS $id=>$url) {
2589 foreach ($ordered_urls as $url) {
2590 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2591 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2593 $display_url = $url["title"];
2595 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2596 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2598 if (strlen($display_url) > 26) {
2599 $display_url = substr($display_url, 0, 25)."…";
2603 //$start = strpos($text, $url, $offset);
2604 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2605 if (!($start === false)) {
2606 $entities["urls"][] = ["url" => $url["url"],
2607 "expanded_url" => $url["url"],
2608 "display_url" => $display_url,
2609 "indices" => [$start, $start+strlen($url["url"])]];
2610 $offset = $start + 1;
2614 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2615 $ordered_images = [];
2616 foreach ($images[1] as $image) {
2617 //$start = strpos($text, $url, $offset);
2618 $start = iconv_strpos($text, $image, 0, "UTF-8");
2619 if (!($start === false)) {
2620 $ordered_images[$start] = $image;
2623 //$entities["media"] = array();
2626 foreach ($ordered_images as $url) {
2627 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2628 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2630 if (strlen($display_url) > 26) {
2631 $display_url = substr($display_url, 0, 25)."…";
2634 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2635 if (!($start === false)) {
2636 $image = Image::getInfoFromURL($url);
2638 // If image cache is activated, then use the following sizes:
2639 // thumb (150), small (340), medium (600) and large (1024)
2640 if (!Config::get("system", "proxy_disabled")) {
2641 $media_url = ProxyUtils::proxifyUrl($url);
2644 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2645 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2647 if (($image[0] > 150) || ($image[1] > 150)) {
2648 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2649 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2652 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2653 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2655 if (($image[0] > 600) || ($image[1] > 600)) {
2656 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2657 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2661 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2664 $entities["media"][] = [
2666 "id_str" => (string)$start+1,
2667 "indices" => [$start, $start+strlen($url)],
2668 "media_url" => Strings::normaliseLink($media_url),
2669 "media_url_https" => $media_url,
2671 "display_url" => $display_url,
2672 "expanded_url" => $url,
2676 $offset = $start + 1;
2685 * @param array $item
2686 * @param string $text
2690 function api_format_items_embeded_images($item, $text)
2692 $text = preg_replace_callback(
2693 '|data:image/([^;]+)[^=]+=*|m',
2694 function () use ($item) {
2695 return System::baseUrl() . '/display/' . $item['guid'];
2703 * @brief return <a href='url'>name</a> as array
2705 * @param string $txt text
2710 function api_contactlink_to_array($txt)
2713 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2714 if ($r && count($match)==3) {
2716 'name' => $match[2],
2730 * @brief return likes, dislikes and attend status for item
2732 * @param array $item array
2733 * @param string $type Return type (atom, rss, xml, json)
2736 * likes => int count,
2737 * dislikes => int count
2739 function api_format_items_activities($item, $type = "json")
2748 'attendmaybe' => [],
2751 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2752 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2754 while ($parent_item = Item::fetch($ret)) {
2755 // not used as result should be structured like other user data
2756 //builtin_activity_puller($i, $activities);
2758 // get user data and add it to the array of the activity
2759 $user = api_get_user($a, $parent_item['author-id']);
2760 switch ($parent_item['verb']) {
2762 $activities['like'][] = $user;
2764 case ACTIVITY_DISLIKE:
2765 $activities['dislike'][] = $user;
2767 case ACTIVITY_ATTEND:
2768 $activities['attendyes'][] = $user;
2770 case ACTIVITY_ATTENDNO:
2771 $activities['attendno'][] = $user;
2773 case ACTIVITY_ATTENDMAYBE:
2774 $activities['attendmaybe'][] = $user;
2783 if ($type == "xml") {
2784 $xml_activities = [];
2785 foreach ($activities as $k => $v) {
2786 // change xml element from "like" to "friendica:like"
2787 $xml_activities["friendica:".$k] = $v;
2788 // add user data into xml output
2790 foreach ($v as $user) {
2791 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2794 $activities = $xml_activities;
2802 * @brief return data from profiles
2804 * @param array $profile_row array containing data from db table 'profile'
2807 function api_format_items_profiles($profile_row)
2810 'profile_id' => $profile_row['id'],
2811 'profile_name' => $profile_row['profile-name'],
2812 'is_default' => $profile_row['is-default'] ? true : false,
2813 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2814 'profile_photo' => $profile_row['photo'],
2815 'profile_thumb' => $profile_row['thumb'],
2816 'publish' => $profile_row['publish'] ? true : false,
2817 'net_publish' => $profile_row['net-publish'] ? true : false,
2818 'description' => $profile_row['pdesc'],
2819 'date_of_birth' => $profile_row['dob'],
2820 'address' => $profile_row['address'],
2821 'city' => $profile_row['locality'],
2822 'region' => $profile_row['region'],
2823 'postal_code' => $profile_row['postal-code'],
2824 'country' => $profile_row['country-name'],
2825 'hometown' => $profile_row['hometown'],
2826 'gender' => $profile_row['gender'],
2827 'marital' => $profile_row['marital'],
2828 'marital_with' => $profile_row['with'],
2829 'marital_since' => $profile_row['howlong'],
2830 'sexual' => $profile_row['sexual'],
2831 'politic' => $profile_row['politic'],
2832 'religion' => $profile_row['religion'],
2833 'public_keywords' => $profile_row['pub_keywords'],
2834 'private_keywords' => $profile_row['prv_keywords'],
2835 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2836 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2837 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2838 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2839 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2840 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2841 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2842 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2843 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2844 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2845 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2846 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2847 'homepage' => $profile_row['homepage'],
2854 * @brief format items to be returned by api
2856 * @param array $r array of items
2857 * @param array $user_info
2858 * @param bool $filter_user filter items by $user_info
2859 * @param string $type Return type (atom, rss, xml, json)
2861 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2867 foreach ($r as $item) {
2868 localize_item($item);
2869 list($status_user, $owner_user) = api_item_get_user($a, $item);
2871 // Look if the posts are matching if they should be filtered by user id
2872 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2876 $in_reply_to = api_in_reply_to($item);
2878 $converted = api_convert_item($item);
2880 if ($type == "xml") {
2881 $geo = "georss:point";
2887 'text' => $converted["text"],
2888 'truncated' => false,
2889 'created_at'=> api_date($item['created']),
2890 'in_reply_to_status_id' => $in_reply_to['status_id'],
2891 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2892 'source' => (($item['app']) ? $item['app'] : 'web'),
2893 'id' => intval($item['id']),
2894 'id_str' => (string) intval($item['id']),
2895 'in_reply_to_user_id' => $in_reply_to['user_id'],
2896 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2897 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2899 'favorited' => $item['starred'] ? true : false,
2900 'user' => $status_user,
2901 'friendica_owner' => $owner_user,
2902 'friendica_private' => $item['private'] == 1,
2903 //'entities' => NULL,
2904 'statusnet_html' => $converted["html"],
2905 'statusnet_conversation_id' => $item['parent'],
2906 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2907 'friendica_activities' => api_format_items_activities($item, $type),
2910 if (count($converted["attachments"]) > 0) {
2911 $status["attachments"] = $converted["attachments"];
2914 if (count($converted["entities"]) > 0) {
2915 $status["entities"] = $converted["entities"];
2918 if ($status["source"] == 'web') {
2919 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
2920 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
2921 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
2924 if ($item["id"] == $item["parent"]) {
2925 $retweeted_item = api_share_as_retweet($item);
2926 if ($retweeted_item !== false) {
2927 $retweeted_status = $status;
2928 $status['user'] = $status['friendica_owner'];
2930 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
2931 } catch (BadRequestException $e) {
2932 // user not found. should be found?
2933 /// @todo check if the user should be always found
2934 $retweeted_status["user"] = [];
2937 $rt_converted = api_convert_item($retweeted_item);
2939 $retweeted_status['text'] = $rt_converted["text"];
2940 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2941 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2942 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2943 $status['retweeted_status'] = $retweeted_status;
2947 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2948 unset($status["user"]["uid"]);
2949 unset($status["user"]["self"]);
2951 if ($item["coord"] != "") {
2952 $coords = explode(' ', $item["coord"]);
2953 if (count($coords) == 2) {
2954 if ($type == "json") {
2955 $status["geo"] = ['type' => 'Point',
2956 'coordinates' => [(float) $coords[0],
2957 (float) $coords[1]]];
2958 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2959 $status["georss:point"] = $item["coord"];
2969 * Returns the remaining number of API requests available to the user before the API limit is reached.
2971 * @param string $type Return type (atom, rss, xml, json)
2973 * @return array|string
2975 function api_account_rate_limit_status($type)
2977 if ($type == "xml") {
2979 'remaining-hits' => '150',
2980 '@attributes' => ["type" => "integer"],
2981 'hourly-limit' => '150',
2982 '@attributes2' => ["type" => "integer"],
2983 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
2984 '@attributes3' => ["type" => "datetime"],
2985 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2986 '@attributes4' => ["type" => "integer"],
2990 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2991 'remaining_hits' => '150',
2992 'hourly_limit' => '150',
2993 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
2997 return api_format_data('hash', $type, ['hash' => $hash]);
3000 /// @TODO move to top of file or somewhere better
3001 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3004 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3006 * @param string $type Return type (atom, rss, xml, json)
3008 * @return array|string
3010 function api_help_test($type)
3012 if ($type == 'xml') {
3018 return api_format_data('ok', $type, ["ok" => $ok]);
3021 /// @TODO move to top of file or somewhere better
3022 api_register_func('api/help/test', 'api_help_test', false);
3025 * Returns all lists the user subscribes to.
3027 * @param string $type Return type (atom, rss, xml, json)
3029 * @return array|string
3030 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3032 function api_lists_list($type)
3035 /// @TODO $ret is not filled here?
3036 return api_format_data('lists', $type, ["lists_list" => $ret]);
3039 /// @TODO move to top of file or somewhere better
3040 api_register_func('api/lists/list', 'api_lists_list', true);
3041 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3044 * Returns all groups the user owns.
3046 * @param string $type Return type (atom, rss, xml, json)
3048 * @return array|string
3049 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3051 function api_lists_ownerships($type)
3055 if (api_user() === false) {
3056 throw new ForbiddenException();
3060 $user_info = api_get_user($a);
3061 $uid = $user_info['uid'];
3063 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3065 // loop through all groups
3067 foreach ($groups as $group) {
3068 if ($group['visible']) {
3074 'name' => $group['name'],
3075 'id' => intval($group['id']),
3076 'id_str' => (string) $group['id'],
3077 'user' => $user_info,
3081 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3084 /// @TODO move to top of file or somewhere better
3085 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3088 * Returns recent statuses from users in the specified group.
3090 * @param string $type Return type (atom, rss, xml, json)
3092 * @return array|string
3093 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3095 function api_lists_statuses($type)
3099 $user_info = api_get_user($a);
3100 if (api_user() === false || $user_info === false) {
3101 throw new ForbiddenException();
3104 unset($_REQUEST["user_id"]);
3105 unset($_GET["user_id"]);
3107 unset($_REQUEST["screen_name"]);
3108 unset($_GET["screen_name"]);
3110 if (empty($_REQUEST['list_id'])) {
3111 throw new BadRequestException('list_id not specified');
3115 $count = defaults($_REQUEST, 'count', 20);
3116 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
3120 $since_id = defaults($_REQUEST, 'since_id', 0);
3121 $max_id = defaults($_REQUEST, 'max_id', 0);
3122 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3123 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
3125 $start = $page * $count;
3127 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3128 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3131 $condition[0] .= " AND `item`.`id` <= ?";
3132 $condition[] = $max_id;
3134 if ($exclude_replies > 0) {
3135 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3137 if ($conversation_id > 0) {
3138 $condition[0] .= " AND `item`.`parent` = ?";
3139 $condition[] = $conversation_id;
3142 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3143 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3145 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3147 $data = ['status' => $items];
3152 $data = api_rss_extra($a, $data, $user_info);
3156 return api_format_data("statuses", $type, $data);
3159 /// @TODO move to top of file or somewhere better
3160 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3163 * Considers friends and followers lists to be private and won't return
3164 * anything if any user_id parameter is passed.
3166 * @brief Returns either the friends of the follower list
3168 * @param string $qtype Either "friends" or "followers"
3169 * @return boolean|array
3170 * @throws ForbiddenException
3172 function api_statuses_f($qtype)
3176 if (api_user() === false) {
3177 throw new ForbiddenException();
3181 $count = defaults($_GET, 'count', 20);
3182 $page = defaults($_GET, 'page', 1);
3186 $start = ($page - 1) * $count;
3188 $user_info = api_get_user($a);
3190 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3191 /* this is to stop Hotot to load friends multiple times
3192 * I'm not sure if I'm missing return something or
3193 * is a bug in hotot. Workaround, meantime
3197 return array('$users' => $ret);*/
3202 if ($qtype == 'friends') {
3203 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3204 } elseif ($qtype == 'followers') {
3205 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3208 // friends and followers only for self
3209 if ($user_info['self'] == 0) {
3210 $sql_extra = " AND false ";
3213 if ($qtype == 'blocks') {
3214 $sql_filter = 'AND `blocked` AND NOT `pending`';
3215 } elseif ($qtype == 'incoming') {
3216 $sql_filter = 'AND `pending`';
3218 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3236 foreach ($r as $cid) {
3237 $user = api_get_user($a, $cid['nurl']);
3238 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3239 unset($user["uid"]);
3240 unset($user["self"]);
3247 return ['user' => $ret];
3252 * Returns the user's friends.
3254 * @brief Returns the list of friends of the provided user
3256 * @deprecated By Twitter API in favor of friends/list
3258 * @param string $type Either "json" or "xml"
3259 * @return boolean|string|array
3261 function api_statuses_friends($type)
3263 $data = api_statuses_f("friends");
3264 if ($data === false) {
3267 return api_format_data("users", $type, $data);
3271 * Returns the user's followers.
3273 * @brief Returns the list of followers of the provided user
3275 * @deprecated By Twitter API in favor of friends/list
3277 * @param string $type Either "json" or "xml"
3278 * @return boolean|string|array
3280 function api_statuses_followers($type)
3282 $data = api_statuses_f("followers");
3283 if ($data === false) {
3286 return api_format_data("users", $type, $data);
3289 /// @TODO move to top of file or somewhere better
3290 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3291 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3294 * Returns the list of blocked users
3296 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3298 * @param string $type Either "json" or "xml"
3300 * @return boolean|string|array
3302 function api_blocks_list($type)
3304 $data = api_statuses_f('blocks');
3305 if ($data === false) {
3308 return api_format_data("users", $type, $data);
3311 /// @TODO move to top of file or somewhere better
3312 api_register_func('api/blocks/list', 'api_blocks_list', true);
3315 * Returns the list of pending users IDs
3317 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3319 * @param string $type Either "json" or "xml"
3321 * @return boolean|string|array
3323 function api_friendships_incoming($type)
3325 $data = api_statuses_f('incoming');
3326 if ($data === false) {
3331 foreach ($data['user'] as $user) {
3332 $ids[] = $user['id'];
3335 return api_format_data("ids", $type, ['id' => $ids]);
3338 /// @TODO move to top of file or somewhere better
3339 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3342 * Returns the instance's configuration information.
3344 * @param string $type Return type (atom, rss, xml, json)
3346 * @return array|string
3348 function api_statusnet_config($type)
3352 $name = Config::get('config', 'sitename');
3353 $server = $a->getHostName();
3354 $logo = System::baseUrl() . '/images/friendica-64.png';
3355 $email = Config::get('config', 'admin_email');
3356 $closed = intval(Config::get('config', 'register_policy')) === REGISTER_CLOSED ? 'true' : 'false';
3357 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3358 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3359 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3360 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3363 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3364 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3365 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3366 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3367 'shorturllength' => '30',
3369 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3370 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3371 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3372 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3377 return api_format_data('config', $type, ['config' => $config]);
3380 /// @TODO move to top of file or somewhere better
3381 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3382 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3386 * @param string $type Return type (atom, rss, xml, json)
3388 * @return array|string
3390 function api_statusnet_version($type)
3393 $fake_statusnet_version = "0.9.7";
3395 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3398 /// @TODO move to top of file or somewhere better
3399 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3400 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3404 * @param string $type Return type (atom, rss, xml, json)
3406 * @todo use api_format_data() to return data
3408 function api_ff_ids($type)
3411 throw new ForbiddenException();
3418 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3421 "SELECT `pcontact`.`id` FROM `contact`
3422 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3423 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3426 if (!DBA::isResult($r)) {
3431 foreach ($r as $rr) {
3432 if ($stringify_ids) {
3435 $ids[] = intval($rr['id']);
3439 return api_format_data("ids", $type, ['id' => $ids]);
3443 * Returns the ID of every user the user is following.
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-friends-ids
3450 function api_friends_ids($type)
3452 return api_ff_ids($type);
3456 * Returns the ID of every user following the user.
3458 * @param string $type Return type (atom, rss, xml, json)
3460 * @return array|string
3461 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3463 function api_followers_ids($type)
3465 return api_ff_ids($type);
3468 /// @TODO move to top of file or somewhere better
3469 api_register_func('api/friends/ids', 'api_friends_ids', true);
3470 api_register_func('api/followers/ids', 'api_followers_ids', true);
3473 * Sends a new direct message.
3475 * @param string $type Return type (atom, rss, xml, json)
3477 * @return array|string
3478 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3480 function api_direct_messages_new($type)
3484 if (api_user() === false) {
3485 throw new ForbiddenException();
3488 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3492 $sender = api_get_user($a);
3495 if (!empty($_POST['screen_name'])) {
3497 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3499 DBA::escape($_POST['screen_name'])
3502 if (DBA::isResult($r)) {
3503 // Selecting the id by priority, friendica first
3504 api_best_nickname($r);
3506 $recipient = api_get_user($a, $r[0]['nurl']);
3509 $recipient = api_get_user($a, $_POST['user_id']);
3512 if (empty($recipient)) {
3513 throw new NotFoundException('Recipient not found');
3518 if (!empty($_REQUEST['replyto'])) {
3520 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3522 intval($_REQUEST['replyto'])
3524 $replyto = $r[0]['parent-uri'];
3525 $sub = $r[0]['title'];
3527 if (!empty($_REQUEST['title'])) {
3528 $sub = $_REQUEST['title'];
3530 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3534 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3537 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3538 $ret = api_format_messages($r[0], $recipient, $sender);
3540 $ret = ["error"=>$id];
3543 $data = ['direct_message'=>$ret];
3549 $data = api_rss_extra($a, $data, $sender);
3553 return api_format_data("direct-messages", $type, $data);
3556 /// @TODO move to top of file or somewhere better
3557 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3560 * Destroys a direct message.
3562 * @brief delete a direct_message from mail table through api
3564 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3565 * @return string|array
3566 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3568 function api_direct_messages_destroy($type)
3572 if (api_user() === false) {
3573 throw new ForbiddenException();
3577 $user_info = api_get_user($a);
3579 $id = defaults($_REQUEST, 'id', 0);
3581 $parenturi = defaults($_REQUEST, 'friendica_parenturi', "");
3582 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3583 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3585 $uid = $user_info['uid'];
3586 // error if no id or parenturi specified (for clients posting parent-uri as well)
3587 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3588 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3589 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3592 // BadRequestException if no id specified (for clients using Twitter API)
3594 throw new BadRequestException('Message id not specified');
3597 // add parent-uri to sql command if specified by calling app
3598 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3600 // get data of the specified message id
3602 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3607 // error message if specified id is not in database
3608 if (!DBA::isResult($r)) {
3609 if ($verbose == "true") {
3610 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3611 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3613 /// @todo BadRequestException ok for Twitter API clients?
3614 throw new BadRequestException('message id not in database');
3619 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3624 if ($verbose == "true") {
3627 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3628 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3630 $answer = ['result' => 'error', 'message' => 'unknown error'];
3631 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3634 /// @todo return JSON data like Twitter API not yet implemented
3637 /// @TODO move to top of file or somewhere better
3638 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3643 * @brief unfollow contact
3645 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3646 * @return string|array
3647 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3649 function api_friendships_destroy($type)
3653 if ($uid === false) {
3654 throw new ForbiddenException();
3657 $contact_id = defaults($_REQUEST, 'user_id');
3659 if (empty($contact_id)) {
3660 Logger::log("No user_id specified", Logger::DEBUG);
3661 throw new BadRequestException("no user_id specified");
3664 // Get Contact by given id
3665 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3667 if(!DBA::isResult($contact)) {
3668 Logger::log("No contact found for ID" . $contact_id, Logger::DEBUG);
3669 throw new NotFoundException("no contact found to given ID");
3672 $url = $contact["url"];
3674 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3675 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3676 Strings::normaliseLink($url), $url];
3677 $contact = DBA::selectFirst('contact', [], $condition);
3679 if (!DBA::isResult($contact)) {
3680 Logger::log("Not following Contact", Logger::DEBUG);
3681 throw new NotFoundException("Not following Contact");
3684 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3685 Logger::log("Not supported", Logger::DEBUG);
3686 throw new ExpectationFailedException("Not supported");
3689 $dissolve = ($contact['rel'] == Contact::SHARING);
3691 $owner = User::getOwnerDataById($uid);
3693 Contact::terminateFriendship($owner, $contact, $dissolve);
3696 Logger::log("No owner found", Logger::DEBUG);
3697 throw new NotFoundException("Error Processing Request");
3700 // Sharing-only contacts get deleted as there no relationship any more
3702 Contact::remove($contact['id']);
3704 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3707 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3708 unset($contact["uid"]);
3709 unset($contact["self"]);
3711 // Set screen_name since Twidere requests it
3712 $contact["screen_name"] = $contact["nick"];
3714 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3716 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3720 * @param string $type Return type (atom, rss, xml, json)
3721 * @param string $box
3722 * @param string $verbose
3724 * @return array|string
3726 function api_direct_messages_box($type, $box, $verbose)
3729 if (api_user() === false) {
3730 throw new ForbiddenException();
3733 $count = defaults($_GET, 'count', 20);
3734 $page = defaults($_REQUEST, 'page', 1) - 1;
3739 $since_id = defaults($_REQUEST, 'since_id', 0);
3740 $max_id = defaults($_REQUEST, 'max_id', 0);
3742 $user_id = defaults($_REQUEST, 'user_id', '');
3743 $screen_name = defaults($_REQUEST, 'screen_name', '');
3746 unset($_REQUEST["user_id"]);
3747 unset($_GET["user_id"]);
3749 unset($_REQUEST["screen_name"]);
3750 unset($_GET["screen_name"]);
3752 $user_info = api_get_user($a);
3753 if ($user_info === false) {
3754 throw new ForbiddenException();
3756 $profile_url = $user_info["url"];
3759 $start = $page * $count;
3764 if ($box=="sentbox") {
3765 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3766 } elseif ($box == "conversation") {
3767 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape(defaults($_GET, 'uri', '')) . "'";
3768 } elseif ($box == "all") {
3769 $sql_extra = "true";
3770 } elseif ($box == "inbox") {
3771 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3775 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3778 if ($user_id != "") {
3779 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3780 } elseif ($screen_name !="") {
3781 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3785 "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",
3791 if ($verbose == "true" && !DBA::isResult($r)) {
3792 $answer = ['result' => 'error', 'message' => 'no mails available'];
3793 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3797 foreach ($r as $item) {
3798 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3799 $recipient = $user_info;
3800 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3801 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3802 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3803 $sender = $user_info;
3806 if (isset($recipient) && isset($sender)) {
3807 $ret[] = api_format_messages($item, $recipient, $sender);
3812 $data = ['direct_message' => $ret];
3817 $data = api_rss_extra($a, $data, $user_info);
3821 return api_format_data("direct-messages", $type, $data);
3825 * Returns the most recent direct messages sent by the user.
3827 * @param string $type Return type (atom, rss, xml, json)
3829 * @return array|string
3830 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3832 function api_direct_messages_sentbox($type)
3834 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3835 return api_direct_messages_box($type, "sentbox", $verbose);
3839 * Returns the most recent direct messages sent to the user.
3841 * @param string $type Return type (atom, rss, xml, json)
3843 * @return array|string
3844 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3846 function api_direct_messages_inbox($type)
3848 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3849 return api_direct_messages_box($type, "inbox", $verbose);
3854 * @param string $type Return type (atom, rss, xml, json)
3856 * @return array|string
3858 function api_direct_messages_all($type)
3860 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3861 return api_direct_messages_box($type, "all", $verbose);
3866 * @param string $type Return type (atom, rss, xml, json)
3868 * @return array|string
3870 function api_direct_messages_conversation($type)
3872 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3873 return api_direct_messages_box($type, "conversation", $verbose);
3876 /// @TODO move to top of file or somewhere better
3877 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3878 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3879 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3880 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3883 * Returns an OAuth Request Token.
3885 * @see https://oauth.net/core/1.0/#auth_step1
3887 function api_oauth_request_token()
3889 $oauth1 = new FKOAuth1();
3891 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3892 } catch (Exception $e) {
3893 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3901 * Returns an OAuth Access Token.
3903 * @return array|string
3904 * @see https://oauth.net/core/1.0/#auth_step3
3906 function api_oauth_access_token()
3908 $oauth1 = new FKOAuth1();
3910 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3911 } catch (Exception $e) {
3912 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3919 /// @TODO move to top of file or somewhere better
3920 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3921 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3925 * @brief delete a complete photoalbum with all containing photos from database through api
3927 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3928 * @return string|array
3930 function api_fr_photoalbum_delete($type)
3932 if (api_user() === false) {
3933 throw new ForbiddenException();
3936 $album = defaults($_REQUEST, 'album', "");
3938 // we do not allow calls without album string
3940 throw new BadRequestException("no albumname specified");
3942 // check if album is existing
3944 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3948 if (!DBA::isResult($r)) {
3949 throw new BadRequestException("album not available");
3952 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3953 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3954 foreach ($r as $rr) {
3955 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
3956 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
3958 if (!DBA::isResult($photo_item)) {
3959 throw new InternalServerErrorException("problem with deleting items occured");
3961 Item::deleteForUser(['id' => $photo_item['id']], api_user());
3964 // now let's delete all photos from the album
3965 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
3967 // return success of deletion or error message
3969 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
3970 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
3972 throw new InternalServerErrorException("unknown error - deleting from database failed");
3977 * @brief update the name of the album for all photos of an album
3979 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3980 * @return string|array
3982 function api_fr_photoalbum_update($type)
3984 if (api_user() === false) {
3985 throw new ForbiddenException();
3988 $album = defaults($_REQUEST, 'album', "");
3989 $album_new = defaults($_REQUEST, 'album_new', "");
3991 // we do not allow calls without album string
3993 throw new BadRequestException("no albumname specified");
3995 if ($album_new == "") {
3996 throw new BadRequestException("no new albumname specified");
3998 // check if album is existing
3999 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4000 throw new BadRequestException("album not available");
4002 // now let's update all photos to the albumname
4003 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4005 // return success of updating or error message
4007 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4008 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4010 throw new InternalServerErrorException("unknown error - updating in database failed");
4016 * @brief list all photos of the authenticated user
4018 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4019 * @return string|array
4021 function api_fr_photos_list($type)
4023 if (api_user() === false) {
4024 throw new ForbiddenException();
4027 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4028 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4029 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4030 intval(local_user())
4033 'image/jpeg' => 'jpg',
4034 'image/png' => 'png',
4035 'image/gif' => 'gif'
4037 $data = ['photo'=>[]];
4038 if (DBA::isResult($r)) {
4039 foreach ($r as $rr) {
4041 $photo['id'] = $rr['resource-id'];
4042 $photo['album'] = $rr['album'];
4043 $photo['filename'] = $rr['filename'];
4044 $photo['type'] = $rr['type'];
4045 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4046 $photo['created'] = $rr['created'];
4047 $photo['edited'] = $rr['edited'];
4048 $photo['desc'] = $rr['desc'];
4050 if ($type == "xml") {
4051 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4053 $photo['thumb'] = $thumb;
4054 $data['photo'][] = $photo;
4058 return api_format_data("photos", $type, $data);
4062 * @brief upload a new photo or change an existing photo
4064 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4065 * @return string|array
4067 function api_fr_photo_create_update($type)
4069 if (api_user() === false) {
4070 throw new ForbiddenException();
4073 $photo_id = defaults($_REQUEST, 'photo_id', null);
4074 $desc = defaults($_REQUEST, 'desc', (array_key_exists('desc', $_REQUEST) ? "" : null)) ; // extra check necessary to distinguish between 'not provided' and 'empty string'
4075 $album = defaults($_REQUEST, 'album', null);
4076 $album_new = defaults($_REQUEST, 'album_new', null);
4077 $allow_cid = defaults($_REQUEST, 'allow_cid', (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4078 $deny_cid = defaults($_REQUEST, 'deny_cid' , (array_key_exists('deny_cid' , $_REQUEST) ? " " : null));
4079 $allow_gid = defaults($_REQUEST, 'allow_gid', (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4080 $deny_gid = defaults($_REQUEST, 'deny_gid' , (array_key_exists('deny_gid' , $_REQUEST) ? " " : null));
4081 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4083 // do several checks on input parameters
4084 // we do not allow calls without album string
4085 if ($album == null) {
4086 throw new BadRequestException("no albumname specified");
4088 // if photo_id == null --> we are uploading a new photo
4089 if ($photo_id == null) {
4092 // error if no media posted in create-mode
4093 if (empty($_FILES['media'])) {
4095 throw new BadRequestException("no media data submitted");
4098 // album_new will be ignored in create-mode
4103 // check if photo is existing in databasei
4104 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4105 throw new BadRequestException("photo not available");
4109 // checks on acl strings provided by clients
4110 $acl_input_error = false;
4111 $acl_input_error |= check_acl_input($allow_cid);
4112 $acl_input_error |= check_acl_input($deny_cid);
4113 $acl_input_error |= check_acl_input($allow_gid);
4114 $acl_input_error |= check_acl_input($deny_gid);
4115 if ($acl_input_error) {
4116 throw new BadRequestException("acl data invalid");
4118 // now let's upload the new media in create-mode
4119 if ($mode == "create") {
4120 $media = $_FILES['media'];
4121 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4123 // return success of updating or error message
4124 if (!is_null($data)) {
4125 return api_format_data("photo_create", $type, $data);
4127 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4131 // now let's do the changes in update-mode
4132 if ($mode == "update") {
4133 $updated_fields = [];
4135 if (!is_null($desc)) {
4136 $updated_fields['desc'] = $desc;
4139 if (!is_null($album_new)) {
4140 $updated_fields['album'] = $album_new;
4143 if (!is_null($allow_cid)) {
4144 $allow_cid = trim($allow_cid);
4145 $updated_fields['allow_cid'] = $allow_cid;
4148 if (!is_null($deny_cid)) {
4149 $deny_cid = trim($deny_cid);
4150 $updated_fields['deny_cid'] = $deny_cid;
4153 if (!is_null($allow_gid)) {
4154 $allow_gid = trim($allow_gid);
4155 $updated_fields['allow_gid'] = $allow_gid;
4158 if (!is_null($deny_gid)) {
4159 $deny_gid = trim($deny_gid);
4160 $updated_fields['deny_gid'] = $deny_gid;
4164 if (count($updated_fields) > 0) {
4165 $nothingtodo = false;
4166 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4168 $nothingtodo = true;
4171 if (!empty($_FILES['media'])) {
4172 $nothingtodo = false;
4173 $media = $_FILES['media'];
4174 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4175 if (!is_null($data)) {
4176 return api_format_data("photo_update", $type, $data);
4180 // return success of updating or error message
4182 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4183 return api_format_data("photo_update", $type, ['$result' => $answer]);
4186 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4187 return api_format_data("photo_update", $type, ['$result' => $answer]);
4189 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4192 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4196 * @brief delete a single photo from the database through api
4198 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4199 * @return string|array
4201 function api_fr_photo_delete($type)
4203 if (api_user() === false) {
4204 throw new ForbiddenException();
4207 $photo_id = defaults($_REQUEST, 'photo_id', null);
4209 // do several checks on input parameters
4210 // we do not allow calls without photo id
4211 if ($photo_id == null) {
4212 throw new BadRequestException("no photo_id specified");
4214 // check if photo is existing in database
4215 $r = Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()]);
4217 throw new BadRequestException("photo not available");
4219 // now we can perform on the deletion of the photo
4220 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4222 // return success of deletion or error message
4224 // retrieve the id of the parent element (the photo element)
4225 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4226 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4228 if (!DBA::isResult($photo_item)) {
4229 throw new InternalServerErrorException("problem with deleting items occured");
4231 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4232 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4233 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4235 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4236 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4238 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4244 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4246 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4247 * @return string|array
4249 function api_fr_photo_detail($type)
4251 if (api_user() === false) {
4252 throw new ForbiddenException();
4254 if (empty($_REQUEST['photo_id'])) {
4255 throw new BadRequestException("No photo id.");
4258 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4259 $photo_id = $_REQUEST['photo_id'];
4261 // prepare json/xml output with data from database for the requested photo
4262 $data = prepare_photo_data($type, $scale, $photo_id);
4264 return api_format_data("photo_detail", $type, $data);
4269 * Updates the user’s profile image.
4271 * @brief updates the profile image for the user (either a specified profile or the default profile)
4273 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4275 * @return string|array
4276 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4278 function api_account_update_profile_image($type)
4280 if (api_user() === false) {
4281 throw new ForbiddenException();
4284 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4286 // error if image data is missing
4287 if (empty($_FILES['image'])) {
4288 throw new BadRequestException("no media data submitted");
4291 // check if specified profile id is valid
4292 if ($profile_id != 0) {
4293 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4294 // error message if specified profile id is not in database
4295 if (!DBA::isResult($profile)) {
4296 throw new BadRequestException("profile_id not available");
4298 $is_default_profile = $profile['is-default'];
4300 $is_default_profile = 1;
4303 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4305 if (!empty($_FILES['image'])) {
4306 $media = $_FILES['image'];
4307 } elseif (!empty($_FILES['media'])) {
4308 $media = $_FILES['media'];
4310 // save new profile image
4311 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4314 if (is_array($media['type'])) {
4315 $filetype = $media['type'][0];
4317 $filetype = $media['type'];
4319 if ($filetype == "image/jpeg") {
4321 } elseif ($filetype == "image/png") {
4324 throw new InternalServerErrorException('Unsupported filetype');
4327 // change specified profile or all profiles to the new resource-id
4328 if ($is_default_profile) {
4329 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4330 Photo::update(['profile' => false], $condition);
4332 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype,
4333 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype];
4334 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4337 Contact::updateSelfFromUserID(api_user(), true);
4339 // Update global directory in background
4340 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4341 if ($url && strlen(Config::get('system', 'directory'))) {
4342 Worker::add(PRIORITY_LOW, "Directory", $url);
4345 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4347 // output for client
4349 return api_account_verify_credentials($type);
4351 // SaveMediaToDatabase failed for some reason
4352 throw new InternalServerErrorException("image upload failed");
4356 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4357 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4358 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4359 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4360 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4361 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4362 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4363 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4364 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4367 * Update user profile
4369 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4371 * @return array|string
4373 function api_account_update_profile($type)
4375 $local_user = api_user();
4376 $api_user = api_get_user(get_app());
4378 if (!empty($_POST['name'])) {
4379 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4380 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4381 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4382 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4385 if (isset($_POST['description'])) {
4386 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4387 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4388 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4391 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4392 // Update global directory in background
4393 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4394 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4397 return api_account_verify_credentials($type);
4400 /// @TODO move to top of file or somewhere better
4401 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4405 * @param string $acl_string
4407 function check_acl_input($acl_string)
4409 if ($acl_string == null || $acl_string == " ") {
4412 $contact_not_found = false;
4414 // split <x><y><z> into array of cid's
4415 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4417 // check for each cid if it is available on server
4418 $cid_array = $array[0];
4419 foreach ($cid_array as $cid) {
4420 $cid = str_replace("<", "", $cid);
4421 $cid = str_replace(">", "", $cid);
4422 $condition = ['id' => $cid, 'uid' => api_user()];
4423 $contact_not_found |= !DBA::exists('contact', $condition);
4425 return $contact_not_found;
4430 * @param string $mediatype
4431 * @param array $media
4432 * @param string $type
4433 * @param string $album
4434 * @param string $allow_cid
4435 * @param string $deny_cid
4436 * @param string $allow_gid
4437 * @param string $deny_gid
4438 * @param string $desc
4439 * @param integer $profile
4440 * @param boolean $visibility
4441 * @param string $photo_id
4443 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)
4451 if (is_array($media)) {
4452 if (is_array($media['tmp_name'])) {
4453 $src = $media['tmp_name'][0];
4455 $src = $media['tmp_name'];
4457 if (is_array($media['name'])) {
4458 $filename = basename($media['name'][0]);
4460 $filename = basename($media['name']);
4462 if (is_array($media['size'])) {
4463 $filesize = intval($media['size'][0]);
4465 $filesize = intval($media['size']);
4467 if (is_array($media['type'])) {
4468 $filetype = $media['type'][0];
4470 $filetype = $media['type'];
4474 if ($filetype == "") {
4475 $filetype=Image::guessType($filename);
4477 $imagedata = @getimagesize($src);
4479 $filetype = $imagedata['mime'];
4482 "File upload src: " . $src . " - filename: " . $filename .
4483 " - size: " . $filesize . " - type: " . $filetype,
4487 // check if there was a php upload error
4488 if ($filesize == 0 && $media['error'] == 1) {
4489 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4491 // check against max upload size within Friendica instance
4492 $maximagesize = Config::get('system', 'maximagesize');
4493 if ($maximagesize && ($filesize > $maximagesize)) {
4494 $formattedBytes = Strings::formatBytes($maximagesize);
4495 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4498 // create Photo instance with the data of the image
4499 $imagedata = @file_get_contents($src);
4500 $Image = new Image($imagedata, $filetype);
4501 if (!$Image->isValid()) {
4502 throw new InternalServerErrorException("unable to process image data");
4505 // check orientation of image
4506 $Image->orient($src);
4509 // check max length of images on server
4510 $max_length = Config::get('system', 'max_image_length');
4512 $max_length = MAX_IMAGE_LENGTH;
4514 if ($max_length > 0) {
4515 $Image->scaleDown($max_length);
4516 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4518 $width = $Image->getWidth();
4519 $height = $Image->getHeight();
4521 // create a new resource-id if not already provided
4522 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4524 if ($mediatype == "photo") {
4525 // upload normal image (scales 0, 1, 2)
4526 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4528 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4530 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4532 if ($width > 640 || $height > 640) {
4533 $Image->scaleDown(640);
4534 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4536 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4540 if ($width > 320 || $height > 320) {
4541 $Image->scaleDown(320);
4542 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4544 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4547 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4548 } elseif ($mediatype == "profileimage") {
4549 // upload profile image (scales 4, 5, 6)
4550 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4552 if ($width > 300 || $height > 300) {
4553 $Image->scaleDown(300);
4554 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4556 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4560 if ($width > 80 || $height > 80) {
4561 $Image->scaleDown(80);
4562 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4564 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4568 if ($width > 48 || $height > 48) {
4569 $Image->scaleDown(48);
4570 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4572 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4575 $Image->__destruct();
4576 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4579 if (isset($r) && $r) {
4580 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4581 if ($photo_id == null && $mediatype == "photo") {
4582 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4584 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4585 return prepare_photo_data($type, false, $hash);
4587 throw new InternalServerErrorException("image upload failed");
4593 * @param string $hash
4594 * @param string $allow_cid
4595 * @param string $deny_cid
4596 * @param string $allow_gid
4597 * @param string $deny_gid
4598 * @param string $filetype
4599 * @param boolean $visibility
4601 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4603 // get data about the api authenticated user
4604 $uri = Item::newURI(intval(api_user()));
4605 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4608 $arr['guid'] = System::createUUID();
4609 $arr['uid'] = intval(api_user());
4611 $arr['parent-uri'] = $uri;
4612 $arr['type'] = 'photo';
4614 $arr['resource-id'] = $hash;
4615 $arr['contact-id'] = $owner_record['id'];
4616 $arr['owner-name'] = $owner_record['name'];
4617 $arr['owner-link'] = $owner_record['url'];
4618 $arr['owner-avatar'] = $owner_record['thumb'];
4619 $arr['author-name'] = $owner_record['name'];
4620 $arr['author-link'] = $owner_record['url'];
4621 $arr['author-avatar'] = $owner_record['thumb'];
4623 $arr['allow_cid'] = $allow_cid;
4624 $arr['allow_gid'] = $allow_gid;
4625 $arr['deny_cid'] = $deny_cid;
4626 $arr['deny_gid'] = $deny_gid;
4627 $arr['visible'] = $visibility;
4631 'image/jpeg' => 'jpg',
4632 'image/png' => 'png',
4633 'image/gif' => 'gif'
4636 // adds link to the thumbnail scale photo
4637 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4638 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4641 // do the magic for storing the item in the database and trigger the federation to other contacts
4647 * @param string $type
4649 * @param string $photo_id
4653 function prepare_photo_data($type, $scale, $photo_id)
4656 $user_info = api_get_user($a);
4658 if ($user_info === false) {
4659 throw new ForbiddenException();
4662 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4663 $data_sql = ($scale === false ? "" : "data, ");
4665 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4666 // clients needs to convert this in their way for further processing
4668 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4669 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4670 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4671 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4673 intval(local_user()),
4674 DBA::escape($photo_id),
4679 'image/jpeg' => 'jpg',
4680 'image/png' => 'png',
4681 'image/gif' => 'gif'
4684 // prepare output data for photo
4685 if (DBA::isResult($r)) {
4686 $data = ['photo' => $r[0]];
4687 $data['photo']['id'] = $data['photo']['resource-id'];
4688 if ($scale !== false) {
4689 $data['photo']['data'] = base64_encode($data['photo']['data']);
4691 unset($data['photo']['datasize']); //needed only with scale param
4693 if ($type == "xml") {
4694 $data['photo']['links'] = [];
4695 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4696 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4698 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4701 $data['photo']['link'] = [];
4702 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4704 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4705 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4709 unset($data['photo']['resource-id']);
4710 unset($data['photo']['minscale']);
4711 unset($data['photo']['maxscale']);
4713 throw new NotFoundException();
4716 // retrieve item element for getting activities (like, dislike etc.) related to photo
4717 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4718 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4720 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4722 // retrieve comments on photo
4723 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4724 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4726 $statuses = Item::selectForUser(api_user(), [], $condition);
4728 // prepare output of comments
4729 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
4731 if ($type == "xml") {
4733 foreach ($commentData as $comment) {
4734 $comments[$k++ . ":comment"] = $comment;
4737 foreach ($commentData as $comment) {
4738 $comments[] = $comment;
4741 $data['photo']['friendica_comments'] = $comments;
4743 // include info if rights on photo and rights on item are mismatching
4744 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4745 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4746 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4747 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4748 $data['photo']['rights_mismatch'] = $rights_mismatch;
4755 * Similar as /mod/redir.php
4756 * redirect to 'url' after dfrn auth
4758 * Why this when there is mod/redir.php already?
4759 * This use api_user() and api_login()
4762 * c_url: url of remote contact to auth to
4763 * url: string, url to redirect after auth
4765 function api_friendica_remoteauth()
4767 $url = defaults($_GET, 'url', '');
4768 $c_url = defaults($_GET, 'c_url', '');
4770 if ($url === '' || $c_url === '') {
4771 throw new BadRequestException("Wrong parameters.");
4774 $c_url = Strings::normaliseLink($c_url);
4778 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4780 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
4781 throw new BadRequestException("Unknown contact");
4784 $cid = $contact['id'];
4786 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4788 if ($contact['duplex'] && $contact['issued-id']) {
4789 $orig_id = $contact['issued-id'];
4790 $dfrn_id = '1:' . $orig_id;
4792 if ($contact['duplex'] && $contact['dfrn-id']) {
4793 $orig_id = $contact['dfrn-id'];
4794 $dfrn_id = '0:' . $orig_id;
4797 $sec = Strings::getRandomHex();
4799 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4800 'sec' => $sec, 'expire' => time() + 45];
4801 DBA::insert('profile_check', $fields);
4803 Logger::log($contact['name'] . ' ' . $sec, Logger::DEBUG);
4804 $dest = ($url ? '&destination_url=' . $url : '');
4806 System::externalRedirect(
4807 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4808 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4809 . '&type=profile&sec=' . $sec . $dest
4812 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4815 * @brief Return the item shared, if the item contains only the [share] tag
4817 * @param array $item Sharer item
4818 * @return array|false Shared item or false if not a reshare
4820 function api_share_as_retweet(&$item)
4822 $body = trim($item["body"]);
4824 if (Diaspora::isReshare($body, false) === false) {
4825 if ($item['author-id'] == $item['owner-id']) {
4828 // Reshares from OStatus, ActivityPub and Twitter
4829 $reshared_item = $item;
4830 $reshared_item['owner-id'] = $reshared_item['author-id'];
4831 $reshared_item['owner-link'] = $reshared_item['author-link'];
4832 $reshared_item['owner-name'] = $reshared_item['author-name'];
4833 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
4834 return $reshared_item;
4838 /// @TODO "$1" should maybe mean '$1' ?
4839 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4841 * Skip if there is no shared message in there
4842 * we already checked this in diaspora::isReshare()
4843 * but better one more than one less...
4845 if (($body == $attributes) || empty($attributes)) {
4849 // build the fake reshared item
4850 $reshared_item = $item;
4853 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4854 if (!empty($matches[1])) {
4855 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4858 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4859 if (!empty($matches[1])) {
4860 $author = $matches[1];
4864 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4865 if (!empty($matches[1])) {
4866 $profile = $matches[1];
4869 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4870 if (!empty($matches[1])) {
4871 $profile = $matches[1];
4875 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4876 if (!empty($matches[1])) {
4877 $avatar = $matches[1];
4880 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4881 if (!empty($matches[1])) {
4882 $avatar = $matches[1];
4886 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4887 if (!empty($matches[1])) {
4888 $link = $matches[1];
4891 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4892 if (!empty($matches[1])) {
4893 $link = $matches[1];
4897 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4898 if (!empty($matches[1])) {
4899 $posted = $matches[1];
4902 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4903 if (!empty($matches[1])) {
4904 $posted = $matches[1];
4907 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4909 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4913 $reshared_item["body"] = $shared_body;
4914 $reshared_item["author-id"] = Contact::getIdForURL($profile, 0, true);
4915 $reshared_item["author-name"] = $author;
4916 $reshared_item["author-link"] = $profile;
4917 $reshared_item["author-avatar"] = $avatar;
4918 $reshared_item["plink"] = $link;
4919 $reshared_item["created"] = $posted;
4920 $reshared_item["edited"] = $posted;
4922 return $reshared_item;
4927 * @param string $profile
4929 * @return string|false
4930 * @todo remove trailing junk from profile url
4931 * @todo pump.io check has to check the website
4933 function api_get_nick($profile)
4938 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4939 DBA::escape(Strings::normaliseLink($profile))
4942 if (DBA::isResult($r)) {
4943 $nick = $r[0]["nick"];
4948 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4949 DBA::escape(Strings::normaliseLink($profile))
4952 if (DBA::isResult($r)) {
4953 $nick = $r[0]["nick"];
4958 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4959 if ($friendica != $profile) {
4965 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4966 if ($diaspora != $profile) {
4972 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4973 if ($twitter != $profile) {
4980 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4981 if ($StatusnetHost != $profile) {
4982 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4983 if ($StatusnetUser != $profile) {
4984 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4985 $user = json_decode($UserData);
4987 $nick = $user->screen_name;
4993 // To-Do: look at the page if its really a pumpio site
4994 //if (!$nick == "") {
4995 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4996 // if ($pumpio != $profile)
4998 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5011 * @param array $item
5015 function api_in_reply_to($item)
5019 $in_reply_to['status_id'] = null;
5020 $in_reply_to['user_id'] = null;
5021 $in_reply_to['status_id_str'] = null;
5022 $in_reply_to['user_id_str'] = null;
5023 $in_reply_to['screen_name'] = null;
5025 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5026 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5027 if (DBA::isResult($parent)) {
5028 $in_reply_to['status_id'] = intval($parent['id']);
5030 $in_reply_to['status_id'] = intval($item['parent']);
5033 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5035 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5036 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5038 if (DBA::isResult($parent)) {
5039 if ($parent['author-nick'] == "") {
5040 $parent['author-nick'] = api_get_nick($parent['author-link']);
5043 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5044 $in_reply_to['user_id'] = intval($parent['author-id']);
5045 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5048 // There seems to be situation, where both fields are identical:
5049 // https://github.com/friendica/friendica/issues/1010
5050 // This is a bugfix for that.
5051 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5052 Logger::log('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], Logger::DEBUG);
5053 $in_reply_to['status_id'] = null;
5054 $in_reply_to['user_id'] = null;
5055 $in_reply_to['status_id_str'] = null;
5056 $in_reply_to['user_id_str'] = null;
5057 $in_reply_to['screen_name'] = null;
5061 return $in_reply_to;
5066 * @param string $text
5070 function api_clean_plain_items($text)
5072 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
5074 $text = BBCode::cleanPictureLinks($text);
5075 $URLSearchString = "^\[\]";
5077 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5079 if ($include_entities == "true") {
5080 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5083 // Simplify "attachment" element
5084 $text = api_clean_attachments($text);
5090 * @brief Removes most sharing information for API text export
5092 * @param string $body The original body
5094 * @return string Cleaned body
5096 function api_clean_attachments($body)
5098 $data = BBCode::getAttachmentData($body);
5105 if (isset($data["text"])) {
5106 $body = $data["text"];
5108 if (($body == "") && isset($data["title"])) {
5109 $body = $data["title"];
5111 if (isset($data["url"])) {
5112 $body .= "\n".$data["url"];
5114 $body .= $data["after"];
5121 * @param array $contacts
5125 function api_best_nickname(&$contacts)
5129 if (count($contacts) == 0) {
5133 foreach ($contacts as $contact) {
5134 if ($contact["network"] == "") {
5135 $contact["network"] = "dfrn";
5136 $best_contact = [$contact];
5140 if (sizeof($best_contact) == 0) {
5141 foreach ($contacts as $contact) {
5142 if ($contact["network"] == "dfrn") {
5143 $best_contact = [$contact];
5148 if (sizeof($best_contact) == 0) {
5149 foreach ($contacts as $contact) {
5150 if ($contact["network"] == "dspr") {
5151 $best_contact = [$contact];
5156 if (sizeof($best_contact) == 0) {
5157 foreach ($contacts as $contact) {
5158 if ($contact["network"] == "stat") {
5159 $best_contact = [$contact];
5164 if (sizeof($best_contact) == 0) {
5165 foreach ($contacts as $contact) {
5166 if ($contact["network"] == "pump") {
5167 $best_contact = [$contact];
5172 if (sizeof($best_contact) == 0) {
5173 foreach ($contacts as $contact) {
5174 if ($contact["network"] == "twit") {
5175 $best_contact = [$contact];
5180 if (sizeof($best_contact) == 1) {
5181 $contacts = $best_contact;
5183 $contacts = [$contacts[0]];
5188 * Return all or a specified group of the user with the containing contacts.
5190 * @param string $type Return type (atom, rss, xml, json)
5192 * @return array|string
5194 function api_friendica_group_show($type)
5198 if (api_user() === false) {
5199 throw new ForbiddenException();
5203 $user_info = api_get_user($a);
5204 $gid = defaults($_REQUEST, 'gid', 0);
5205 $uid = $user_info['uid'];
5207 // get data of the specified group id or all groups if not specified
5210 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5214 // error message if specified gid is not in database
5215 if (!DBA::isResult($r)) {
5216 throw new BadRequestException("gid not available");
5220 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5225 // loop through all groups and retrieve all members for adding data in the user array
5227 foreach ($r as $rr) {
5228 $members = Contact::getByGroupId($rr['id']);
5231 if ($type == "xml") {
5232 $user_element = "users";
5234 foreach ($members as $member) {
5235 $user = api_get_user($a, $member['nurl']);
5236 $users[$k++.":user"] = $user;
5239 $user_element = "user";
5240 foreach ($members as $member) {
5241 $user = api_get_user($a, $member['nurl']);
5245 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5247 return api_format_data("groups", $type, ['group' => $grps]);
5249 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5253 * Delete the specified group of the user.
5255 * @param string $type Return type (atom, rss, xml, json)
5257 * @return array|string
5259 function api_friendica_group_delete($type)
5263 if (api_user() === false) {
5264 throw new ForbiddenException();
5268 $user_info = api_get_user($a);
5269 $gid = defaults($_REQUEST, 'gid', 0);
5270 $name = defaults($_REQUEST, 'name', "");
5271 $uid = $user_info['uid'];
5273 // error if no gid specified
5274 if ($gid == 0 || $name == "") {
5275 throw new BadRequestException('gid or name not specified');
5278 // get data of the specified group id
5280 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5284 // error message if specified gid is not in database
5285 if (!DBA::isResult($r)) {
5286 throw new BadRequestException('gid not available');
5289 // get data of the specified group id and group name
5291 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5296 // error message if specified gid is not in database
5297 if (!DBA::isResult($rname)) {
5298 throw new BadRequestException('wrong group name');
5302 $ret = Group::removeByName($uid, $name);
5305 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5306 return api_format_data("group_delete", $type, ['result' => $success]);
5308 throw new BadRequestException('other API error');
5311 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5316 * @param string $type Return type (atom, rss, xml, json)
5318 * @return array|string
5319 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5321 function api_lists_destroy($type)
5325 if (api_user() === false) {
5326 throw new ForbiddenException();
5330 $user_info = api_get_user($a);
5331 $gid = defaults($_REQUEST, 'list_id', 0);
5332 $uid = $user_info['uid'];
5334 // error if no gid specified
5336 throw new BadRequestException('gid not specified');
5339 // get data of the specified group id
5340 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5341 // error message if specified gid is not in database
5343 throw new BadRequestException('gid not available');
5346 if (Group::remove($gid)) {
5348 'name' => $group['name'],
5349 'id' => intval($gid),
5350 'id_str' => (string) $gid,
5351 'user' => $user_info
5354 return api_format_data("lists", $type, ['lists' => $list]);
5357 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5360 * Add a new group to the database.
5362 * @param string $name Group name
5363 * @param int $uid User ID
5364 * @param array $users List of users to add to the group
5368 function group_create($name, $uid, $users = [])
5370 // error if no name specified
5372 throw new BadRequestException('group name not specified');
5375 // get data of the specified group name
5377 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5381 // error message if specified group name already exists
5382 if (DBA::isResult($rname)) {
5383 throw new BadRequestException('group name already exists');
5386 // check if specified group name is a deleted group
5388 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5392 // error message if specified group name already exists
5393 if (DBA::isResult($rname)) {
5394 $reactivate_group = true;
5398 $ret = Group::create($uid, $name);
5400 $gid = Group::getIdByName($uid, $name);
5402 throw new BadRequestException('other API error');
5406 $erroraddinguser = false;
5408 foreach ($users as $user) {
5409 $cid = $user['cid'];
5410 // check if user really exists as contact
5412 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5416 if (count($contact)) {
5417 Group::addMember($gid, $cid);
5419 $erroraddinguser = true;
5420 $errorusers[] = $cid;
5424 // return success message incl. missing users in array
5425 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5427 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5431 * Create the specified group with the posted array of contacts.
5433 * @param string $type Return type (atom, rss, xml, json)
5435 * @return array|string
5437 function api_friendica_group_create($type)
5441 if (api_user() === false) {
5442 throw new ForbiddenException();
5446 $user_info = api_get_user($a);
5447 $name = defaults($_REQUEST, 'name', "");
5448 $uid = $user_info['uid'];
5449 $json = json_decode($_POST['json'], true);
5450 $users = $json['user'];
5452 $success = group_create($name, $uid, $users);
5454 return api_format_data("group_create", $type, ['result' => $success]);
5456 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5459 * Create a new group.
5461 * @param string $type Return type (atom, rss, xml, json)
5463 * @return array|string
5464 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5466 function api_lists_create($type)
5470 if (api_user() === false) {
5471 throw new ForbiddenException();
5475 $user_info = api_get_user($a);
5476 $name = defaults($_REQUEST, 'name', "");
5477 $uid = $user_info['uid'];
5479 $success = group_create($name, $uid);
5480 if ($success['success']) {
5482 'name' => $success['name'],
5483 'id' => intval($success['gid']),
5484 'id_str' => (string) $success['gid'],
5485 'user' => $user_info
5488 return api_format_data("lists", $type, ['lists'=>$grp]);
5491 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5494 * Update the specified group with the posted array of contacts.
5496 * @param string $type Return type (atom, rss, xml, json)
5498 * @return array|string
5500 function api_friendica_group_update($type)
5504 if (api_user() === false) {
5505 throw new ForbiddenException();
5509 $user_info = api_get_user($a);
5510 $uid = $user_info['uid'];
5511 $gid = defaults($_REQUEST, 'gid', 0);
5512 $name = defaults($_REQUEST, 'name', "");
5513 $json = json_decode($_POST['json'], true);
5514 $users = $json['user'];
5516 // error if no name specified
5518 throw new BadRequestException('group name not specified');
5521 // error if no gid specified
5523 throw new BadRequestException('gid not specified');
5527 $members = Contact::getByGroupId($gid);
5528 foreach ($members as $member) {
5529 $cid = $member['id'];
5530 foreach ($users as $user) {
5531 $found = ($user['cid'] == $cid ? true : false);
5533 if (!isset($found) || !$found) {
5534 Group::removeMemberByName($uid, $name, $cid);
5539 $erroraddinguser = false;
5541 foreach ($users as $user) {
5542 $cid = $user['cid'];
5543 // check if user really exists as contact
5545 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5550 if (count($contact)) {
5551 Group::addMember($gid, $cid);
5553 $erroraddinguser = true;
5554 $errorusers[] = $cid;
5558 // return success message incl. missing users in array
5559 $status = ($erroraddinguser ? "missing user" : "ok");
5560 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5561 return api_format_data("group_update", $type, ['result' => $success]);
5564 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5567 * Update information about a group.
5569 * @param string $type Return type (atom, rss, xml, json)
5571 * @return array|string
5572 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5574 function api_lists_update($type)
5578 if (api_user() === false) {
5579 throw new ForbiddenException();
5583 $user_info = api_get_user($a);
5584 $gid = defaults($_REQUEST, 'list_id', 0);
5585 $name = defaults($_REQUEST, 'name', "");
5586 $uid = $user_info['uid'];
5588 // error if no gid specified
5590 throw new BadRequestException('gid not specified');
5593 // get data of the specified group id
5594 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5595 // error message if specified gid is not in database
5597 throw new BadRequestException('gid not available');
5600 if (Group::update($gid, $name)) {
5603 'id' => intval($gid),
5604 'id_str' => (string) $gid,
5605 'user' => $user_info
5608 return api_format_data("lists", $type, ['lists' => $list]);
5612 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5616 * @param string $type Return type (atom, rss, xml, json)
5618 * @return array|string
5620 function api_friendica_activity($type)
5624 if (api_user() === false) {
5625 throw new ForbiddenException();
5627 $verb = strtolower($a->argv[3]);
5628 $verb = preg_replace("|\..*$|", "", $verb);
5630 $id = defaults($_REQUEST, 'id', 0);
5632 $res = Item::performLike($id, $verb);
5635 if ($type == "xml") {
5640 return api_format_data('ok', $type, ['ok' => $ok]);
5642 throw new BadRequestException('Error adding activity');
5646 /// @TODO move to top of file or somewhere better
5647 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5648 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5649 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5650 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5651 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5652 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5653 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5654 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5655 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5656 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5659 * @brief Returns notifications
5661 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5662 * @return string|array
5664 function api_friendica_notification($type)
5668 if (api_user() === false) {
5669 throw new ForbiddenException();
5672 throw new BadRequestException("Invalid argument count");
5674 $nm = new NotificationsManager();
5676 $notes = $nm->getAll([], "+seen -date", 50);
5678 if ($type == "xml") {
5680 if (!empty($notes)) {
5681 foreach ($notes as $note) {
5682 $xmlnotes[] = ["@attributes" => $note];
5689 return api_format_data("notes", $type, ['note' => $notes]);
5693 * POST request with 'id' param as notification id
5695 * @brief Set notification as seen and returns associated item (if possible)
5697 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5698 * @return string|array
5700 function api_friendica_notification_seen($type)
5703 $user_info = api_get_user($a);
5705 if (api_user() === false || $user_info === false) {
5706 throw new ForbiddenException();
5709 throw new BadRequestException("Invalid argument count");
5712 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5714 $nm = new NotificationsManager();
5715 $note = $nm->getByID($id);
5716 if (is_null($note)) {
5717 throw new BadRequestException("Invalid argument");
5720 $nm->setSeen($note);
5721 if ($note['otype']=='item') {
5722 // would be really better with an ItemsManager and $im->getByID() :-P
5723 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5724 if (DBA::isResult($item)) {
5725 // we found the item, return it to the user
5726 $ret = api_format_items([$item], $user_info, false, $type);
5727 $data = ['status' => $ret];
5728 return api_format_data("status", $type, $data);
5730 // the item can't be found, but we set the note as seen, so we count this as a success
5732 return api_format_data('result', $type, ['result' => "success"]);
5735 /// @TODO move to top of file or somewhere better
5736 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5737 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5740 * @brief update a direct_message to seen state
5742 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5743 * @return string|array (success result=ok, error result=error with error message)
5745 function api_friendica_direct_messages_setseen($type)
5748 if (api_user() === false) {
5749 throw new ForbiddenException();
5753 $user_info = api_get_user($a);
5754 $uid = $user_info['uid'];
5755 $id = defaults($_REQUEST, 'id', 0);
5757 // return error if id is zero
5759 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5760 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5763 // error message if specified id is not in database
5764 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5765 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5766 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5769 // update seen indicator
5770 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5774 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5775 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5777 $answer = ['result' => 'error', 'message' => 'unknown error'];
5778 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5782 /// @TODO move to top of file or somewhere better
5783 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5786 * @brief search for direct_messages containing a searchstring through api
5788 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5789 * @param string $box
5790 * @return string|array (success: success=true if found and search_result contains found messages,
5791 * success=false if nothing was found, search_result='nothing found',
5792 * error: result=error with error message)
5794 function api_friendica_direct_messages_search($type, $box = "")
5798 if (api_user() === false) {
5799 throw new ForbiddenException();
5803 $user_info = api_get_user($a);
5804 $searchstring = defaults($_REQUEST, 'searchstring', "");
5805 $uid = $user_info['uid'];
5807 // error if no searchstring specified
5808 if ($searchstring == "") {
5809 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5810 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5813 // get data for the specified searchstring
5815 "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",
5817 DBA::escape('%'.$searchstring.'%')
5820 $profile_url = $user_info["url"];
5822 // message if nothing was found
5823 if (!DBA::isResult($r)) {
5824 $success = ['success' => false, 'search_results' => 'problem with query'];
5825 } elseif (count($r) == 0) {
5826 $success = ['success' => false, 'search_results' => 'nothing found'];
5829 foreach ($r as $item) {
5830 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5831 $recipient = $user_info;
5832 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5833 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5834 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5835 $sender = $user_info;
5838 if (isset($recipient) && isset($sender)) {
5839 $ret[] = api_format_messages($item, $recipient, $sender);
5842 $success = ['success' => true, 'search_results' => $ret];
5845 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5848 /// @TODO move to top of file or somewhere better
5849 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5852 * @brief return data of all the profiles a user has to the client
5854 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5855 * @return string|array
5857 function api_friendica_profile_show($type)
5861 if (api_user() === false) {
5862 throw new ForbiddenException();
5866 $profile_id = defaults($_REQUEST, 'profile_id', 0);
5868 // retrieve general information about profiles for user
5869 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5870 $directory = Config::get('system', 'directory');
5872 // get data of the specified profile id or all profiles of the user if not specified
5873 if ($profile_id != 0) {
5875 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5880 // error message if specified gid is not in database
5881 if (!DBA::isResult($r)) {
5882 throw new BadRequestException("profile_id not available");
5886 "SELECT * FROM `profile` WHERE `uid` = %d",
5890 // loop through all returned profiles and retrieve data and users
5893 foreach ($r as $rr) {
5894 $profile = api_format_items_profiles($rr);
5896 // select all users from contact table, loop and prepare standard return for user data
5899 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5904 foreach ($nurls as $nurl) {
5905 $user = api_get_user($a, $nurl['nurl']);
5906 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5908 $profile['users'] = $users;
5910 // add prepared profile data to array for final return
5911 if ($type == "xml") {
5912 $profiles[$k++ . ":profile"] = $profile;
5914 $profiles[] = $profile;
5918 // return settings, authenticated user and profiles data
5919 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
5921 $result = ['multi_profiles' => $multi_profiles ? true : false,
5922 'global_dir' => $directory,
5923 'friendica_owner' => api_get_user($a, $self['nurl']),
5924 'profiles' => $profiles];
5925 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5927 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5930 * Returns a list of saved searches.
5932 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5934 * @param string $type Return format: json or xml
5936 * @return string|array
5938 function api_saved_searches_list($type)
5940 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
5943 while ($term = $terms->fetch()) {
5945 'created_at' => api_date(time()),
5946 'id' => intval($term['id']),
5947 'id_str' => $term['id'],
5948 'name' => $term['term'],
5950 'query' => $term['term']
5956 return api_format_data("terms", $type, ['terms' => $result]);
5959 /// @TODO move to top of file or somewhere better
5960 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5963 @TODO Maybe open to implement?
5965 [pagename] => api/1.1/statuses/lookup.json
5966 [id] => 605138389168451584
5967 [include_cards] => true
5968 [cards_platform] => Android-12
5969 [include_entities] => true
5970 [include_my_retweet] => 1
5972 [include_reply_count] => true
5973 [include_descendent_reply_count] => true
5977 Not implemented by now:
5978 statuses/retweets_of_me
5983 account/update_location
5984 account/update_profile_background_image
5987 friendica/profile/update
5988 friendica/profile/create
5989 friendica/profile/delete
5991 Not implemented in status.net:
5992 statuses/retweeted_to_me
5993 statuses/retweeted_by_me
5994 direct_messages/destroy
5996 account/update_delivery_device
5997 notifications/follow