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);
956 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
957 * returns a 401 status code and an error message if not.
958 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
960 * @param string $type Return type (atom, rss, xml, json)
962 function api_account_verify_credentials($type)
967 if (api_user() === false) {
968 throw new ForbiddenException();
971 unset($_REQUEST["user_id"]);
972 unset($_GET["user_id"]);
974 unset($_REQUEST["screen_name"]);
975 unset($_GET["screen_name"]);
977 $skip_status = defaults($_REQUEST, 'skip_status', false);
979 $user_info = api_get_user($a);
981 // "verified" isn't used here in the standard
982 unset($user_info["verified"]);
984 // - Adding last status
986 $user_info["status"] = api_status_show("raw");
987 if (!count($user_info["status"])) {
988 unset($user_info["status"]);
990 unset($user_info["status"]["user"]);
994 // "uid" and "self" are only needed for some internal stuff, so remove it from here
995 unset($user_info["uid"]);
996 unset($user_info["self"]);
998 return api_format_data("user", $type, ['user' => $user_info]);
1001 /// @TODO move to top of file or somewhere better
1002 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1005 * Get data from $_POST or $_GET
1009 function requestdata($k)
1011 if (!empty($_POST[$k])) {
1014 if (!empty($_GET[$k])) {
1021 * Deprecated function to upload media.
1023 * @param string $type Return type (atom, rss, xml, json)
1025 * @return array|string
1027 function api_statuses_mediap($type)
1031 if (api_user() === false) {
1032 Logger::log('api_statuses_update: no user');
1033 throw new ForbiddenException();
1035 $user_info = api_get_user($a);
1037 $_REQUEST['profile_uid'] = api_user();
1038 $_REQUEST['api_source'] = true;
1039 $txt = requestdata('status');
1040 /// @TODO old-lost code?
1041 //$txt = urldecode(requestdata('status'));
1043 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1044 $txt = HTML::toBBCodeVideo($txt);
1045 $config = HTMLPurifier_Config::createDefault();
1046 $config->set('Cache.DefinitionImpl', null);
1047 $purifier = new HTMLPurifier($config);
1048 $txt = $purifier->purify($txt);
1050 $txt = HTML::toBBCode($txt);
1052 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1054 $picture = wall_upload_post($a, false);
1056 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1057 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1058 $item_id = item_post($a);
1060 // output the post that we just posted.
1061 return api_status_show($type, $item_id);
1064 /// @TODO move this to top of file or somewhere better!
1065 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1068 * Updates the user’s current status.
1070 * @param string $type Return type (atom, rss, xml, json)
1072 * @return array|string
1073 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1075 function api_statuses_update($type)
1079 if (api_user() === false) {
1080 Logger::log('api_statuses_update: no user');
1081 throw new ForbiddenException();
1086 // convert $_POST array items to the form we use for web posts.
1087 if (requestdata('htmlstatus')) {
1088 $txt = requestdata('htmlstatus');
1089 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1090 $txt = HTML::toBBCodeVideo($txt);
1092 $config = HTMLPurifier_Config::createDefault();
1093 $config->set('Cache.DefinitionImpl', null);
1095 $purifier = new HTMLPurifier($config);
1096 $txt = $purifier->purify($txt);
1098 $_REQUEST['body'] = HTML::toBBCode($txt);
1101 $_REQUEST['body'] = requestdata('status');
1104 $_REQUEST['title'] = requestdata('title');
1106 $parent = requestdata('in_reply_to_status_id');
1108 // Twidere sends "-1" if it is no reply ...
1109 if ($parent == -1) {
1113 if (ctype_digit($parent)) {
1114 $_REQUEST['parent'] = $parent;
1116 $_REQUEST['parent_uri'] = $parent;
1119 if (requestdata('lat') && requestdata('long')) {
1120 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1122 $_REQUEST['profile_uid'] = api_user();
1125 // Check for throttling (maximum posts per day, week and month)
1126 $throttle_day = Config::get('system', 'throttle_limit_day');
1127 if ($throttle_day > 0) {
1128 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1130 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1131 $posts_day = DBA::count('thread', $condition);
1133 if ($posts_day > $throttle_day) {
1134 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1135 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1136 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));
1140 $throttle_week = Config::get('system', 'throttle_limit_week');
1141 if ($throttle_week > 0) {
1142 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1144 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1145 $posts_week = DBA::count('thread', $condition);
1147 if ($posts_week > $throttle_week) {
1148 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1149 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1150 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));
1154 $throttle_month = Config::get('system', 'throttle_limit_month');
1155 if ($throttle_month > 0) {
1156 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1158 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1159 $posts_month = DBA::count('thread', $condition);
1161 if ($posts_month > $throttle_month) {
1162 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1163 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1164 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));
1169 if (!empty($_FILES['media'])) {
1170 // upload the image if we have one
1171 $picture = wall_upload_post($a, false);
1172 if (is_array($picture)) {
1173 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1177 // To-Do: Multiple IDs
1178 if (requestdata('media_ids')) {
1180 "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",
1181 intval(requestdata('media_ids')),
1184 if (DBA::isResult($r)) {
1185 $phototypes = Image::supportedTypes();
1186 $ext = $phototypes[$r[0]['type']];
1187 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1188 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1192 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1194 $_REQUEST['api_source'] = true;
1196 if (empty($_REQUEST['source'])) {
1197 $_REQUEST["source"] = api_source();
1200 // call out normal post function
1201 $item_id = item_post($a);
1203 // output the post that we just posted.
1204 return api_status_show($type, $item_id);
1207 /// @TODO move to top of file or somewhere better
1208 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1209 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1212 * Uploads an image to Friendica.
1215 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1217 function api_media_upload()
1221 if (api_user() === false) {
1222 Logger::log('no user');
1223 throw new ForbiddenException();
1228 if (empty($_FILES['media'])) {
1230 throw new BadRequestException("No media.");
1233 $media = wall_upload_post($a, false);
1236 throw new InternalServerErrorException();
1240 $returndata["media_id"] = $media["id"];
1241 $returndata["media_id_string"] = (string)$media["id"];
1242 $returndata["size"] = $media["size"];
1243 $returndata["image"] = ["w" => $media["width"],
1244 "h" => $media["height"],
1245 "image_type" => $media["type"],
1246 "friendica_preview_url" => $media["preview"]];
1248 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1250 return ["media" => $returndata];
1253 /// @TODO move to top of file or somewhere better
1254 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1258 * @param string $type Return type (atom, rss, xml, json)
1260 * @return array|string
1262 function api_status_show($type, $item_id = 0)
1266 $user_info = api_get_user($a);
1268 Logger::log('api_status_show: user_info: '.print_r($user_info, true), Logger::DEBUG);
1270 if ($type == "raw") {
1271 $privacy_sql = "AND NOT `private`";
1276 if (!empty($item_id)) {
1277 // Get the item with the given id
1278 $condition = ['id' => $item_id];
1280 // get last public wall message
1281 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1282 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1284 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1286 if (DBA::isResult($lastwall)) {
1287 $in_reply_to = api_in_reply_to($lastwall);
1289 $converted = api_convert_item($lastwall);
1291 if ($type == "xml") {
1292 $geo = "georss:point";
1298 'created_at' => api_date($lastwall['created']),
1299 'id' => intval($lastwall['id']),
1300 'id_str' => (string) $lastwall['id'],
1301 'text' => $converted["text"],
1302 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1303 'truncated' => false,
1304 'in_reply_to_status_id' => $in_reply_to['status_id'],
1305 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1306 'in_reply_to_user_id' => $in_reply_to['user_id'],
1307 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1308 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1309 'user' => $user_info,
1311 'coordinates' => '',
1313 'contributors' => '',
1314 'is_quote_status' => false,
1315 'retweet_count' => 0,
1316 'favorite_count' => 0,
1317 'favorited' => $lastwall['starred'] ? true : false,
1318 'retweeted' => false,
1319 'possibly_sensitive' => false,
1321 'statusnet_html' => $converted["html"],
1322 'statusnet_conversation_id' => $lastwall['parent'],
1323 'external_url' => System::baseUrl() . '/display/' . $lastwall['guid'],
1326 if (count($converted["attachments"]) > 0) {
1327 $status_info["attachments"] = $converted["attachments"];
1330 if (count($converted["entities"]) > 0) {
1331 $status_info["entities"] = $converted["entities"];
1334 if ($status_info["source"] == 'web') {
1335 $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1336 } elseif (ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) != $status_info["source"]) {
1337 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']).')');
1340 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1341 unset($status_info["user"]["uid"]);
1342 unset($status_info["user"]["self"]);
1344 Logger::log('status_info: '.print_r($status_info, true), Logger::DEBUG);
1346 if ($type == "raw") {
1347 return $status_info;
1350 return api_format_data("statuses", $type, ['status' => $status_info]);
1355 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1356 * The author's most recent status will be returned inline.
1358 * @param string $type Return type (atom, rss, xml, json)
1359 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1361 function api_users_show($type)
1365 $user_info = api_get_user($a);
1367 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1368 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'private' => false];
1369 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1371 if (DBA::isResult($lastwall)) {
1372 $in_reply_to = api_in_reply_to($lastwall);
1374 $converted = api_convert_item($lastwall);
1376 if ($type == "xml") {
1377 $geo = "georss:point";
1382 $user_info['status'] = [
1383 'text' => $converted["text"],
1384 'truncated' => false,
1385 'created_at' => api_date($lastwall['created']),
1386 'in_reply_to_status_id' => $in_reply_to['status_id'],
1387 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1388 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1389 'id' => intval($lastwall['contact-id']),
1390 'id_str' => (string) $lastwall['contact-id'],
1391 'in_reply_to_user_id' => $in_reply_to['user_id'],
1392 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1393 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1395 'favorited' => $lastwall['starred'] ? true : false,
1396 'statusnet_html' => $converted["html"],
1397 'statusnet_conversation_id' => $lastwall['parent'],
1398 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1401 if (count($converted["attachments"]) > 0) {
1402 $user_info["status"]["attachments"] = $converted["attachments"];
1405 if (count($converted["entities"]) > 0) {
1406 $user_info["status"]["entities"] = $converted["entities"];
1409 if ($user_info["status"]["source"] == 'web') {
1410 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1413 if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
1414 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) . ')');
1418 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1419 unset($user_info["uid"]);
1420 unset($user_info["self"]);
1422 return api_format_data("user", $type, ['user' => $user_info]);
1425 /// @TODO move to top of file or somewhere better
1426 api_register_func('api/users/show', 'api_users_show');
1427 api_register_func('api/externalprofile/show', 'api_users_show');
1430 * Search a public user account.
1432 * @param string $type Return type (atom, rss, xml, json)
1434 * @return array|string
1435 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1437 function api_users_search($type)
1443 if (!empty($_GET['q'])) {
1444 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1446 if (!DBA::isResult($r)) {
1447 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1450 if (DBA::isResult($r)) {
1452 foreach ($r as $user) {
1453 $user_info = api_get_user($a, $user["id"]);
1455 if ($type == "xml") {
1456 $userlist[$k++.":user"] = $user_info;
1458 $userlist[] = $user_info;
1461 $userlist = ["users" => $userlist];
1463 throw new BadRequestException("User ".$_GET["q"]." not found.");
1466 throw new BadRequestException("No user specified.");
1469 return api_format_data("users", $type, $userlist);
1472 /// @TODO move to top of file or somewhere better
1473 api_register_func('api/users/search', 'api_users_search');
1476 * Return user objects
1478 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1480 * @param string $type Return format: json or xml
1482 * @return array|string
1483 * @throws NotFoundException if the results are empty.
1485 function api_users_lookup($type)
1489 if (!empty($_REQUEST['user_id'])) {
1490 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1492 $users[] = api_get_user(get_app(), $id);
1497 if (empty($users)) {
1498 throw new NotFoundException;
1501 return api_format_data("users", $type, ['users' => $users]);
1504 /// @TODO move to top of file or somewhere better
1505 api_register_func('api/users/lookup', 'api_users_lookup', true);
1508 * Returns statuses that match a specified query.
1510 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1512 * @param string $type Return format: json, xml, atom, rss
1514 * @return array|string
1515 * @throws BadRequestException if the "q" parameter is missing.
1517 function api_search($type)
1520 $user_info = api_get_user($a);
1522 if (api_user() === false || $user_info === false) { throw new ForbiddenException(); }
1524 if (empty($_REQUEST['q'])) { throw new BadRequestException("q parameter is required."); }
1526 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1530 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1531 if (!empty($_REQUEST['rpp'])) {
1532 $count = $_REQUEST['rpp'];
1533 } elseif (!empty($_REQUEST['count'])) {
1534 $count = $_REQUEST['count'];
1537 $since_id = defaults($_REQUEST, 'since_id', 0);
1538 $max_id = defaults($_REQUEST, 'max_id', 0);
1539 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1540 $start = $page * $count;
1541 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1542 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1543 $searchTerm = $matches[1];
1544 $condition = ["`oid` > ?
1545 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1546 AND `otype` = ? AND `type` = ? AND `term` = ?",
1547 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1549 $condition[0] .= " AND `oid` <= ?";
1550 $condition[] = $max_id;
1552 $terms = DBA::select('term', ['oid'], $condition, []);
1554 while($term = DBA::fetch($terms)){ $itemIds[] = $term['oid']; }
1556 $condition = [$exclude_replies ? "`id` = `parent` AND " : ''];
1557 $condition[0] .= empty($itemIds) ? '' : ' `id` IN ('.implode(", ", $itemIds).')' ;
1560 $condition = ["`id` > ?
1561 ". ($exclude_replies ? " AND `id` = `parent` " : ' ')."
1562 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1563 AND `body` LIKE CONCAT('%',?,'%')",
1564 $since_id, api_user(), $_REQUEST['q']];
1566 $condition[0] .= " AND `id` <= ?";
1567 $condition[] = $max_id;
1572 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1574 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1576 bindComments($data['status']);
1578 return api_format_data("statuses", $type, $data);
1581 /// @TODO move to top of file or somewhere better
1582 api_register_func('api/search/tweets', 'api_search', true);
1583 api_register_func('api/search', 'api_search', true);
1586 * Returns the most recent statuses posted by the user and the users they follow.
1588 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1590 * @param string $type Return type (atom, rss, xml, json)
1592 * @todo Optional parameters
1593 * @todo Add reply info
1595 function api_statuses_home_timeline($type)
1598 $user_info = api_get_user($a);
1600 if (api_user() === false || $user_info === false) {
1601 throw new ForbiddenException();
1604 unset($_REQUEST["user_id"]);
1605 unset($_GET["user_id"]);
1607 unset($_REQUEST["screen_name"]);
1608 unset($_GET["screen_name"]);
1610 // get last network messages
1613 $count = defaults($_REQUEST, 'count', 20);
1614 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1618 $since_id = defaults($_REQUEST, 'since_id', 0);
1619 $max_id = defaults($_REQUEST, 'max_id', 0);
1620 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1621 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1623 $start = $page * $count;
1625 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1626 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1629 $condition[0] .= " AND `item`.`id` <= ?";
1630 $condition[] = $max_id;
1632 if ($exclude_replies) {
1633 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1635 if ($conversation_id > 0) {
1636 $condition[0] .= " AND `item`.`parent` = ?";
1637 $condition[] = $conversation_id;
1640 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1641 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1643 $items = Item::inArray($statuses);
1645 $ret = api_format_items($items, $user_info, false, $type);
1647 // Set all posts from the query above to seen
1649 foreach ($items as $item) {
1650 $idarray[] = intval($item["id"]);
1653 if (!empty($idarray)) {
1654 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1656 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1662 $data = ['status' => $ret];
1667 $data = api_rss_extra($a, $data, $user_info);
1671 return api_format_data("statuses", $type, $data);
1675 /// @TODO move to top of file or somewhere better
1676 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1677 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1680 * Returns the most recent statuses from public users.
1682 * @param string $type Return type (atom, rss, xml, json)
1684 * @return array|string
1686 function api_statuses_public_timeline($type)
1689 $user_info = api_get_user($a);
1691 if (api_user() === false || $user_info === false) {
1692 throw new ForbiddenException();
1695 // get last network messages
1698 $count = defaults($_REQUEST, 'count', 20);
1699 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
1703 $since_id = defaults($_REQUEST, 'since_id', 0);
1704 $max_id = defaults($_REQUEST, 'max_id', 0);
1705 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1706 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1708 $start = $page * $count;
1710 if ($exclude_replies && !$conversation_id) {
1711 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall`",
1712 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1715 $condition[0] .= " AND `thread`.`iid` <= ?";
1716 $condition[] = $max_id;
1719 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1720 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1722 $r = Item::inArray($statuses);
1724 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin`",
1725 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1728 $condition[0] .= " AND `item`.`id` <= ?";
1729 $condition[] = $max_id;
1731 if ($conversation_id > 0) {
1732 $condition[0] .= " AND `item`.`parent` = ?";
1733 $condition[] = $conversation_id;
1736 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1737 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1739 $r = Item::inArray($statuses);
1742 $ret = api_format_items($r, $user_info, false, $type);
1746 $data = ['status' => $ret];
1751 $data = api_rss_extra($a, $data, $user_info);
1755 return api_format_data("statuses", $type, $data);
1758 /// @TODO move to top of file or somewhere better
1759 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1762 * Returns the most recent statuses posted by users this node knows about.
1764 * @brief Returns the list of public federated posts this node knows about
1766 * @param string $type Return format: json, xml, atom, rss
1767 * @return array|string
1768 * @throws ForbiddenException
1770 function api_statuses_networkpublic_timeline($type)
1773 $user_info = api_get_user($a);
1775 if (api_user() === false || $user_info === false) {
1776 throw new ForbiddenException();
1779 $since_id = defaults($_REQUEST, 'since_id', 0);
1780 $max_id = defaults($_REQUEST, 'max_id', 0);
1783 $count = defaults($_REQUEST, 'count', 20);
1784 $page = defaults($_REQUEST, 'page', 1);
1788 $start = ($page - 1) * $count;
1790 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1791 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1794 $condition[0] .= " AND `thread`.`iid` <= ?";
1795 $condition[] = $max_id;
1798 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1799 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1801 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1805 $data = ['status' => $ret];
1810 $data = api_rss_extra($a, $data, $user_info);
1814 return api_format_data("statuses", $type, $data);
1817 /// @TODO move to top of file or somewhere better
1818 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1821 * Returns a single status.
1823 * @param string $type Return type (atom, rss, xml, json)
1825 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1827 function api_statuses_show($type)
1830 $user_info = api_get_user($a);
1832 if (api_user() === false || $user_info === false) {
1833 throw new ForbiddenException();
1837 $id = intval(defaults($a->argv, 3, 0));
1840 $id = intval(defaults($_REQUEST, 'id', 0));
1845 $id = intval(defaults($a->argv, 4, 0));
1848 Logger::log('API: api_statuses_show: ' . $id);
1850 $conversation = !empty($_REQUEST['conversation']);
1852 // try to fetch the item for the local user - or the public item, if there is no local one
1853 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1854 if (!DBA::isResult($uri_item)) {
1855 throw new BadRequestException("There is no status with this id.");
1858 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1859 if (!DBA::isResult($item)) {
1860 throw new BadRequestException("There is no status with this id.");
1865 if ($conversation) {
1866 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1867 $params = ['order' => ['id' => true]];
1869 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1873 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1875 /// @TODO How about copying this to above methods which don't check $r ?
1876 if (!DBA::isResult($statuses)) {
1877 throw new BadRequestException("There is no status with this id.");
1880 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1882 if ($conversation) {
1883 $data = ['status' => $ret];
1884 return api_format_data("statuses", $type, $data);
1886 $data = ['status' => $ret[0]];
1887 return api_format_data("status", $type, $data);
1891 /// @TODO move to top of file or somewhere better
1892 api_register_func('api/statuses/show', 'api_statuses_show', true);
1896 * @param string $type Return type (atom, rss, xml, json)
1898 * @todo nothing to say?
1900 function api_conversation_show($type)
1903 $user_info = api_get_user($a);
1905 if (api_user() === false || $user_info === false) {
1906 throw new ForbiddenException();
1910 $id = intval(defaults($a->argv , 3 , 0));
1911 $since_id = intval(defaults($_REQUEST, 'since_id', 0));
1912 $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
1913 $count = intval(defaults($_REQUEST, 'count' , 20));
1914 $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
1919 $start = $page * $count;
1922 $id = intval(defaults($_REQUEST, 'id', 0));
1927 $id = intval(defaults($a->argv, 4, 0));
1930 Logger::log('API: api_conversation_show: '.$id);
1932 // try to fetch the item for the local user - or the public item, if there is no local one
1933 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1934 if (!DBA::isResult($item)) {
1935 throw new BadRequestException("There is no status with this id.");
1938 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1939 if (!DBA::isResult($parent)) {
1940 throw new BadRequestException("There is no status with this id.");
1943 $id = $parent['id'];
1945 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1946 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1949 $condition[0] .= " AND `item`.`id` <= ?";
1950 $condition[] = $max_id;
1953 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1954 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1956 if (!DBA::isResult($statuses)) {
1957 throw new BadRequestException("There is no status with id $id.");
1960 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1962 $data = ['status' => $ret];
1963 return api_format_data("statuses", $type, $data);
1966 /// @TODO move to top of file or somewhere better
1967 api_register_func('api/conversation/show', 'api_conversation_show', true);
1968 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1973 * @param string $type Return type (atom, rss, xml, json)
1975 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1977 function api_statuses_repeat($type)
1983 if (api_user() === false) {
1984 throw new ForbiddenException();
1990 $id = intval(defaults($a->argv, 3, 0));
1993 $id = intval(defaults($_REQUEST, 'id', 0));
1998 $id = intval(defaults($a->argv, 4, 0));
2001 Logger::log('API: api_statuses_repeat: '.$id);
2003 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2004 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2006 if (DBA::isResult($item) && $item['body'] != "") {
2007 if (strpos($item['body'], "[/share]") !== false) {
2008 $pos = strpos($item['body'], "[share");
2009 $post = substr($item['body'], $pos);
2011 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2013 $post .= $item['body'];
2014 $post .= "[/share]";
2016 $_REQUEST['body'] = $post;
2017 $_REQUEST['profile_uid'] = api_user();
2018 $_REQUEST['api_source'] = true;
2020 if (empty($_REQUEST['source'])) {
2021 $_REQUEST["source"] = api_source();
2024 $item_id = item_post($a);
2026 throw new ForbiddenException();
2029 // output the post that we just posted.
2031 return api_status_show($type, $item_id);
2034 /// @TODO move to top of file or somewhere better
2035 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2038 * Destroys a specific status.
2040 * @param string $type Return type (atom, rss, xml, json)
2042 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2044 function api_statuses_destroy($type)
2048 if (api_user() === false) {
2049 throw new ForbiddenException();
2055 $id = intval(defaults($a->argv, 3, 0));
2058 $id = intval(defaults($_REQUEST, 'id', 0));
2063 $id = intval(defaults($a->argv, 4, 0));
2066 Logger::log('API: api_statuses_destroy: '.$id);
2068 $ret = api_statuses_show($type);
2070 Item::deleteForUser(['id' => $id], api_user());
2075 /// @TODO move to top of file or somewhere better
2076 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2079 * Returns the most recent mentions.
2081 * @param string $type Return type (atom, rss, xml, json)
2083 * @see http://developer.twitter.com/doc/get/statuses/mentions
2085 function api_statuses_mentions($type)
2088 $user_info = api_get_user($a);
2090 if (api_user() === false || $user_info === false) {
2091 throw new ForbiddenException();
2094 unset($_REQUEST["user_id"]);
2095 unset($_GET["user_id"]);
2097 unset($_REQUEST["screen_name"]);
2098 unset($_GET["screen_name"]);
2100 // get last network messages
2103 $since_id = defaults($_REQUEST, 'since_id', 0);
2104 $max_id = defaults($_REQUEST, 'max_id' , 0);
2105 $count = defaults($_REQUEST, 'count' , 20);
2106 $page = defaults($_REQUEST, 'page' , 1);
2111 $start = ($page - 1) * $count;
2113 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2114 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2115 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2118 $condition[0] .= " AND `item`.`id` <= ?";
2119 $condition[] = $max_id;
2122 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2123 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2125 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2127 $data = ['status' => $ret];
2132 $data = api_rss_extra($a, $data, $user_info);
2136 return api_format_data("statuses", $type, $data);
2139 /// @TODO move to top of file or somewhere better
2140 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2141 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2144 * Returns the most recent statuses posted by the user.
2146 * @brief Returns a user's public timeline
2148 * @param string $type Either "json" or "xml"
2149 * @return string|array
2150 * @throws ForbiddenException
2151 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2153 function api_statuses_user_timeline($type)
2156 $user_info = api_get_user($a);
2158 if (api_user() === false || $user_info === false) {
2159 throw new ForbiddenException();
2163 "api_statuses_user_timeline: api_user: ". api_user() .
2164 "\nuser_info: ".print_r($user_info, true) .
2165 "\n_REQUEST: ".print_r($_REQUEST, true),
2169 $since_id = defaults($_REQUEST, 'since_id', 0);
2170 $max_id = defaults($_REQUEST, 'max_id', 0);
2171 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2172 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
2175 $count = defaults($_REQUEST, 'count', 20);
2176 $page = defaults($_REQUEST, 'page', 1);
2180 $start = ($page - 1) * $count;
2182 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2183 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2185 if ($user_info['self'] == 1) {
2186 $condition[0] .= ' AND `item`.`wall` ';
2189 if ($exclude_replies) {
2190 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2193 if ($conversation_id > 0) {
2194 $condition[0] .= " AND `item`.`parent` = ?";
2195 $condition[] = $conversation_id;
2199 $condition[0] .= " AND `item`.`id` <= ?";
2200 $condition[] = $max_id;
2203 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2204 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2206 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2210 $data = ['status' => $ret];
2215 $data = api_rss_extra($a, $data, $user_info);
2219 return api_format_data("statuses", $type, $data);
2222 /// @TODO move to top of file or somewhere better
2223 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2226 * Star/unstar an item.
2227 * param: id : id of the item
2229 * @param string $type Return type (atom, rss, xml, json)
2231 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2233 function api_favorites_create_destroy($type)
2237 if (api_user() === false) {
2238 throw new ForbiddenException();
2241 // for versioned api.
2242 /// @TODO We need a better global soluton
2243 $action_argv_id = 2;
2244 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2245 $action_argv_id = 3;
2248 if ($a->argc <= $action_argv_id) {
2249 throw new BadRequestException("Invalid request.");
2251 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2252 if ($a->argc == $action_argv_id + 2) {
2253 $itemid = intval(defaults($a->argv, $action_argv_id + 1, 0));
2255 $itemid = intval(defaults($_REQUEST, 'id', 0));
2258 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2260 if (!DBA::isResult($item)) {
2261 throw new BadRequestException("Invalid item.");
2266 $item['starred'] = 1;
2269 $item['starred'] = 0;
2272 throw new BadRequestException("Invalid action ".$action);
2275 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2278 throw new InternalServerErrorException("DB error");
2282 $user_info = api_get_user($a);
2283 $rets = api_format_items([$item], $user_info, false, $type);
2286 $data = ['status' => $ret];
2291 $data = api_rss_extra($a, $data, $user_info);
2295 return api_format_data("status", $type, $data);
2298 /// @TODO move to top of file or somewhere better
2299 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2300 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2303 * Returns the most recent favorite statuses.
2305 * @param string $type Return type (atom, rss, xml, json)
2307 * @return string|array
2309 function api_favorites($type)
2314 $user_info = api_get_user($a);
2316 if (api_user() === false || $user_info === false) {
2317 throw new ForbiddenException();
2322 // in friendica starred item are private
2323 // return favorites only for self
2324 Logger::log('api_favorites: self:' . $user_info['self']);
2326 if ($user_info['self'] == 0) {
2330 $since_id = defaults($_REQUEST, 'since_id', 0);
2331 $max_id = defaults($_REQUEST, 'max_id', 0);
2332 $count = defaults($_GET, 'count', 20);
2333 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
2338 $start = $page*$count;
2340 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2341 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2343 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2346 $condition[0] .= " AND `item`.`id` <= ?";
2347 $condition[] = $max_id;
2350 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2352 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2357 $data = ['status' => $ret];
2362 $data = api_rss_extra($a, $data, $user_info);
2366 return api_format_data("statuses", $type, $data);
2369 /// @TODO move to top of file or somewhere better
2370 api_register_func('api/favorites', 'api_favorites', true);
2374 * @param array $item
2375 * @param array $recipient
2376 * @param array $sender
2380 function api_format_messages($item, $recipient, $sender)
2382 // standard meta information
2384 'id' => $item['id'],
2385 'sender_id' => $sender['id'],
2387 'recipient_id' => $recipient['id'],
2388 'created_at' => api_date(defaults($item, 'created', DateTimeFormat::utcNow())),
2389 'sender_screen_name' => $sender['screen_name'],
2390 'recipient_screen_name' => $recipient['screen_name'],
2391 'sender' => $sender,
2392 'recipient' => $recipient,
2394 'friendica_seen' => defaults($item, 'seen', 0),
2395 'friendica_parent_uri' => defaults($item, 'parent-uri', ''),
2398 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2399 if (isset($ret['sender']['uid'])) {
2400 unset($ret['sender']['uid']);
2402 if (isset($ret['sender']['self'])) {
2403 unset($ret['sender']['self']);
2405 if (isset($ret['recipient']['uid'])) {
2406 unset($ret['recipient']['uid']);
2408 if (isset($ret['recipient']['self'])) {
2409 unset($ret['recipient']['self']);
2412 //don't send title to regular StatusNET requests to avoid confusing these apps
2413 if (!empty($_GET['getText'])) {
2414 $ret['title'] = $item['title'];
2415 if ($_GET['getText'] == 'html') {
2416 $ret['text'] = BBCode::convert($item['body'], false);
2417 } elseif ($_GET['getText'] == 'plain') {
2418 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2421 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2423 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2424 unset($ret['sender']);
2425 unset($ret['recipient']);
2433 * @param array $item
2437 function api_convert_item($item)
2439 $body = $item['body'];
2440 $attachments = api_get_attachments($body);
2442 // Workaround for ostatus messages where the title is identically to the body
2443 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2444 $statusbody = trim(HTML::toPlaintext($html, 0));
2446 // handle data: images
2447 $statusbody = api_format_items_embeded_images($item, $statusbody);
2449 $statustitle = trim($item['title']);
2451 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2452 $statustext = trim($statusbody);
2454 $statustext = trim($statustitle."\n\n".$statusbody);
2457 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($statustext)> 1000)) {
2458 $statustext = substr($statustext, 0, 1000) . "... \n" . defaults($item, 'plink', '');
2461 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2463 // Workaround for clients with limited HTML parser functionality
2464 $search = ["<br>", "<blockquote>", "</blockquote>",
2465 "<h1>", "</h1>", "<h2>", "</h2>",
2466 "<h3>", "</h3>", "<h4>", "</h4>",
2467 "<h5>", "</h5>", "<h6>", "</h6>"];
2468 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2469 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2470 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2471 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2472 $statushtml = str_replace($search, $replace, $statushtml);
2474 if ($item['title'] != "") {
2475 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2479 $oldtext = $statushtml;
2480 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2481 } while ($oldtext != $statushtml);
2483 if (substr($statushtml, 0, 4) == '<br>') {
2484 $statushtml = substr($statushtml, 4);
2487 if (substr($statushtml, 0, -4) == '<br>') {
2488 $statushtml = substr($statushtml, -4);
2491 // feeds without body should contain the link
2492 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2493 $statushtml .= BBCode::convert($item['plink']);
2496 $entities = api_get_entitities($statustext, $body);
2499 "text" => $statustext,
2500 "html" => $statushtml,
2501 "attachments" => $attachments,
2502 "entities" => $entities
2508 * @param string $body
2512 function api_get_attachments(&$body)
2515 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2517 $URLSearchString = "^\[\]";
2518 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2526 foreach ($images[1] as $image) {
2527 $imagedata = Image::getInfoFromURL($image);
2530 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2534 if (strstr(defaults($_SERVER, 'HTTP_USER_AGENT', ''), "AndStatus")) {
2535 foreach ($images[0] as $orig) {
2536 $body = str_replace($orig, "", $body);
2540 return $attachments;
2545 * @param string $text
2546 * @param string $bbcode
2549 * @todo Links at the first character of the post
2551 function api_get_entitities(&$text, $bbcode)
2553 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
2555 if ($include_entities != "true") {
2556 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2558 foreach ($images[1] as $image) {
2559 $replace = ProxyUtils::proxifyUrl($image);
2560 $text = str_replace($image, $replace, $text);
2565 $bbcode = BBCode::cleanPictureLinks($bbcode);
2567 // Change pure links in text to bbcode uris
2568 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2571 $entities["hashtags"] = [];
2572 $entities["symbols"] = [];
2573 $entities["urls"] = [];
2574 $entities["user_mentions"] = [];
2576 $URLSearchString = "^\[\]";
2578 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2580 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2581 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2582 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2584 $bbcode = preg_replace(
2585 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2586 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2589 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2591 $bbcode = preg_replace(
2592 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2593 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2596 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2598 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2600 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2601 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2604 foreach ($urls[1] as $id => $url) {
2605 //$start = strpos($text, $url, $offset);
2606 $start = iconv_strpos($text, $url, 0, "UTF-8");
2607 if (!($start === false)) {
2608 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2612 ksort($ordered_urls);
2615 //foreach ($urls[1] AS $id=>$url) {
2616 foreach ($ordered_urls as $url) {
2617 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2618 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2620 $display_url = $url["title"];
2622 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2623 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2625 if (strlen($display_url) > 26) {
2626 $display_url = substr($display_url, 0, 25)."…";
2630 //$start = strpos($text, $url, $offset);
2631 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2632 if (!($start === false)) {
2633 $entities["urls"][] = ["url" => $url["url"],
2634 "expanded_url" => $url["url"],
2635 "display_url" => $display_url,
2636 "indices" => [$start, $start+strlen($url["url"])]];
2637 $offset = $start + 1;
2641 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2642 $ordered_images = [];
2643 foreach ($images[1] as $image) {
2644 //$start = strpos($text, $url, $offset);
2645 $start = iconv_strpos($text, $image, 0, "UTF-8");
2646 if (!($start === false)) {
2647 $ordered_images[$start] = $image;
2650 //$entities["media"] = array();
2653 foreach ($ordered_images as $url) {
2654 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2655 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2657 if (strlen($display_url) > 26) {
2658 $display_url = substr($display_url, 0, 25)."…";
2661 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2662 if (!($start === false)) {
2663 $image = Image::getInfoFromURL($url);
2665 // If image cache is activated, then use the following sizes:
2666 // thumb (150), small (340), medium (600) and large (1024)
2667 if (!Config::get("system", "proxy_disabled")) {
2668 $media_url = ProxyUtils::proxifyUrl($url);
2671 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2672 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2674 if (($image[0] > 150) || ($image[1] > 150)) {
2675 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2676 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2679 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2680 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2682 if (($image[0] > 600) || ($image[1] > 600)) {
2683 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2684 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2688 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2691 $entities["media"][] = [
2693 "id_str" => (string)$start+1,
2694 "indices" => [$start, $start+strlen($url)],
2695 "media_url" => Strings::normaliseLink($media_url),
2696 "media_url_https" => $media_url,
2698 "display_url" => $display_url,
2699 "expanded_url" => $url,
2703 $offset = $start + 1;
2712 * @param array $item
2713 * @param string $text
2717 function api_format_items_embeded_images($item, $text)
2719 $text = preg_replace_callback(
2720 '|data:image/([^;]+)[^=]+=*|m',
2721 function () use ($item) {
2722 return System::baseUrl() . '/display/' . $item['guid'];
2730 * @brief return <a href='url'>name</a> as array
2732 * @param string $txt text
2737 function api_contactlink_to_array($txt)
2740 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2741 if ($r && count($match)==3) {
2743 'name' => $match[2],
2757 * @brief return likes, dislikes and attend status for item
2759 * @param array $item array
2760 * @param string $type Return type (atom, rss, xml, json)
2763 * likes => int count,
2764 * dislikes => int count
2766 function api_format_items_activities($item, $type = "json")
2775 'attendmaybe' => [],
2778 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2779 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2781 while ($parent_item = Item::fetch($ret)) {
2782 // not used as result should be structured like other user data
2783 //builtin_activity_puller($i, $activities);
2785 // get user data and add it to the array of the activity
2786 $user = api_get_user($a, $parent_item['author-id']);
2787 switch ($parent_item['verb']) {
2789 $activities['like'][] = $user;
2791 case ACTIVITY_DISLIKE:
2792 $activities['dislike'][] = $user;
2794 case ACTIVITY_ATTEND:
2795 $activities['attendyes'][] = $user;
2797 case ACTIVITY_ATTENDNO:
2798 $activities['attendno'][] = $user;
2800 case ACTIVITY_ATTENDMAYBE:
2801 $activities['attendmaybe'][] = $user;
2810 if ($type == "xml") {
2811 $xml_activities = [];
2812 foreach ($activities as $k => $v) {
2813 // change xml element from "like" to "friendica:like"
2814 $xml_activities["friendica:".$k] = $v;
2815 // add user data into xml output
2817 foreach ($v as $user) {
2818 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2821 $activities = $xml_activities;
2829 * @brief return data from profiles
2831 * @param array $profile_row array containing data from db table 'profile'
2834 function api_format_items_profiles($profile_row)
2837 'profile_id' => $profile_row['id'],
2838 'profile_name' => $profile_row['profile-name'],
2839 'is_default' => $profile_row['is-default'] ? true : false,
2840 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2841 'profile_photo' => $profile_row['photo'],
2842 'profile_thumb' => $profile_row['thumb'],
2843 'publish' => $profile_row['publish'] ? true : false,
2844 'net_publish' => $profile_row['net-publish'] ? true : false,
2845 'description' => $profile_row['pdesc'],
2846 'date_of_birth' => $profile_row['dob'],
2847 'address' => $profile_row['address'],
2848 'city' => $profile_row['locality'],
2849 'region' => $profile_row['region'],
2850 'postal_code' => $profile_row['postal-code'],
2851 'country' => $profile_row['country-name'],
2852 'hometown' => $profile_row['hometown'],
2853 'gender' => $profile_row['gender'],
2854 'marital' => $profile_row['marital'],
2855 'marital_with' => $profile_row['with'],
2856 'marital_since' => $profile_row['howlong'],
2857 'sexual' => $profile_row['sexual'],
2858 'politic' => $profile_row['politic'],
2859 'religion' => $profile_row['religion'],
2860 'public_keywords' => $profile_row['pub_keywords'],
2861 'private_keywords' => $profile_row['prv_keywords'],
2862 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2863 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2864 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2865 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2866 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2867 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2868 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2869 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2870 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2871 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2872 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2873 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2874 'homepage' => $profile_row['homepage'],
2881 * @brief format items to be returned by api
2883 * @param array $r array of items
2884 * @param array $user_info
2885 * @param bool $filter_user filter items by $user_info
2886 * @param string $type Return type (atom, rss, xml, json)
2888 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2894 foreach ((array)$r as $item) {
2895 localize_item($item);
2896 list($status_user, $owner_user) = api_item_get_user($a, $item);
2898 // Look if the posts are matching if they should be filtered by user id
2899 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2903 $in_reply_to = api_in_reply_to($item);
2905 $converted = api_convert_item($item);
2907 if ($type == "xml") {
2908 $geo = "georss:point";
2914 'text' => $converted["text"],
2915 'truncated' => false,
2916 'created_at'=> api_date($item['created']),
2917 'in_reply_to_status_id' => $in_reply_to['status_id'],
2918 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2919 'source' => (($item['app']) ? $item['app'] : 'web'),
2920 'id' => intval($item['id']),
2921 'id_str' => (string) intval($item['id']),
2922 'in_reply_to_user_id' => $in_reply_to['user_id'],
2923 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2924 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2926 'favorited' => $item['starred'] ? true : false,
2927 'user' => $status_user,
2928 'friendica_owner' => $owner_user,
2929 'friendica_private' => $item['private'] == 1,
2930 //'entities' => NULL,
2931 'statusnet_html' => $converted["html"],
2932 'statusnet_conversation_id' => $item['parent'],
2933 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2934 'friendica_activities' => api_format_items_activities($item, $type),
2937 if (count($converted["attachments"]) > 0) {
2938 $status["attachments"] = $converted["attachments"];
2941 if (count($converted["entities"]) > 0) {
2942 $status["entities"] = $converted["entities"];
2945 if ($status["source"] == 'web') {
2946 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
2947 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
2948 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
2951 if ($item["id"] == $item["parent"]) {
2952 $retweeted_item = api_share_as_retweet($item);
2953 if ($retweeted_item !== false) {
2954 $retweeted_status = $status;
2955 $status['user'] = $status['friendica_owner'];
2957 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
2958 } catch (BadRequestException $e) {
2959 // user not found. should be found?
2960 /// @todo check if the user should be always found
2961 $retweeted_status["user"] = [];
2964 $rt_converted = api_convert_item($retweeted_item);
2966 $retweeted_status['text'] = $rt_converted["text"];
2967 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2968 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2969 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2970 $status['retweeted_status'] = $retweeted_status;
2974 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2975 unset($status["user"]["uid"]);
2976 unset($status["user"]["self"]);
2978 if ($item["coord"] != "") {
2979 $coords = explode(' ', $item["coord"]);
2980 if (count($coords) == 2) {
2981 if ($type == "json") {
2982 $status["geo"] = ['type' => 'Point',
2983 'coordinates' => [(float) $coords[0],
2984 (float) $coords[1]]];
2985 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2986 $status["georss:point"] = $item["coord"];
2996 * Returns the remaining number of API requests available to the user before the API limit is reached.
2998 * @param string $type Return type (atom, rss, xml, json)
3000 * @return array|string
3002 function api_account_rate_limit_status($type)
3004 if ($type == "xml") {
3006 'remaining-hits' => '150',
3007 '@attributes' => ["type" => "integer"],
3008 'hourly-limit' => '150',
3009 '@attributes2' => ["type" => "integer"],
3010 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3011 '@attributes3' => ["type" => "datetime"],
3012 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3013 '@attributes4' => ["type" => "integer"],
3017 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3018 'remaining_hits' => '150',
3019 'hourly_limit' => '150',
3020 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3024 return api_format_data('hash', $type, ['hash' => $hash]);
3027 /// @TODO move to top of file or somewhere better
3028 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3031 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3033 * @param string $type Return type (atom, rss, xml, json)
3035 * @return array|string
3037 function api_help_test($type)
3039 if ($type == 'xml') {
3045 return api_format_data('ok', $type, ["ok" => $ok]);
3048 /// @TODO move to top of file or somewhere better
3049 api_register_func('api/help/test', 'api_help_test', false);
3052 * Returns all lists the user subscribes to.
3054 * @param string $type Return type (atom, rss, xml, json)
3056 * @return array|string
3057 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3059 function api_lists_list($type)
3062 /// @TODO $ret is not filled here?
3063 return api_format_data('lists', $type, ["lists_list" => $ret]);
3066 /// @TODO move to top of file or somewhere better
3067 api_register_func('api/lists/list', 'api_lists_list', true);
3068 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3071 * Returns all groups the user owns.
3073 * @param string $type Return type (atom, rss, xml, json)
3075 * @return array|string
3076 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3078 function api_lists_ownerships($type)
3082 if (api_user() === false) {
3083 throw new ForbiddenException();
3087 $user_info = api_get_user($a);
3088 $uid = $user_info['uid'];
3090 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3092 // loop through all groups
3094 foreach ($groups as $group) {
3095 if ($group['visible']) {
3101 'name' => $group['name'],
3102 'id' => intval($group['id']),
3103 'id_str' => (string) $group['id'],
3104 'user' => $user_info,
3108 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3111 /// @TODO move to top of file or somewhere better
3112 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3115 * Returns recent statuses from users in the specified group.
3117 * @param string $type Return type (atom, rss, xml, json)
3119 * @return array|string
3120 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3122 function api_lists_statuses($type)
3126 $user_info = api_get_user($a);
3127 if (api_user() === false || $user_info === false) {
3128 throw new ForbiddenException();
3131 unset($_REQUEST["user_id"]);
3132 unset($_GET["user_id"]);
3134 unset($_REQUEST["screen_name"]);
3135 unset($_GET["screen_name"]);
3137 if (empty($_REQUEST['list_id'])) {
3138 throw new BadRequestException('list_id not specified');
3142 $count = defaults($_REQUEST, 'count', 20);
3143 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
3147 $since_id = defaults($_REQUEST, 'since_id', 0);
3148 $max_id = defaults($_REQUEST, 'max_id', 0);
3149 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3150 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
3152 $start = $page * $count;
3154 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3155 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3158 $condition[0] .= " AND `item`.`id` <= ?";
3159 $condition[] = $max_id;
3161 if ($exclude_replies > 0) {
3162 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3164 if ($conversation_id > 0) {
3165 $condition[0] .= " AND `item`.`parent` = ?";
3166 $condition[] = $conversation_id;
3169 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3170 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3172 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3174 $data = ['status' => $items];
3179 $data = api_rss_extra($a, $data, $user_info);
3183 return api_format_data("statuses", $type, $data);
3186 /// @TODO move to top of file or somewhere better
3187 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3190 * Considers friends and followers lists to be private and won't return
3191 * anything if any user_id parameter is passed.
3193 * @brief Returns either the friends of the follower list
3195 * @param string $qtype Either "friends" or "followers"
3196 * @return boolean|array
3197 * @throws ForbiddenException
3199 function api_statuses_f($qtype)
3203 if (api_user() === false) {
3204 throw new ForbiddenException();
3208 $count = defaults($_GET, 'count', 20);
3209 $page = defaults($_GET, 'page', 1);
3213 $start = ($page - 1) * $count;
3215 $user_info = api_get_user($a);
3217 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3218 /* this is to stop Hotot to load friends multiple times
3219 * I'm not sure if I'm missing return something or
3220 * is a bug in hotot. Workaround, meantime
3224 return array('$users' => $ret);*/
3229 if ($qtype == 'friends') {
3230 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3231 } elseif ($qtype == 'followers') {
3232 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3235 // friends and followers only for self
3236 if ($user_info['self'] == 0) {
3237 $sql_extra = " AND false ";
3240 if ($qtype == 'blocks') {
3241 $sql_filter = 'AND `blocked` AND NOT `pending`';
3242 } elseif ($qtype == 'incoming') {
3243 $sql_filter = 'AND `pending`';
3245 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3263 foreach ($r as $cid) {
3264 $user = api_get_user($a, $cid['nurl']);
3265 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3266 unset($user["uid"]);
3267 unset($user["self"]);
3274 return ['user' => $ret];
3279 * Returns the user's friends.
3281 * @brief Returns the list of friends of the provided user
3283 * @deprecated By Twitter API in favor of friends/list
3285 * @param string $type Either "json" or "xml"
3286 * @return boolean|string|array
3288 function api_statuses_friends($type)
3290 $data = api_statuses_f("friends");
3291 if ($data === false) {
3294 return api_format_data("users", $type, $data);
3298 * Returns the user's followers.
3300 * @brief Returns the list of followers of the provided user
3302 * @deprecated By Twitter API in favor of friends/list
3304 * @param string $type Either "json" or "xml"
3305 * @return boolean|string|array
3307 function api_statuses_followers($type)
3309 $data = api_statuses_f("followers");
3310 if ($data === false) {
3313 return api_format_data("users", $type, $data);
3316 /// @TODO move to top of file or somewhere better
3317 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3318 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3321 * Returns the list of blocked users
3323 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3325 * @param string $type Either "json" or "xml"
3327 * @return boolean|string|array
3329 function api_blocks_list($type)
3331 $data = api_statuses_f('blocks');
3332 if ($data === false) {
3335 return api_format_data("users", $type, $data);
3338 /// @TODO move to top of file or somewhere better
3339 api_register_func('api/blocks/list', 'api_blocks_list', true);
3342 * Returns the list of pending users IDs
3344 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3346 * @param string $type Either "json" or "xml"
3348 * @return boolean|string|array
3350 function api_friendships_incoming($type)
3352 $data = api_statuses_f('incoming');
3353 if ($data === false) {
3358 foreach ($data['user'] as $user) {
3359 $ids[] = $user['id'];
3362 return api_format_data("ids", $type, ['id' => $ids]);
3365 /// @TODO move to top of file or somewhere better
3366 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3369 * Returns the instance's configuration information.
3371 * @param string $type Return type (atom, rss, xml, json)
3373 * @return array|string
3375 function api_statusnet_config($type)
3379 $name = Config::get('config', 'sitename');
3380 $server = $a->getHostName();
3381 $logo = System::baseUrl() . '/images/friendica-64.png';
3382 $email = Config::get('config', 'admin_email');
3383 $closed = intval(Config::get('config', 'register_policy')) === REGISTER_CLOSED ? 'true' : 'false';
3384 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3385 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3386 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3387 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3390 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3391 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3392 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3393 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3394 'shorturllength' => '30',
3396 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3397 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3398 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3399 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3404 return api_format_data('config', $type, ['config' => $config]);
3407 /// @TODO move to top of file or somewhere better
3408 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3409 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3413 * @param string $type Return type (atom, rss, xml, json)
3415 * @return array|string
3417 function api_statusnet_version($type)
3420 $fake_statusnet_version = "0.9.7";
3422 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3425 /// @TODO move to top of file or somewhere better
3426 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3427 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3431 * @param string $type Return type (atom, rss, xml, json)
3433 * @todo use api_format_data() to return data
3435 function api_ff_ids($type)
3438 throw new ForbiddenException();
3445 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3448 "SELECT `pcontact`.`id` FROM `contact`
3449 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3450 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3453 if (!DBA::isResult($r)) {
3458 foreach ($r as $rr) {
3459 if ($stringify_ids) {
3462 $ids[] = intval($rr['id']);
3466 return api_format_data("ids", $type, ['id' => $ids]);
3470 * Returns the ID of every user the user is following.
3472 * @param string $type Return type (atom, rss, xml, json)
3474 * @return array|string
3475 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3477 function api_friends_ids($type)
3479 return api_ff_ids($type);
3483 * Returns the ID of every user following the user.
3485 * @param string $type Return type (atom, rss, xml, json)
3487 * @return array|string
3488 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3490 function api_followers_ids($type)
3492 return api_ff_ids($type);
3495 /// @TODO move to top of file or somewhere better
3496 api_register_func('api/friends/ids', 'api_friends_ids', true);
3497 api_register_func('api/followers/ids', 'api_followers_ids', true);
3500 * Sends a new direct message.
3502 * @param string $type Return type (atom, rss, xml, json)
3504 * @return array|string
3505 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3507 function api_direct_messages_new($type)
3511 if (api_user() === false) {
3512 throw new ForbiddenException();
3515 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3519 $sender = api_get_user($a);
3522 if (!empty($_POST['screen_name'])) {
3524 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3526 DBA::escape($_POST['screen_name'])
3529 if (DBA::isResult($r)) {
3530 // Selecting the id by priority, friendica first
3531 api_best_nickname($r);
3533 $recipient = api_get_user($a, $r[0]['nurl']);
3536 $recipient = api_get_user($a, $_POST['user_id']);
3539 if (empty($recipient)) {
3540 throw new NotFoundException('Recipient not found');
3545 if (!empty($_REQUEST['replyto'])) {
3547 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3549 intval($_REQUEST['replyto'])
3551 $replyto = $r[0]['parent-uri'];
3552 $sub = $r[0]['title'];
3554 if (!empty($_REQUEST['title'])) {
3555 $sub = $_REQUEST['title'];
3557 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3561 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3564 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3565 $ret = api_format_messages($r[0], $recipient, $sender);
3567 $ret = ["error"=>$id];
3570 $data = ['direct_message'=>$ret];
3576 $data = api_rss_extra($a, $data, $sender);
3580 return api_format_data("direct-messages", $type, $data);
3583 /// @TODO move to top of file or somewhere better
3584 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3587 * Destroys a direct message.
3589 * @brief delete a direct_message from mail table through api
3591 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3592 * @return string|array
3593 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3595 function api_direct_messages_destroy($type)
3599 if (api_user() === false) {
3600 throw new ForbiddenException();
3604 $user_info = api_get_user($a);
3606 $id = defaults($_REQUEST, 'id', 0);
3608 $parenturi = defaults($_REQUEST, 'friendica_parenturi', "");
3609 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3610 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3612 $uid = $user_info['uid'];
3613 // error if no id or parenturi specified (for clients posting parent-uri as well)
3614 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3615 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3616 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3619 // BadRequestException if no id specified (for clients using Twitter API)
3621 throw new BadRequestException('Message id not specified');
3624 // add parent-uri to sql command if specified by calling app
3625 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3627 // get data of the specified message id
3629 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3634 // error message if specified id is not in database
3635 if (!DBA::isResult($r)) {
3636 if ($verbose == "true") {
3637 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3638 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3640 /// @todo BadRequestException ok for Twitter API clients?
3641 throw new BadRequestException('message id not in database');
3646 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3651 if ($verbose == "true") {
3654 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3655 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3657 $answer = ['result' => 'error', 'message' => 'unknown error'];
3658 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3661 /// @todo return JSON data like Twitter API not yet implemented
3664 /// @TODO move to top of file or somewhere better
3665 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3670 * @brief unfollow contact
3672 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3673 * @return string|array
3674 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3676 function api_friendships_destroy($type)
3680 if ($uid === false) {
3681 throw new ForbiddenException();
3684 $contact_id = defaults($_REQUEST, 'user_id');
3686 if (empty($contact_id)) {
3687 Logger::log("No user_id specified", Logger::DEBUG);
3688 throw new BadRequestException("no user_id specified");
3691 // Get Contact by given id
3692 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3694 if(!DBA::isResult($contact)) {
3695 Logger::log("No contact found for ID" . $contact_id, Logger::DEBUG);
3696 throw new NotFoundException("no contact found to given ID");
3699 $url = $contact["url"];
3701 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3702 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3703 Strings::normaliseLink($url), $url];
3704 $contact = DBA::selectFirst('contact', [], $condition);
3706 if (!DBA::isResult($contact)) {
3707 Logger::log("Not following Contact", Logger::DEBUG);
3708 throw new NotFoundException("Not following Contact");
3711 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3712 Logger::log("Not supported", Logger::DEBUG);
3713 throw new ExpectationFailedException("Not supported");
3716 $dissolve = ($contact['rel'] == Contact::SHARING);
3718 $owner = User::getOwnerDataById($uid);
3720 Contact::terminateFriendship($owner, $contact, $dissolve);
3723 Logger::log("No owner found", Logger::DEBUG);
3724 throw new NotFoundException("Error Processing Request");
3727 // Sharing-only contacts get deleted as there no relationship any more
3729 Contact::remove($contact['id']);
3731 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3734 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3735 unset($contact["uid"]);
3736 unset($contact["self"]);
3738 // Set screen_name since Twidere requests it
3739 $contact["screen_name"] = $contact["nick"];
3741 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3743 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3747 * @param string $type Return type (atom, rss, xml, json)
3748 * @param string $box
3749 * @param string $verbose
3751 * @return array|string
3753 function api_direct_messages_box($type, $box, $verbose)
3756 if (api_user() === false) {
3757 throw new ForbiddenException();
3760 $count = defaults($_GET, 'count', 20);
3761 $page = defaults($_REQUEST, 'page', 1) - 1;
3766 $since_id = defaults($_REQUEST, 'since_id', 0);
3767 $max_id = defaults($_REQUEST, 'max_id', 0);
3769 $user_id = defaults($_REQUEST, 'user_id', '');
3770 $screen_name = defaults($_REQUEST, 'screen_name', '');
3773 unset($_REQUEST["user_id"]);
3774 unset($_GET["user_id"]);
3776 unset($_REQUEST["screen_name"]);
3777 unset($_GET["screen_name"]);
3779 $user_info = api_get_user($a);
3780 if ($user_info === false) {
3781 throw new ForbiddenException();
3783 $profile_url = $user_info["url"];
3786 $start = $page * $count;
3791 if ($box=="sentbox") {
3792 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3793 } elseif ($box == "conversation") {
3794 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape(defaults($_GET, 'uri', '')) . "'";
3795 } elseif ($box == "all") {
3796 $sql_extra = "true";
3797 } elseif ($box == "inbox") {
3798 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3802 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3805 if ($user_id != "") {
3806 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3807 } elseif ($screen_name !="") {
3808 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3812 "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",
3818 if ($verbose == "true" && !DBA::isResult($r)) {
3819 $answer = ['result' => 'error', 'message' => 'no mails available'];
3820 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3824 foreach ($r as $item) {
3825 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3826 $recipient = $user_info;
3827 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3828 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3829 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3830 $sender = $user_info;
3833 if (isset($recipient) && isset($sender)) {
3834 $ret[] = api_format_messages($item, $recipient, $sender);
3839 $data = ['direct_message' => $ret];
3844 $data = api_rss_extra($a, $data, $user_info);
3848 return api_format_data("direct-messages", $type, $data);
3852 * Returns the most recent direct messages sent by the user.
3854 * @param string $type Return type (atom, rss, xml, json)
3856 * @return array|string
3857 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3859 function api_direct_messages_sentbox($type)
3861 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3862 return api_direct_messages_box($type, "sentbox", $verbose);
3866 * Returns the most recent direct messages sent to the user.
3868 * @param string $type Return type (atom, rss, xml, json)
3870 * @return array|string
3871 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3873 function api_direct_messages_inbox($type)
3875 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3876 return api_direct_messages_box($type, "inbox", $verbose);
3881 * @param string $type Return type (atom, rss, xml, json)
3883 * @return array|string
3885 function api_direct_messages_all($type)
3887 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3888 return api_direct_messages_box($type, "all", $verbose);
3893 * @param string $type Return type (atom, rss, xml, json)
3895 * @return array|string
3897 function api_direct_messages_conversation($type)
3899 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3900 return api_direct_messages_box($type, "conversation", $verbose);
3903 /// @TODO move to top of file or somewhere better
3904 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3905 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3906 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3907 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3910 * Returns an OAuth Request Token.
3912 * @see https://oauth.net/core/1.0/#auth_step1
3914 function api_oauth_request_token()
3916 $oauth1 = new FKOAuth1();
3918 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3919 } catch (Exception $e) {
3920 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3928 * Returns an OAuth Access Token.
3930 * @return array|string
3931 * @see https://oauth.net/core/1.0/#auth_step3
3933 function api_oauth_access_token()
3935 $oauth1 = new FKOAuth1();
3937 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3938 } catch (Exception $e) {
3939 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3946 /// @TODO move to top of file or somewhere better
3947 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3948 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3952 * @brief delete a complete photoalbum with all containing photos from database through api
3954 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3955 * @return string|array
3957 function api_fr_photoalbum_delete($type)
3959 if (api_user() === false) {
3960 throw new ForbiddenException();
3963 $album = defaults($_REQUEST, 'album', "");
3965 // we do not allow calls without album string
3967 throw new BadRequestException("no albumname specified");
3969 // check if album is existing
3971 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3975 if (!DBA::isResult($r)) {
3976 throw new BadRequestException("album not available");
3979 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3980 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3981 foreach ($r as $rr) {
3982 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
3983 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
3985 if (!DBA::isResult($photo_item)) {
3986 throw new InternalServerErrorException("problem with deleting items occured");
3988 Item::deleteForUser(['id' => $photo_item['id']], api_user());
3991 // now let's delete all photos from the album
3992 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
3994 // return success of deletion or error message
3996 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
3997 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
3999 throw new InternalServerErrorException("unknown error - deleting from database failed");
4004 * @brief update the name of the album for all photos of an album
4006 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4007 * @return string|array
4009 function api_fr_photoalbum_update($type)
4011 if (api_user() === false) {
4012 throw new ForbiddenException();
4015 $album = defaults($_REQUEST, 'album', "");
4016 $album_new = defaults($_REQUEST, 'album_new', "");
4018 // we do not allow calls without album string
4020 throw new BadRequestException("no albumname specified");
4022 if ($album_new == "") {
4023 throw new BadRequestException("no new albumname specified");
4025 // check if album is existing
4026 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4027 throw new BadRequestException("album not available");
4029 // now let's update all photos to the albumname
4030 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4032 // return success of updating or error message
4034 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4035 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4037 throw new InternalServerErrorException("unknown error - updating in database failed");
4043 * @brief list all photos of the authenticated user
4045 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4046 * @return string|array
4048 function api_fr_photos_list($type)
4050 if (api_user() === false) {
4051 throw new ForbiddenException();
4054 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4055 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4056 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4057 intval(local_user())
4060 'image/jpeg' => 'jpg',
4061 'image/png' => 'png',
4062 'image/gif' => 'gif'
4064 $data = ['photo'=>[]];
4065 if (DBA::isResult($r)) {
4066 foreach ($r as $rr) {
4068 $photo['id'] = $rr['resource-id'];
4069 $photo['album'] = $rr['album'];
4070 $photo['filename'] = $rr['filename'];
4071 $photo['type'] = $rr['type'];
4072 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4073 $photo['created'] = $rr['created'];
4074 $photo['edited'] = $rr['edited'];
4075 $photo['desc'] = $rr['desc'];
4077 if ($type == "xml") {
4078 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4080 $photo['thumb'] = $thumb;
4081 $data['photo'][] = $photo;
4085 return api_format_data("photos", $type, $data);
4089 * @brief upload a new photo or change an existing photo
4091 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4092 * @return string|array
4094 function api_fr_photo_create_update($type)
4096 if (api_user() === false) {
4097 throw new ForbiddenException();
4100 $photo_id = defaults($_REQUEST, 'photo_id', null);
4101 $desc = defaults($_REQUEST, 'desc', (array_key_exists('desc', $_REQUEST) ? "" : null)) ; // extra check necessary to distinguish between 'not provided' and 'empty string'
4102 $album = defaults($_REQUEST, 'album', null);
4103 $album_new = defaults($_REQUEST, 'album_new', null);
4104 $allow_cid = defaults($_REQUEST, 'allow_cid', (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4105 $deny_cid = defaults($_REQUEST, 'deny_cid' , (array_key_exists('deny_cid' , $_REQUEST) ? " " : null));
4106 $allow_gid = defaults($_REQUEST, 'allow_gid', (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4107 $deny_gid = defaults($_REQUEST, 'deny_gid' , (array_key_exists('deny_gid' , $_REQUEST) ? " " : null));
4108 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4110 // do several checks on input parameters
4111 // we do not allow calls without album string
4112 if ($album == null) {
4113 throw new BadRequestException("no albumname specified");
4115 // if photo_id == null --> we are uploading a new photo
4116 if ($photo_id == null) {
4119 // error if no media posted in create-mode
4120 if (empty($_FILES['media'])) {
4122 throw new BadRequestException("no media data submitted");
4125 // album_new will be ignored in create-mode
4130 // check if photo is existing in databasei
4131 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4132 throw new BadRequestException("photo not available");
4136 // checks on acl strings provided by clients
4137 $acl_input_error = false;
4138 $acl_input_error |= check_acl_input($allow_cid);
4139 $acl_input_error |= check_acl_input($deny_cid);
4140 $acl_input_error |= check_acl_input($allow_gid);
4141 $acl_input_error |= check_acl_input($deny_gid);
4142 if ($acl_input_error) {
4143 throw new BadRequestException("acl data invalid");
4145 // now let's upload the new media in create-mode
4146 if ($mode == "create") {
4147 $media = $_FILES['media'];
4148 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4150 // return success of updating or error message
4151 if (!is_null($data)) {
4152 return api_format_data("photo_create", $type, $data);
4154 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4158 // now let's do the changes in update-mode
4159 if ($mode == "update") {
4160 $updated_fields = [];
4162 if (!is_null($desc)) {
4163 $updated_fields['desc'] = $desc;
4166 if (!is_null($album_new)) {
4167 $updated_fields['album'] = $album_new;
4170 if (!is_null($allow_cid)) {
4171 $allow_cid = trim($allow_cid);
4172 $updated_fields['allow_cid'] = $allow_cid;
4175 if (!is_null($deny_cid)) {
4176 $deny_cid = trim($deny_cid);
4177 $updated_fields['deny_cid'] = $deny_cid;
4180 if (!is_null($allow_gid)) {
4181 $allow_gid = trim($allow_gid);
4182 $updated_fields['allow_gid'] = $allow_gid;
4185 if (!is_null($deny_gid)) {
4186 $deny_gid = trim($deny_gid);
4187 $updated_fields['deny_gid'] = $deny_gid;
4191 if (count($updated_fields) > 0) {
4192 $nothingtodo = false;
4193 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4195 $nothingtodo = true;
4198 if (!empty($_FILES['media'])) {
4199 $nothingtodo = false;
4200 $media = $_FILES['media'];
4201 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4202 if (!is_null($data)) {
4203 return api_format_data("photo_update", $type, $data);
4207 // return success of updating or error message
4209 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4210 return api_format_data("photo_update", $type, ['$result' => $answer]);
4213 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4214 return api_format_data("photo_update", $type, ['$result' => $answer]);
4216 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4219 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4223 * @brief delete a single photo from the database through api
4225 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4226 * @return string|array
4228 function api_fr_photo_delete($type)
4230 if (api_user() === false) {
4231 throw new ForbiddenException();
4234 $photo_id = defaults($_REQUEST, 'photo_id', null);
4236 // do several checks on input parameters
4237 // we do not allow calls without photo id
4238 if ($photo_id == null) {
4239 throw new BadRequestException("no photo_id specified");
4241 // check if photo is existing in database
4242 $r = Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()]);
4244 throw new BadRequestException("photo not available");
4246 // now we can perform on the deletion of the photo
4247 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4249 // return success of deletion or error message
4251 // retrieve the id of the parent element (the photo element)
4252 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4253 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4255 if (!DBA::isResult($photo_item)) {
4256 throw new InternalServerErrorException("problem with deleting items occured");
4258 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4259 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4260 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4262 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4263 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4265 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4271 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4273 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4274 * @return string|array
4276 function api_fr_photo_detail($type)
4278 if (api_user() === false) {
4279 throw new ForbiddenException();
4281 if (empty($_REQUEST['photo_id'])) {
4282 throw new BadRequestException("No photo id.");
4285 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4286 $photo_id = $_REQUEST['photo_id'];
4288 // prepare json/xml output with data from database for the requested photo
4289 $data = prepare_photo_data($type, $scale, $photo_id);
4291 return api_format_data("photo_detail", $type, $data);
4296 * Updates the user’s profile image.
4298 * @brief updates the profile image for the user (either a specified profile or the default profile)
4300 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4302 * @return string|array
4303 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4305 function api_account_update_profile_image($type)
4307 if (api_user() === false) {
4308 throw new ForbiddenException();
4311 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4313 // error if image data is missing
4314 if (empty($_FILES['image'])) {
4315 throw new BadRequestException("no media data submitted");
4318 // check if specified profile id is valid
4319 if ($profile_id != 0) {
4320 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4321 // error message if specified profile id is not in database
4322 if (!DBA::isResult($profile)) {
4323 throw new BadRequestException("profile_id not available");
4325 $is_default_profile = $profile['is-default'];
4327 $is_default_profile = 1;
4330 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4332 if (!empty($_FILES['image'])) {
4333 $media = $_FILES['image'];
4334 } elseif (!empty($_FILES['media'])) {
4335 $media = $_FILES['media'];
4337 // save new profile image
4338 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4341 if (is_array($media['type'])) {
4342 $filetype = $media['type'][0];
4344 $filetype = $media['type'];
4346 if ($filetype == "image/jpeg") {
4348 } elseif ($filetype == "image/png") {
4351 throw new InternalServerErrorException('Unsupported filetype');
4354 // change specified profile or all profiles to the new resource-id
4355 if ($is_default_profile) {
4356 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4357 Photo::update(['profile' => false], $condition);
4359 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype,
4360 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype];
4361 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4364 Contact::updateSelfFromUserID(api_user(), true);
4366 // Update global directory in background
4367 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4368 if ($url && strlen(Config::get('system', 'directory'))) {
4369 Worker::add(PRIORITY_LOW, "Directory", $url);
4372 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4374 // output for client
4376 return api_account_verify_credentials($type);
4378 // SaveMediaToDatabase failed for some reason
4379 throw new InternalServerErrorException("image upload failed");
4383 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4384 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4385 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4386 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4387 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4388 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4389 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4390 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4391 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4394 * Update user profile
4396 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4398 * @return array|string
4400 function api_account_update_profile($type)
4402 $local_user = api_user();
4403 $api_user = api_get_user(get_app());
4405 if (!empty($_POST['name'])) {
4406 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4407 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4408 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4409 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4412 if (isset($_POST['description'])) {
4413 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4414 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4415 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4418 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4419 // Update global directory in background
4420 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4421 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4424 return api_account_verify_credentials($type);
4427 /// @TODO move to top of file or somewhere better
4428 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4432 * @param string $acl_string
4434 function check_acl_input($acl_string)
4436 if ($acl_string == null || $acl_string == " ") {
4439 $contact_not_found = false;
4441 // split <x><y><z> into array of cid's
4442 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4444 // check for each cid if it is available on server
4445 $cid_array = $array[0];
4446 foreach ($cid_array as $cid) {
4447 $cid = str_replace("<", "", $cid);
4448 $cid = str_replace(">", "", $cid);
4449 $condition = ['id' => $cid, 'uid' => api_user()];
4450 $contact_not_found |= !DBA::exists('contact', $condition);
4452 return $contact_not_found;
4457 * @param string $mediatype
4458 * @param array $media
4459 * @param string $type
4460 * @param string $album
4461 * @param string $allow_cid
4462 * @param string $deny_cid
4463 * @param string $allow_gid
4464 * @param string $deny_gid
4465 * @param string $desc
4466 * @param integer $profile
4467 * @param boolean $visibility
4468 * @param string $photo_id
4470 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)
4478 if (is_array($media)) {
4479 if (is_array($media['tmp_name'])) {
4480 $src = $media['tmp_name'][0];
4482 $src = $media['tmp_name'];
4484 if (is_array($media['name'])) {
4485 $filename = basename($media['name'][0]);
4487 $filename = basename($media['name']);
4489 if (is_array($media['size'])) {
4490 $filesize = intval($media['size'][0]);
4492 $filesize = intval($media['size']);
4494 if (is_array($media['type'])) {
4495 $filetype = $media['type'][0];
4497 $filetype = $media['type'];
4501 if ($filetype == "") {
4502 $filetype=Image::guessType($filename);
4504 $imagedata = @getimagesize($src);
4506 $filetype = $imagedata['mime'];
4509 "File upload src: " . $src . " - filename: " . $filename .
4510 " - size: " . $filesize . " - type: " . $filetype,
4514 // check if there was a php upload error
4515 if ($filesize == 0 && $media['error'] == 1) {
4516 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4518 // check against max upload size within Friendica instance
4519 $maximagesize = Config::get('system', 'maximagesize');
4520 if ($maximagesize && ($filesize > $maximagesize)) {
4521 $formattedBytes = Strings::formatBytes($maximagesize);
4522 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4525 // create Photo instance with the data of the image
4526 $imagedata = @file_get_contents($src);
4527 $Image = new Image($imagedata, $filetype);
4528 if (!$Image->isValid()) {
4529 throw new InternalServerErrorException("unable to process image data");
4532 // check orientation of image
4533 $Image->orient($src);
4536 // check max length of images on server
4537 $max_length = Config::get('system', 'max_image_length');
4539 $max_length = MAX_IMAGE_LENGTH;
4541 if ($max_length > 0) {
4542 $Image->scaleDown($max_length);
4543 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4545 $width = $Image->getWidth();
4546 $height = $Image->getHeight();
4548 // create a new resource-id if not already provided
4549 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4551 if ($mediatype == "photo") {
4552 // upload normal image (scales 0, 1, 2)
4553 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4555 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4557 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4559 if ($width > 640 || $height > 640) {
4560 $Image->scaleDown(640);
4561 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4563 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4567 if ($width > 320 || $height > 320) {
4568 $Image->scaleDown(320);
4569 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4571 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4574 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4575 } elseif ($mediatype == "profileimage") {
4576 // upload profile image (scales 4, 5, 6)
4577 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4579 if ($width > 300 || $height > 300) {
4580 $Image->scaleDown(300);
4581 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4583 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4587 if ($width > 80 || $height > 80) {
4588 $Image->scaleDown(80);
4589 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4591 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4595 if ($width > 48 || $height > 48) {
4596 $Image->scaleDown(48);
4597 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4599 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4602 $Image->__destruct();
4603 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4606 if (isset($r) && $r) {
4607 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4608 if ($photo_id == null && $mediatype == "photo") {
4609 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4611 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4612 return prepare_photo_data($type, false, $hash);
4614 throw new InternalServerErrorException("image upload failed");
4620 * @param string $hash
4621 * @param string $allow_cid
4622 * @param string $deny_cid
4623 * @param string $allow_gid
4624 * @param string $deny_gid
4625 * @param string $filetype
4626 * @param boolean $visibility
4628 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4630 // get data about the api authenticated user
4631 $uri = Item::newURI(intval(api_user()));
4632 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4635 $arr['guid'] = System::createUUID();
4636 $arr['uid'] = intval(api_user());
4638 $arr['parent-uri'] = $uri;
4639 $arr['type'] = 'photo';
4641 $arr['resource-id'] = $hash;
4642 $arr['contact-id'] = $owner_record['id'];
4643 $arr['owner-name'] = $owner_record['name'];
4644 $arr['owner-link'] = $owner_record['url'];
4645 $arr['owner-avatar'] = $owner_record['thumb'];
4646 $arr['author-name'] = $owner_record['name'];
4647 $arr['author-link'] = $owner_record['url'];
4648 $arr['author-avatar'] = $owner_record['thumb'];
4650 $arr['allow_cid'] = $allow_cid;
4651 $arr['allow_gid'] = $allow_gid;
4652 $arr['deny_cid'] = $deny_cid;
4653 $arr['deny_gid'] = $deny_gid;
4654 $arr['visible'] = $visibility;
4658 'image/jpeg' => 'jpg',
4659 'image/png' => 'png',
4660 'image/gif' => 'gif'
4663 // adds link to the thumbnail scale photo
4664 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4665 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4668 // do the magic for storing the item in the database and trigger the federation to other contacts
4674 * @param string $type
4676 * @param string $photo_id
4680 function prepare_photo_data($type, $scale, $photo_id)
4683 $user_info = api_get_user($a);
4685 if ($user_info === false) {
4686 throw new ForbiddenException();
4689 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4690 $data_sql = ($scale === false ? "" : "data, ");
4692 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4693 // clients needs to convert this in their way for further processing
4695 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4696 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4697 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4698 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4700 intval(local_user()),
4701 DBA::escape($photo_id),
4706 'image/jpeg' => 'jpg',
4707 'image/png' => 'png',
4708 'image/gif' => 'gif'
4711 // prepare output data for photo
4712 if (DBA::isResult($r)) {
4713 $data = ['photo' => $r[0]];
4714 $data['photo']['id'] = $data['photo']['resource-id'];
4715 if ($scale !== false) {
4716 $data['photo']['data'] = base64_encode($data['photo']['data']);
4718 unset($data['photo']['datasize']); //needed only with scale param
4720 if ($type == "xml") {
4721 $data['photo']['links'] = [];
4722 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4723 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4725 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4728 $data['photo']['link'] = [];
4729 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4731 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4732 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4736 unset($data['photo']['resource-id']);
4737 unset($data['photo']['minscale']);
4738 unset($data['photo']['maxscale']);
4740 throw new NotFoundException();
4743 // retrieve item element for getting activities (like, dislike etc.) related to photo
4744 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4745 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4747 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4749 // retrieve comments on photo
4750 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4751 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4753 $statuses = Item::selectForUser(api_user(), [], $condition);
4755 // prepare output of comments
4756 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
4758 if ($type == "xml") {
4760 foreach ($commentData as $comment) {
4761 $comments[$k++ . ":comment"] = $comment;
4764 foreach ($commentData as $comment) {
4765 $comments[] = $comment;
4768 $data['photo']['friendica_comments'] = $comments;
4770 // include info if rights on photo and rights on item are mismatching
4771 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4772 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4773 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4774 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4775 $data['photo']['rights_mismatch'] = $rights_mismatch;
4782 * Similar as /mod/redir.php
4783 * redirect to 'url' after dfrn auth
4785 * Why this when there is mod/redir.php already?
4786 * This use api_user() and api_login()
4789 * c_url: url of remote contact to auth to
4790 * url: string, url to redirect after auth
4792 function api_friendica_remoteauth()
4794 $url = defaults($_GET, 'url', '');
4795 $c_url = defaults($_GET, 'c_url', '');
4797 if ($url === '' || $c_url === '') {
4798 throw new BadRequestException("Wrong parameters.");
4801 $c_url = Strings::normaliseLink($c_url);
4805 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4807 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
4808 throw new BadRequestException("Unknown contact");
4811 $cid = $contact['id'];
4813 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4815 if ($contact['duplex'] && $contact['issued-id']) {
4816 $orig_id = $contact['issued-id'];
4817 $dfrn_id = '1:' . $orig_id;
4819 if ($contact['duplex'] && $contact['dfrn-id']) {
4820 $orig_id = $contact['dfrn-id'];
4821 $dfrn_id = '0:' . $orig_id;
4824 $sec = Strings::getRandomHex();
4826 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4827 'sec' => $sec, 'expire' => time() + 45];
4828 DBA::insert('profile_check', $fields);
4830 Logger::log($contact['name'] . ' ' . $sec, Logger::DEBUG);
4831 $dest = ($url ? '&destination_url=' . $url : '');
4833 System::externalRedirect(
4834 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4835 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4836 . '&type=profile&sec=' . $sec . $dest
4839 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4842 * @brief Return the item shared, if the item contains only the [share] tag
4844 * @param array $item Sharer item
4845 * @return array|false Shared item or false if not a reshare
4847 function api_share_as_retweet(&$item)
4849 $body = trim($item["body"]);
4851 if (Diaspora::isReshare($body, false) === false) {
4852 if ($item['author-id'] == $item['owner-id']) {
4855 // Reshares from OStatus, ActivityPub and Twitter
4856 $reshared_item = $item;
4857 $reshared_item['owner-id'] = $reshared_item['author-id'];
4858 $reshared_item['owner-link'] = $reshared_item['author-link'];
4859 $reshared_item['owner-name'] = $reshared_item['author-name'];
4860 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
4861 return $reshared_item;
4865 /// @TODO "$1" should maybe mean '$1' ?
4866 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4868 * Skip if there is no shared message in there
4869 * we already checked this in diaspora::isReshare()
4870 * but better one more than one less...
4872 if (($body == $attributes) || empty($attributes)) {
4876 // build the fake reshared item
4877 $reshared_item = $item;
4880 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4881 if (!empty($matches[1])) {
4882 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4885 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4886 if (!empty($matches[1])) {
4887 $author = $matches[1];
4891 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4892 if (!empty($matches[1])) {
4893 $profile = $matches[1];
4896 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4897 if (!empty($matches[1])) {
4898 $profile = $matches[1];
4902 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4903 if (!empty($matches[1])) {
4904 $avatar = $matches[1];
4907 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4908 if (!empty($matches[1])) {
4909 $avatar = $matches[1];
4913 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4914 if (!empty($matches[1])) {
4915 $link = $matches[1];
4918 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4919 if (!empty($matches[1])) {
4920 $link = $matches[1];
4924 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4925 if (!empty($matches[1])) {
4926 $posted = $matches[1];
4929 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4930 if (!empty($matches[1])) {
4931 $posted = $matches[1];
4934 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4936 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4940 $reshared_item["body"] = $shared_body;
4941 $reshared_item["author-id"] = Contact::getIdForURL($profile, 0, true);
4942 $reshared_item["author-name"] = $author;
4943 $reshared_item["author-link"] = $profile;
4944 $reshared_item["author-avatar"] = $avatar;
4945 $reshared_item["plink"] = $link;
4946 $reshared_item["created"] = $posted;
4947 $reshared_item["edited"] = $posted;
4949 return $reshared_item;
4954 * @param string $profile
4956 * @return string|false
4957 * @todo remove trailing junk from profile url
4958 * @todo pump.io check has to check the website
4960 function api_get_nick($profile)
4965 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4966 DBA::escape(Strings::normaliseLink($profile))
4969 if (DBA::isResult($r)) {
4970 $nick = $r[0]["nick"];
4975 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4976 DBA::escape(Strings::normaliseLink($profile))
4979 if (DBA::isResult($r)) {
4980 $nick = $r[0]["nick"];
4985 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4986 if ($friendica != $profile) {
4992 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4993 if ($diaspora != $profile) {
4999 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5000 if ($twitter != $profile) {
5007 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5008 if ($StatusnetHost != $profile) {
5009 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5010 if ($StatusnetUser != $profile) {
5011 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5012 $user = json_decode($UserData);
5014 $nick = $user->screen_name;
5020 // To-Do: look at the page if its really a pumpio site
5021 //if (!$nick == "") {
5022 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5023 // if ($pumpio != $profile)
5025 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5038 * @param array $item
5042 function api_in_reply_to($item)
5046 $in_reply_to['status_id'] = null;
5047 $in_reply_to['user_id'] = null;
5048 $in_reply_to['status_id_str'] = null;
5049 $in_reply_to['user_id_str'] = null;
5050 $in_reply_to['screen_name'] = null;
5052 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5053 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5054 if (DBA::isResult($parent)) {
5055 $in_reply_to['status_id'] = intval($parent['id']);
5057 $in_reply_to['status_id'] = intval($item['parent']);
5060 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5062 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5063 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5065 if (DBA::isResult($parent)) {
5066 if ($parent['author-nick'] == "") {
5067 $parent['author-nick'] = api_get_nick($parent['author-link']);
5070 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5071 $in_reply_to['user_id'] = intval($parent['author-id']);
5072 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5075 // There seems to be situation, where both fields are identical:
5076 // https://github.com/friendica/friendica/issues/1010
5077 // This is a bugfix for that.
5078 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5079 Logger::log('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], Logger::DEBUG);
5080 $in_reply_to['status_id'] = null;
5081 $in_reply_to['user_id'] = null;
5082 $in_reply_to['status_id_str'] = null;
5083 $in_reply_to['user_id_str'] = null;
5084 $in_reply_to['screen_name'] = null;
5088 return $in_reply_to;
5093 * @param string $text
5097 function api_clean_plain_items($text)
5099 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
5101 $text = BBCode::cleanPictureLinks($text);
5102 $URLSearchString = "^\[\]";
5104 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5106 if ($include_entities == "true") {
5107 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5110 // Simplify "attachment" element
5111 $text = api_clean_attachments($text);
5117 * @brief Removes most sharing information for API text export
5119 * @param string $body The original body
5121 * @return string Cleaned body
5123 function api_clean_attachments($body)
5125 $data = BBCode::getAttachmentData($body);
5132 if (isset($data["text"])) {
5133 $body = $data["text"];
5135 if (($body == "") && isset($data["title"])) {
5136 $body = $data["title"];
5138 if (isset($data["url"])) {
5139 $body .= "\n".$data["url"];
5141 $body .= $data["after"];
5148 * @param array $contacts
5152 function api_best_nickname(&$contacts)
5156 if (count($contacts) == 0) {
5160 foreach ($contacts as $contact) {
5161 if ($contact["network"] == "") {
5162 $contact["network"] = "dfrn";
5163 $best_contact = [$contact];
5167 if (sizeof($best_contact) == 0) {
5168 foreach ($contacts as $contact) {
5169 if ($contact["network"] == "dfrn") {
5170 $best_contact = [$contact];
5175 if (sizeof($best_contact) == 0) {
5176 foreach ($contacts as $contact) {
5177 if ($contact["network"] == "dspr") {
5178 $best_contact = [$contact];
5183 if (sizeof($best_contact) == 0) {
5184 foreach ($contacts as $contact) {
5185 if ($contact["network"] == "stat") {
5186 $best_contact = [$contact];
5191 if (sizeof($best_contact) == 0) {
5192 foreach ($contacts as $contact) {
5193 if ($contact["network"] == "pump") {
5194 $best_contact = [$contact];
5199 if (sizeof($best_contact) == 0) {
5200 foreach ($contacts as $contact) {
5201 if ($contact["network"] == "twit") {
5202 $best_contact = [$contact];
5207 if (sizeof($best_contact) == 1) {
5208 $contacts = $best_contact;
5210 $contacts = [$contacts[0]];
5215 * Return all or a specified group of the user with the containing contacts.
5217 * @param string $type Return type (atom, rss, xml, json)
5219 * @return array|string
5221 function api_friendica_group_show($type)
5225 if (api_user() === false) {
5226 throw new ForbiddenException();
5230 $user_info = api_get_user($a);
5231 $gid = defaults($_REQUEST, 'gid', 0);
5232 $uid = $user_info['uid'];
5234 // get data of the specified group id or all groups if not specified
5237 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5241 // error message if specified gid is not in database
5242 if (!DBA::isResult($r)) {
5243 throw new BadRequestException("gid not available");
5247 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5252 // loop through all groups and retrieve all members for adding data in the user array
5254 foreach ($r as $rr) {
5255 $members = Contact::getByGroupId($rr['id']);
5258 if ($type == "xml") {
5259 $user_element = "users";
5261 foreach ($members as $member) {
5262 $user = api_get_user($a, $member['nurl']);
5263 $users[$k++.":user"] = $user;
5266 $user_element = "user";
5267 foreach ($members as $member) {
5268 $user = api_get_user($a, $member['nurl']);
5272 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5274 return api_format_data("groups", $type, ['group' => $grps]);
5276 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5280 * Delete the specified group of the user.
5282 * @param string $type Return type (atom, rss, xml, json)
5284 * @return array|string
5286 function api_friendica_group_delete($type)
5290 if (api_user() === false) {
5291 throw new ForbiddenException();
5295 $user_info = api_get_user($a);
5296 $gid = defaults($_REQUEST, 'gid', 0);
5297 $name = defaults($_REQUEST, 'name', "");
5298 $uid = $user_info['uid'];
5300 // error if no gid specified
5301 if ($gid == 0 || $name == "") {
5302 throw new BadRequestException('gid or name not specified');
5305 // get data of the specified group id
5307 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5311 // error message if specified gid is not in database
5312 if (!DBA::isResult($r)) {
5313 throw new BadRequestException('gid not available');
5316 // get data of the specified group id and group name
5318 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5323 // error message if specified gid is not in database
5324 if (!DBA::isResult($rname)) {
5325 throw new BadRequestException('wrong group name');
5329 $ret = Group::removeByName($uid, $name);
5332 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5333 return api_format_data("group_delete", $type, ['result' => $success]);
5335 throw new BadRequestException('other API error');
5338 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5343 * @param string $type Return type (atom, rss, xml, json)
5345 * @return array|string
5346 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5348 function api_lists_destroy($type)
5352 if (api_user() === false) {
5353 throw new ForbiddenException();
5357 $user_info = api_get_user($a);
5358 $gid = defaults($_REQUEST, 'list_id', 0);
5359 $uid = $user_info['uid'];
5361 // error if no gid specified
5363 throw new BadRequestException('gid not specified');
5366 // get data of the specified group id
5367 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5368 // error message if specified gid is not in database
5370 throw new BadRequestException('gid not available');
5373 if (Group::remove($gid)) {
5375 'name' => $group['name'],
5376 'id' => intval($gid),
5377 'id_str' => (string) $gid,
5378 'user' => $user_info
5381 return api_format_data("lists", $type, ['lists' => $list]);
5384 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5387 * Add a new group to the database.
5389 * @param string $name Group name
5390 * @param int $uid User ID
5391 * @param array $users List of users to add to the group
5395 function group_create($name, $uid, $users = [])
5397 // error if no name specified
5399 throw new BadRequestException('group name not specified');
5402 // get data of the specified group name
5404 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5408 // error message if specified group name already exists
5409 if (DBA::isResult($rname)) {
5410 throw new BadRequestException('group name already exists');
5413 // check if specified group name is a deleted group
5415 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5419 // error message if specified group name already exists
5420 if (DBA::isResult($rname)) {
5421 $reactivate_group = true;
5425 $ret = Group::create($uid, $name);
5427 $gid = Group::getIdByName($uid, $name);
5429 throw new BadRequestException('other API error');
5433 $erroraddinguser = false;
5435 foreach ($users as $user) {
5436 $cid = $user['cid'];
5437 // check if user really exists as contact
5439 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5443 if (count($contact)) {
5444 Group::addMember($gid, $cid);
5446 $erroraddinguser = true;
5447 $errorusers[] = $cid;
5451 // return success message incl. missing users in array
5452 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5454 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5458 * Create the specified group with the posted array of contacts.
5460 * @param string $type Return type (atom, rss, xml, json)
5462 * @return array|string
5464 function api_friendica_group_create($type)
5468 if (api_user() === false) {
5469 throw new ForbiddenException();
5473 $user_info = api_get_user($a);
5474 $name = defaults($_REQUEST, 'name', "");
5475 $uid = $user_info['uid'];
5476 $json = json_decode($_POST['json'], true);
5477 $users = $json['user'];
5479 $success = group_create($name, $uid, $users);
5481 return api_format_data("group_create", $type, ['result' => $success]);
5483 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5486 * Create a new group.
5488 * @param string $type Return type (atom, rss, xml, json)
5490 * @return array|string
5491 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5493 function api_lists_create($type)
5497 if (api_user() === false) {
5498 throw new ForbiddenException();
5502 $user_info = api_get_user($a);
5503 $name = defaults($_REQUEST, 'name', "");
5504 $uid = $user_info['uid'];
5506 $success = group_create($name, $uid);
5507 if ($success['success']) {
5509 'name' => $success['name'],
5510 'id' => intval($success['gid']),
5511 'id_str' => (string) $success['gid'],
5512 'user' => $user_info
5515 return api_format_data("lists", $type, ['lists'=>$grp]);
5518 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5521 * Update the specified group with the posted array of contacts.
5523 * @param string $type Return type (atom, rss, xml, json)
5525 * @return array|string
5527 function api_friendica_group_update($type)
5531 if (api_user() === false) {
5532 throw new ForbiddenException();
5536 $user_info = api_get_user($a);
5537 $uid = $user_info['uid'];
5538 $gid = defaults($_REQUEST, 'gid', 0);
5539 $name = defaults($_REQUEST, 'name', "");
5540 $json = json_decode($_POST['json'], true);
5541 $users = $json['user'];
5543 // error if no name specified
5545 throw new BadRequestException('group name not specified');
5548 // error if no gid specified
5550 throw new BadRequestException('gid not specified');
5554 $members = Contact::getByGroupId($gid);
5555 foreach ($members as $member) {
5556 $cid = $member['id'];
5557 foreach ($users as $user) {
5558 $found = ($user['cid'] == $cid ? true : false);
5560 if (!isset($found) || !$found) {
5561 Group::removeMemberByName($uid, $name, $cid);
5566 $erroraddinguser = false;
5568 foreach ($users as $user) {
5569 $cid = $user['cid'];
5570 // check if user really exists as contact
5572 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5577 if (count($contact)) {
5578 Group::addMember($gid, $cid);
5580 $erroraddinguser = true;
5581 $errorusers[] = $cid;
5585 // return success message incl. missing users in array
5586 $status = ($erroraddinguser ? "missing user" : "ok");
5587 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5588 return api_format_data("group_update", $type, ['result' => $success]);
5591 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5594 * Update information about a group.
5596 * @param string $type Return type (atom, rss, xml, json)
5598 * @return array|string
5599 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5601 function api_lists_update($type)
5605 if (api_user() === false) {
5606 throw new ForbiddenException();
5610 $user_info = api_get_user($a);
5611 $gid = defaults($_REQUEST, 'list_id', 0);
5612 $name = defaults($_REQUEST, 'name', "");
5613 $uid = $user_info['uid'];
5615 // error if no gid specified
5617 throw new BadRequestException('gid not specified');
5620 // get data of the specified group id
5621 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5622 // error message if specified gid is not in database
5624 throw new BadRequestException('gid not available');
5627 if (Group::update($gid, $name)) {
5630 'id' => intval($gid),
5631 'id_str' => (string) $gid,
5632 'user' => $user_info
5635 return api_format_data("lists", $type, ['lists' => $list]);
5639 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5643 * @param string $type Return type (atom, rss, xml, json)
5645 * @return array|string
5647 function api_friendica_activity($type)
5651 if (api_user() === false) {
5652 throw new ForbiddenException();
5654 $verb = strtolower($a->argv[3]);
5655 $verb = preg_replace("|\..*$|", "", $verb);
5657 $id = defaults($_REQUEST, 'id', 0);
5659 $res = Item::performLike($id, $verb);
5662 if ($type == "xml") {
5667 return api_format_data('ok', $type, ['ok' => $ok]);
5669 throw new BadRequestException('Error adding activity');
5673 /// @TODO move to top of file or somewhere better
5674 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5675 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5676 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5677 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5678 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5679 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5680 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5681 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5682 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5683 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5686 * @brief Returns notifications
5688 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5689 * @return string|array
5691 function api_friendica_notification($type)
5695 if (api_user() === false) {
5696 throw new ForbiddenException();
5699 throw new BadRequestException("Invalid argument count");
5701 $nm = new NotificationsManager();
5703 $notes = $nm->getAll([], "+seen -date", 50);
5705 if ($type == "xml") {
5707 if (!empty($notes)) {
5708 foreach ($notes as $note) {
5709 $xmlnotes[] = ["@attributes" => $note];
5715 return api_format_data("notes", $type, ['note' => $notes]);
5719 * POST request with 'id' param as notification id
5721 * @brief Set notification as seen and returns associated item (if possible)
5723 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5724 * @return string|array
5726 function api_friendica_notification_seen($type)
5729 $user_info = api_get_user($a);
5731 if (api_user() === false || $user_info === false) {
5732 throw new ForbiddenException();
5735 throw new BadRequestException("Invalid argument count");
5738 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5740 $nm = new NotificationsManager();
5741 $note = $nm->getByID($id);
5742 if (is_null($note)) {
5743 throw new BadRequestException("Invalid argument");
5746 $nm->setSeen($note);
5747 if ($note['otype']=='item') {
5748 // would be really better with an ItemsManager and $im->getByID() :-P
5749 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5750 if (DBA::isResult($item)) {
5751 // we found the item, return it to the user
5752 $ret = api_format_items([$item], $user_info, false, $type);
5753 $data = ['status' => $ret];
5754 return api_format_data("status", $type, $data);
5756 // the item can't be found, but we set the note as seen, so we count this as a success
5758 return api_format_data('result', $type, ['result' => "success"]);
5761 /// @TODO move to top of file or somewhere better
5762 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5763 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5766 * @brief update a direct_message to seen state
5768 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5769 * @return string|array (success result=ok, error result=error with error message)
5771 function api_friendica_direct_messages_setseen($type)
5774 if (api_user() === false) {
5775 throw new ForbiddenException();
5779 $user_info = api_get_user($a);
5780 $uid = $user_info['uid'];
5781 $id = defaults($_REQUEST, 'id', 0);
5783 // return error if id is zero
5785 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5786 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5789 // error message if specified id is not in database
5790 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5791 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5792 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5795 // update seen indicator
5796 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5800 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5801 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5803 $answer = ['result' => 'error', 'message' => 'unknown error'];
5804 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5808 /// @TODO move to top of file or somewhere better
5809 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5812 * @brief search for direct_messages containing a searchstring through api
5814 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5815 * @param string $box
5816 * @return string|array (success: success=true if found and search_result contains found messages,
5817 * success=false if nothing was found, search_result='nothing found',
5818 * error: result=error with error message)
5820 function api_friendica_direct_messages_search($type, $box = "")
5824 if (api_user() === false) {
5825 throw new ForbiddenException();
5829 $user_info = api_get_user($a);
5830 $searchstring = defaults($_REQUEST, 'searchstring', "");
5831 $uid = $user_info['uid'];
5833 // error if no searchstring specified
5834 if ($searchstring == "") {
5835 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5836 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5839 // get data for the specified searchstring
5841 "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",
5843 DBA::escape('%'.$searchstring.'%')
5846 $profile_url = $user_info["url"];
5848 // message if nothing was found
5849 if (!DBA::isResult($r)) {
5850 $success = ['success' => false, 'search_results' => 'problem with query'];
5851 } elseif (count($r) == 0) {
5852 $success = ['success' => false, 'search_results' => 'nothing found'];
5855 foreach ($r as $item) {
5856 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5857 $recipient = $user_info;
5858 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5859 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5860 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5861 $sender = $user_info;
5864 if (isset($recipient) && isset($sender)) {
5865 $ret[] = api_format_messages($item, $recipient, $sender);
5868 $success = ['success' => true, 'search_results' => $ret];
5871 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5874 /// @TODO move to top of file or somewhere better
5875 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5878 * @brief return data of all the profiles a user has to the client
5880 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5881 * @return string|array
5883 function api_friendica_profile_show($type)
5887 if (api_user() === false) {
5888 throw new ForbiddenException();
5892 $profile_id = defaults($_REQUEST, 'profile_id', 0);
5894 // retrieve general information about profiles for user
5895 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5896 $directory = Config::get('system', 'directory');
5898 // get data of the specified profile id or all profiles of the user if not specified
5899 if ($profile_id != 0) {
5901 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5906 // error message if specified gid is not in database
5907 if (!DBA::isResult($r)) {
5908 throw new BadRequestException("profile_id not available");
5912 "SELECT * FROM `profile` WHERE `uid` = %d",
5916 // loop through all returned profiles and retrieve data and users
5919 foreach ($r as $rr) {
5920 $profile = api_format_items_profiles($rr);
5922 // select all users from contact table, loop and prepare standard return for user data
5925 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5930 foreach ($nurls as $nurl) {
5931 $user = api_get_user($a, $nurl['nurl']);
5932 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5934 $profile['users'] = $users;
5936 // add prepared profile data to array for final return
5937 if ($type == "xml") {
5938 $profiles[$k++ . ":profile"] = $profile;
5940 $profiles[] = $profile;
5944 // return settings, authenticated user and profiles data
5945 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
5947 $result = ['multi_profiles' => $multi_profiles ? true : false,
5948 'global_dir' => $directory,
5949 'friendica_owner' => api_get_user($a, $self['nurl']),
5950 'profiles' => $profiles];
5951 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5953 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5956 * Returns a list of saved searches.
5958 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5960 * @param string $type Return format: json or xml
5962 * @return string|array
5964 function api_saved_searches_list($type)
5966 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
5969 while ($term = $terms->fetch()) {
5971 'created_at' => api_date(time()),
5972 'id' => intval($term['id']),
5973 'id_str' => $term['id'],
5974 'name' => $term['term'],
5976 'query' => $term['term']
5982 return api_format_data("terms", $type, ['terms' => $result]);
5985 /// @TODO move to top of file or somewhere better
5986 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5989 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
5991 * @brief Number of comments
5993 * @param object $data [Status, Status]
5997 function bindComments(&$data){
5998 if(count($data) == 0) return;
6002 foreach($data as $item){ $ids[] = $item['id']; }
6004 $sql = "SELECT `parent`,COUNT(*) as comments FROM `item`
6005 WHERE `parent` IN ( %s ) AND `deleted` = %d AND `gravity`= %d GROUP BY `parent`";
6006 $result = q($sql, implode(",", $ids), 0, GRAVITY_COMMENT);
6008 foreach($result as $records) {
6009 $comments[$records['parent']] = $records['comments'];
6012 foreach($data as $idx => $item){
6014 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6019 @TODO Maybe open to implement?
6021 [pagename] => api/1.1/statuses/lookup.json
6022 [id] => 605138389168451584
6023 [include_cards] => true
6024 [cards_platform] => Android-12
6025 [include_entities] => true
6026 [include_my_retweet] => 1
6028 [include_reply_count] => true
6029 [include_descendent_reply_count] => true
6033 Not implemented by now:
6034 statuses/retweets_of_me
6039 account/update_location
6040 account/update_profile_background_image
6043 friendica/profile/update
6044 friendica/profile/create
6045 friendica/profile/delete
6047 Not implemented in status.net:
6048 statuses/retweeted_to_me
6049 statuses/retweeted_by_me
6050 direct_messages/destroy
6052 account/update_delivery_device
6053 notifications/follow