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 'include/conversation.php';
50 require_once 'mod/share.php';
51 require_once 'mod/item.php';
52 require_once 'mod/wall_upload.php';
54 define('API_METHOD_ANY', '*');
55 define('API_METHOD_GET', 'GET');
56 define('API_METHOD_POST', 'POST,PUT');
57 define('API_METHOD_DELETE', 'POST,DELETE');
63 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
64 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
65 * into a page, and visitors will post something without noticing it).
67 * @brief Auth API user
71 if (x($_SESSION, 'allow_api')) {
79 * Clients can send 'source' parameter to be show in post metadata
80 * as "sent via <source>".
81 * Some clients doesn't send a source param, we support ones we know
84 * @brief Get source name from API client
87 * Client source name, default to "api" if unset/unknown
91 if (requestdata('source')) {
92 return requestdata('source');
95 // Support for known clients that doesn't send a source name
96 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
97 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
101 Logger::log("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], Logger::DEBUG);
103 Logger::log("Empty user-agent", Logger::DEBUG);
110 * @brief Format date for API
112 * @param string $str Source date, as UTC
113 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
115 function api_date($str)
117 // Wed May 23 06:01:13 +0000 2007
118 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
122 * Register a function to be the endpoint for defined API path.
124 * @brief Register API endpoint
126 * @param string $path API URL path, relative to System::baseUrl()
127 * @param string $func Function name to call on path request
128 * @param bool $auth API need logged user
129 * @param string $method HTTP method reqiured to call this endpoint.
130 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
131 * Default to API_METHOD_ANY
133 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
143 // Workaround for hotot
144 $path = str_replace("api/", "api/1.1/", $path);
154 * Log in user via OAuth1 or Simple HTTP Auth.
155 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
157 * @brief Login API user
159 * @param object $a App
160 * @hook 'authenticate'
162 * 'username' => username from login form
163 * 'password' => password from login form
164 * 'authenticated' => return status,
165 * 'user_record' => return authenticated user record
167 * array $user logged user record
169 function api_login(App $a)
171 $oauth1 = new FKOAuth1();
174 $request = OAuthRequest::from_request();
175 list($consumer, $token) = $oauth1->verify_request($request);
176 if (!is_null($token)) {
177 $oauth1->loginUser($token->uid);
178 Addon::callHooks('logged_in', $a->user);
181 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
182 var_dump($consumer, $token);
184 } catch (Exception $e) {
188 // workaround for HTTP-auth in CGI mode
189 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
190 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
191 if (strlen($userpass)) {
192 list($name, $password) = explode(':', $userpass);
193 $_SERVER['PHP_AUTH_USER'] = $name;
194 $_SERVER['PHP_AUTH_PW'] = $password;
198 if (!x($_SERVER, 'PHP_AUTH_USER')) {
199 Logger::log('API_login: ' . print_r($_SERVER, true), Logger::DEBUG);
200 header('WWW-Authenticate: Basic realm="Friendica"');
201 throw new UnauthorizedException("This API requires login");
204 $user = defaults($_SERVER, 'PHP_AUTH_USER', '');
205 $password = defaults($_SERVER, 'PHP_AUTH_PW', '');
207 // allow "user@server" login (but ignore 'server' part)
208 $at = strstr($user, "@", true);
213 // next code from mod/auth.php. needs better solution
217 'username' => trim($user),
218 'password' => trim($password),
219 'authenticated' => 0,
220 'user_record' => null,
224 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
225 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
226 * and later addons should not interfere with an earlier one that succeeded.
228 Addon::callHooks('authenticate', $addon_auth);
230 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
231 $record = $addon_auth['user_record'];
233 $user_id = User::authenticate(trim($user), trim($password));
234 if ($user_id !== false) {
235 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
239 if (!DBA::isResult($record)) {
240 Logger::log('API_login failure: ' . print_r($_SERVER, true), Logger::DEBUG);
241 header('WWW-Authenticate: Basic realm="Friendica"');
242 //header('HTTP/1.0 401 Unauthorized');
243 //die('This api requires login');
244 throw new UnauthorizedException("This API requires login");
247 Authentication::setAuthenticatedSessionForUser($record);
249 $_SESSION["allow_api"] = true;
251 Addon::callHooks('logged_in', $a->user);
255 * API endpoints can define which HTTP method to accept when called.
256 * This function check the current HTTP method agains endpoint
259 * @brief Check HTTP method of called API
261 * @param string $method Required methods, uppercase, separated by comma
264 function api_check_method($method)
266 if ($method == "*") {
269 return (stripos($method, defaults($_SERVER, 'REQUEST_METHOD', 'GET')) !== false);
273 * Authenticate user, call registered API function, set HTTP headers
275 * @brief Main API entry point
277 * @param object $a App
278 * @return string|array API call result
280 function api_call(App $a)
282 global $API, $called_api;
285 if (strpos($a->query_string, ".xml") > 0) {
288 if (strpos($a->query_string, ".json") > 0) {
291 if (strpos($a->query_string, ".rss") > 0) {
294 if (strpos($a->query_string, ".atom") > 0) {
299 foreach ($API as $p => $info) {
300 if (strpos($a->query_string, $p) === 0) {
301 if (!api_check_method($info['method'])) {
302 throw new MethodNotAllowedException();
305 $called_api = explode("/", $p);
306 //unset($_SERVER['PHP_AUTH_USER']);
308 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
309 if (!empty($info['auth']) && api_user() === false) {
313 Logger::log('API call for ' . $a->user['username'] . ': ' . $a->query_string);
314 Logger::log('API parameters: ' . print_r($_REQUEST, true));
316 $stamp = microtime(true);
317 $return = call_user_func($info['func'], $type);
318 $duration = (float) (microtime(true) - $stamp);
319 Logger::log("API call duration: " . round($duration, 2) . "\t" . $a->query_string, Logger::DEBUG);
321 if (Config::get("system", "profiler")) {
322 $duration = microtime(true)-$a->performance["start"];
324 /// @TODO round() really everywhere?
326 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
327 "Database: %s/%s, Cache %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
328 round($a->performance["database"] - $a->performance["database_write"], 3),
329 round($a->performance["database_write"], 3),
330 round($a->performance["cache"], 3),
331 round($a->performance["cache_write"], 3),
332 round($a->performance["network"], 2),
333 round($a->performance["file"], 2),
334 round($duration - ($a->performance["database"]
335 + $a->performance["cache"] + $a->performance["cache_write"]
336 + $a->performance["network"] + $a->performance["file"]), 2),
342 if (Config::get("rendertime", "callstack")) {
343 $o = "Database Read:\n";
344 foreach ($a->callstack["database"] as $func => $time) {
345 $time = round($time, 3);
347 $o .= $func . ": " . $time . "\n";
350 $o .= "\nDatabase Write:\n";
351 foreach ($a->callstack["database_write"] as $func => $time) {
352 $time = round($time, 3);
354 $o .= $func . ": " . $time . "\n";
358 $o = "Cache Read:\n";
359 foreach ($a->callstack["cache"] as $func => $time) {
360 $time = round($time, 3);
362 $o .= $func . ": " . $time . "\n";
365 $o .= "\nCache Write:\n";
366 foreach ($a->callstack["cache_write"] as $func => $time) {
367 $time = round($time, 3);
369 $o .= $func . ": " . $time . "\n";
373 $o .= "\nNetwork:\n";
374 foreach ($a->callstack["network"] as $func => $time) {
375 $time = round($time, 3);
377 $o .= $func . ": " . $time . "\n";
380 Logger::log($o, Logger::DEBUG);
384 if (false === $return) {
386 * api function returned false withour throw an
387 * exception. This should not happend, throw a 500
389 throw new InternalServerErrorException();
394 header("Content-Type: text/xml");
397 header("Content-Type: application/json");
398 $json = json_encode(end($return));
399 if (x($_GET, 'callback')) {
400 $json = $_GET['callback'] . "(" . $json . ")";
405 header("Content-Type: application/rss+xml");
406 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
409 header("Content-Type: application/atom+xml");
410 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
417 Logger::log('API call not implemented: ' . $a->query_string);
418 throw new NotImplementedException();
419 } catch (HTTPException $e) {
420 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
421 return api_error($type, $e);
426 * @brief Format API error string
428 * @param string $type Return type (xml, json, rss, as)
429 * @param object $e HTTPException Error object
430 * @return string|array error message formatted as $type
432 function api_error($type, $e)
436 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
437 /// @TODO: https://dev.twitter.com/overview/api/response-codes
439 $error = ["error" => $error,
440 "code" => $e->httpcode . " " . $e->httpdesc,
441 "request" => $a->query_string];
443 $return = api_format_data('status', $type, ['status' => $error]);
447 header("Content-Type: text/xml");
450 header("Content-Type: application/json");
451 $return = json_encode($return);
454 header("Content-Type: application/rss+xml");
457 header("Content-Type: application/atom+xml");
465 * @brief Set values for RSS template
468 * @param array $arr Array to be passed to template
469 * @param array $user_info User info
471 * @todo find proper type-hints
473 function api_rss_extra(App $a, $arr, $user_info)
475 if (is_null($user_info)) {
476 $user_info = api_get_user($a);
479 $arr['$user'] = $user_info;
481 'alternate' => $user_info['url'],
482 'self' => System::baseUrl() . "/" . $a->query_string,
483 'base' => System::baseUrl(),
484 'updated' => api_date(null),
485 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
486 'language' => $user_info['lang'],
487 'logo' => System::baseUrl() . "/images/friendica-32.png",
495 * @brief Unique contact to contact url.
497 * @param int $id Contact id
498 * @return bool|string
499 * Contact url or False if contact id is unknown
501 function api_unique_id_to_nurl($id)
503 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
505 if (DBA::isResult($r)) {
513 * @brief Get user info array.
515 * @param object $a App
516 * @param int|string $contact_id Contact ID or URL
518 function api_get_user(App $a, $contact_id = null)
526 Logger::log("api_get_user: Fetching user data for user ".$contact_id, Logger::DEBUG);
528 // Searching for contact URL
529 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
530 $user = DBA::escape(Strings::normaliseLink($contact_id));
532 $extra_query = "AND `contact`.`nurl` = '%s' ";
533 if (api_user() !== false) {
534 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
538 // Searching for contact id with uid = 0
539 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
540 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
543 throw new BadRequestException("User ID ".$contact_id." not found.");
547 $extra_query = "AND `contact`.`nurl` = '%s' ";
548 if (api_user() !== false) {
549 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
553 if (is_null($user) && x($_GET, 'user_id')) {
554 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
557 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
561 $extra_query = "AND `contact`.`nurl` = '%s' ";
562 if (api_user() !== false) {
563 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
566 if (is_null($user) && x($_GET, 'screen_name')) {
567 $user = DBA::escape($_GET['screen_name']);
568 $extra_query = "AND `contact`.`nick` = '%s' ";
569 if (api_user() !== false) {
570 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
574 if (is_null($user) && x($_GET, 'profileurl')) {
575 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
576 $extra_query = "AND `contact`.`nurl` = '%s' ";
577 if (api_user() !== false) {
578 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
582 // $called_api is the API path exploded on / and is expected to have at least 2 elements
583 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
584 $argid = count($called_api);
585 if (!empty($a->argv[$argid])) {
586 $data = explode(".", $a->argv[$argid]);
587 if (count($data) > 1) {
588 list($user, $null) = $data;
591 if (is_numeric($user)) {
592 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
596 $extra_query = "AND `contact`.`nurl` = '%s' ";
597 if (api_user() !== false) {
598 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
602 $user = DBA::escape($user);
603 $extra_query = "AND `contact`.`nick` = '%s' ";
604 if (api_user() !== false) {
605 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
610 Logger::log("api_get_user: user ".$user, Logger::DEBUG);
613 if (api_user() === false) {
617 $user = $_SESSION['uid'];
618 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
622 Logger::log('api_user: ' . $extra_query . ', user: ' . $user);
626 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
632 // Selecting the id by priority, friendica first
633 if (is_array($uinfo)) {
634 api_best_nickname($uinfo);
637 // if the contact wasn't found, fetch it from the contacts with uid = 0
638 if (!DBA::isResult($uinfo)) {
640 throw new BadRequestException("User not found.");
643 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
645 if (DBA::isResult($contact)) {
646 $network_name = ContactSelector::networkToName($contact['network'], $contact['url']);
648 // If no nick where given, extract it from the address
649 if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
650 $contact['nick'] = api_get_nick($contact["url"]);
654 'id' => $contact["id"],
655 'id_str' => (string) $contact["id"],
656 'name' => $contact["name"],
657 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
658 'location' => ($contact["location"] != "") ? $contact["location"] : $network_name,
659 'description' => $contact["about"],
660 'profile_image_url' => $contact["micro"],
661 'profile_image_url_https' => $contact["micro"],
662 'profile_image_url_profile_size' => $contact["thumb"],
663 'profile_image_url_large' => $contact["photo"],
664 'url' => $contact["url"],
665 'protected' => false,
666 'followers_count' => 0,
667 'friends_count' => 0,
669 'created_at' => api_date($contact["created"]),
670 'favourites_count' => 0,
672 'time_zone' => 'UTC',
673 'geo_enabled' => false,
675 'statuses_count' => 0,
677 'contributors_enabled' => false,
678 'is_translator' => false,
679 'is_translation_enabled' => false,
680 'following' => false,
681 'follow_request_sent' => false,
682 'statusnet_blocking' => false,
683 'notifications' => false,
684 'statusnet_profile_url' => $contact["url"],
686 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
687 'pid' => Contact::getIdForURL($contact["url"], 0, true),
689 'network' => $contact["network"],
694 throw new BadRequestException("User ".$url." not found.");
698 if ($uinfo[0]['self']) {
699 if ($uinfo[0]['network'] == "") {
700 $uinfo[0]['network'] = Protocol::DFRN;
703 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
704 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
711 // Add a nick if it isn't present there
712 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
713 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
716 $network_name = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
718 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
720 if (!empty($profile['about'])) {
721 $description = $profile['about'];
723 $description = $uinfo[0]["about"];
726 if (!empty($usr['default-location'])) {
727 $location = $usr['default-location'];
728 } elseif (!empty($uinfo[0]["location"])) {
729 $location = $uinfo[0]["location"];
731 $location = $network_name;
735 'id' => intval($pcontact_id),
736 'id_str' => (string) intval($pcontact_id),
737 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
738 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
739 'location' => $location,
740 'description' => $description,
741 'profile_image_url' => $uinfo[0]['micro'],
742 'profile_image_url_https' => $uinfo[0]['micro'],
743 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
744 'profile_image_url_large' => $uinfo[0]["photo"],
745 'url' => $uinfo[0]['url'],
746 'protected' => false,
747 'followers_count' => intval($countfollowers),
748 'friends_count' => intval($countfriends),
750 'created_at' => api_date($uinfo[0]['created']),
751 'favourites_count' => intval($starred),
753 'time_zone' => 'UTC',
754 'geo_enabled' => false,
756 'statuses_count' => intval($countitems),
758 'contributors_enabled' => false,
759 'is_translator' => false,
760 'is_translation_enabled' => false,
761 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
762 'follow_request_sent' => false,
763 'statusnet_blocking' => false,
764 'notifications' => false,
766 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
767 'statusnet_profile_url' => $uinfo[0]['url'],
768 'uid' => intval($uinfo[0]['uid']),
769 'cid' => intval($uinfo[0]['cid']),
770 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
771 'self' => $uinfo[0]['self'],
772 'network' => $uinfo[0]['network'],
775 // If this is a local user and it uses Frio, we can get its color preferences.
777 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
778 if ($theme_info['theme'] === 'frio') {
779 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
781 if ($schema && ($schema != '---')) {
782 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
783 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
784 require_once $schemefile;
787 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
788 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
789 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
791 if (empty($nav_bg)) {
794 if (empty($link_color)) {
795 $link_color = "#6fdbe8";
797 if (empty($bgcolor)) {
798 $bgcolor = "#ededed";
801 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
802 $ret['profile_link_color'] = str_replace('#', '', $link_color);
803 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
811 * @brief return api-formatted array for item's author and owner
813 * @param object $a App
814 * @param array $item item from db
815 * @return array(array:author, array:owner)
817 function api_item_get_user(App $a, $item)
819 $status_user = api_get_user($a, defaults($item, 'author-id', null));
821 $status_user["protected"] = defaults($item, 'private', 0);
823 if (defaults($item, 'thr-parent', '') == defaults($item, 'uri', '')) {
824 $owner_user = api_get_user($a, defaults($item, 'owner-id', null));
826 $owner_user = $status_user;
829 return ([$status_user, $owner_user]);
833 * @brief walks recursively through an array with the possibility to change value and key
835 * @param array $array The array to walk through
836 * @param string $callback The callback function
838 * @return array the transformed array
840 function api_walk_recursive(array &$array, callable $callback)
844 foreach ($array as $k => $v) {
846 if ($callback($v, $k)) {
847 $new_array[$k] = api_walk_recursive($v, $callback);
850 if ($callback($v, $k)) {
861 * @brief Callback function to transform the array in an array that can be transformed in a XML file
863 * @param mixed $item Array item value
864 * @param string $key Array key
866 * @return boolean Should the array item be deleted?
868 function api_reformat_xml(&$item, &$key)
870 if (is_bool($item)) {
871 $item = ($item ? "true" : "false");
874 if (substr($key, 0, 10) == "statusnet_") {
875 $key = "statusnet:".substr($key, 10);
876 } elseif (substr($key, 0, 10) == "friendica_") {
877 $key = "friendica:".substr($key, 10);
879 /// @TODO old-lost code?
881 // $key = "default:".$key;
887 * @brief Creates the XML from a JSON style array
889 * @param array $data JSON style array
890 * @param string $root_element Name of the root element
892 * @return string The XML data
894 function api_create_xml(array $data, $root_element)
896 $childname = key($data);
897 $data2 = array_pop($data);
899 $namespaces = ["" => "http://api.twitter.com",
900 "statusnet" => "http://status.net/schema/api/1/",
901 "friendica" => "http://friendi.ca/schema/api/1/",
902 "georss" => "http://www.georss.org/georss"];
904 /// @todo Auto detection of needed namespaces
905 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
909 if (is_array($data2)) {
911 api_walk_recursive($data2, "api_reformat_xml");
917 foreach ($data2 as $item) {
918 $data4[$i++ . ":" . $childname] = $item;
925 $data3 = [$root_element => $data2];
927 $ret = XML::fromArray($data3, $xml, false, $namespaces);
932 * @brief Formats the data according to the data type
934 * @param string $root_element Name of the root element
935 * @param string $type Return type (atom, rss, xml, json)
936 * @param array $data JSON style array
938 * @return (string|array) XML data or JSON data
940 function api_format_data($root_element, $type, $data)
946 $ret = api_create_xml($data, $root_element);
962 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
963 * returns a 401 status code and an error message if not.
964 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
966 * @param string $type Return type (atom, rss, xml, json)
968 function api_account_verify_credentials($type)
973 if (api_user() === false) {
974 throw new ForbiddenException();
977 unset($_REQUEST["user_id"]);
978 unset($_GET["user_id"]);
980 unset($_REQUEST["screen_name"]);
981 unset($_GET["screen_name"]);
983 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
985 $user_info = api_get_user($a);
987 // "verified" isn't used here in the standard
988 unset($user_info["verified"]);
990 // - Adding last status
992 $user_info["status"] = api_status_show("raw");
993 if (!count($user_info["status"])) {
994 unset($user_info["status"]);
996 unset($user_info["status"]["user"]);
1000 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1001 unset($user_info["uid"]);
1002 unset($user_info["self"]);
1004 return api_format_data("user", $type, ['user' => $user_info]);
1007 /// @TODO move to top of file or somewhere better
1008 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1011 * Get data from $_POST or $_GET
1015 function requestdata($k)
1017 if (x($_POST, $k)) {
1027 * Deprecated function to upload media.
1029 * @param string $type Return type (atom, rss, xml, json)
1031 * @return array|string
1033 function api_statuses_mediap($type)
1037 if (api_user() === false) {
1038 Logger::log('api_statuses_update: no user');
1039 throw new ForbiddenException();
1041 $user_info = api_get_user($a);
1043 $_REQUEST['profile_uid'] = api_user();
1044 $_REQUEST['api_source'] = true;
1045 $txt = requestdata('status');
1046 /// @TODO old-lost code?
1047 //$txt = urldecode(requestdata('status'));
1049 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1050 $txt = HTML::toBBCodeVideo($txt);
1051 $config = HTMLPurifier_Config::createDefault();
1052 $config->set('Cache.DefinitionImpl', null);
1053 $purifier = new HTMLPurifier($config);
1054 $txt = $purifier->purify($txt);
1056 $txt = HTML::toBBCode($txt);
1058 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1060 $picture = wall_upload_post($a, false);
1062 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1063 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1064 $item_id = item_post($a);
1066 // output the post that we just posted.
1067 return api_status_show($type, $item_id);
1070 /// @TODO move this to top of file or somewhere better!
1071 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1074 * Updates the user’s current status.
1076 * @param string $type Return type (atom, rss, xml, json)
1078 * @return array|string
1079 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1081 function api_statuses_update($type)
1085 if (api_user() === false) {
1086 Logger::log('api_statuses_update: no user');
1087 throw new ForbiddenException();
1092 // convert $_POST array items to the form we use for web posts.
1093 if (requestdata('htmlstatus')) {
1094 $txt = requestdata('htmlstatus');
1095 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1096 $txt = HTML::toBBCodeVideo($txt);
1098 $config = HTMLPurifier_Config::createDefault();
1099 $config->set('Cache.DefinitionImpl', null);
1101 $purifier = new HTMLPurifier($config);
1102 $txt = $purifier->purify($txt);
1104 $_REQUEST['body'] = HTML::toBBCode($txt);
1107 $_REQUEST['body'] = requestdata('status');
1110 $_REQUEST['title'] = requestdata('title');
1112 $parent = requestdata('in_reply_to_status_id');
1114 // Twidere sends "-1" if it is no reply ...
1115 if ($parent == -1) {
1119 if (ctype_digit($parent)) {
1120 $_REQUEST['parent'] = $parent;
1122 $_REQUEST['parent_uri'] = $parent;
1125 if (requestdata('lat') && requestdata('long')) {
1126 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1128 $_REQUEST['profile_uid'] = api_user();
1131 // Check for throttling (maximum posts per day, week and month)
1132 $throttle_day = Config::get('system', 'throttle_limit_day');
1133 if ($throttle_day > 0) {
1134 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1136 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1137 $posts_day = DBA::count('thread', $condition);
1139 if ($posts_day > $throttle_day) {
1140 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1141 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1142 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));
1146 $throttle_week = Config::get('system', 'throttle_limit_week');
1147 if ($throttle_week > 0) {
1148 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1150 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1151 $posts_week = DBA::count('thread', $condition);
1153 if ($posts_week > $throttle_week) {
1154 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1155 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1156 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));
1160 $throttle_month = Config::get('system', 'throttle_limit_month');
1161 if ($throttle_month > 0) {
1162 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1164 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1165 $posts_month = DBA::count('thread', $condition);
1167 if ($posts_month > $throttle_month) {
1168 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1169 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1170 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));
1175 if (x($_FILES, 'media')) {
1176 // upload the image if we have one
1177 $picture = wall_upload_post($a, false);
1178 if (is_array($picture)) {
1179 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1183 // To-Do: Multiple IDs
1184 if (requestdata('media_ids')) {
1186 "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",
1187 intval(requestdata('media_ids')),
1190 if (DBA::isResult($r)) {
1191 $phototypes = Image::supportedTypes();
1192 $ext = $phototypes[$r[0]['type']];
1193 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1194 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1198 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1200 $_REQUEST['api_source'] = true;
1202 if (!x($_REQUEST, "source")) {
1203 $_REQUEST["source"] = api_source();
1206 // call out normal post function
1207 $item_id = item_post($a);
1209 // output the post that we just posted.
1210 return api_status_show($type, $item_id);
1213 /// @TODO move to top of file or somewhere better
1214 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1215 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1218 * Uploads an image to Friendica.
1221 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1223 function api_media_upload()
1227 if (api_user() === false) {
1228 Logger::log('no user');
1229 throw new ForbiddenException();
1234 if (!x($_FILES, 'media')) {
1236 throw new BadRequestException("No media.");
1239 $media = wall_upload_post($a, false);
1242 throw new InternalServerErrorException();
1246 $returndata["media_id"] = $media["id"];
1247 $returndata["media_id_string"] = (string)$media["id"];
1248 $returndata["size"] = $media["size"];
1249 $returndata["image"] = ["w" => $media["width"],
1250 "h" => $media["height"],
1251 "image_type" => $media["type"]];
1253 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1255 return ["media" => $returndata];
1258 /// @TODO move to top of file or somewhere better
1259 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1263 * @param string $type Return type (atom, rss, xml, json)
1265 * @return array|string
1267 function api_status_show($type, $item_id = 0)
1271 $user_info = api_get_user($a);
1273 Logger::log('api_status_show: user_info: '.print_r($user_info, true), Logger::DEBUG);
1275 if ($type == "raw") {
1276 $privacy_sql = "AND NOT `private`";
1281 if (!empty($item_id)) {
1282 // Get the item with the given id
1283 $condition = ['id' => $item_id];
1285 // get last public wall message
1286 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1287 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1289 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1291 if (DBA::isResult($lastwall)) {
1292 $in_reply_to = api_in_reply_to($lastwall);
1294 $converted = api_convert_item($lastwall);
1296 if ($type == "xml") {
1297 $geo = "georss:point";
1303 'created_at' => api_date($lastwall['created']),
1304 'id' => intval($lastwall['id']),
1305 'id_str' => (string) $lastwall['id'],
1306 'text' => $converted["text"],
1307 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1308 'truncated' => false,
1309 'in_reply_to_status_id' => $in_reply_to['status_id'],
1310 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1311 'in_reply_to_user_id' => $in_reply_to['user_id'],
1312 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1313 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1314 'user' => $user_info,
1316 'coordinates' => '',
1318 'contributors' => '',
1319 'is_quote_status' => false,
1320 'retweet_count' => 0,
1321 'favorite_count' => 0,
1322 'favorited' => $lastwall['starred'] ? true : false,
1323 'retweeted' => false,
1324 'possibly_sensitive' => false,
1326 'statusnet_html' => $converted["html"],
1327 'statusnet_conversation_id' => $lastwall['parent'],
1328 'external_url' => System::baseUrl() . '/display/' . $lastwall['guid'],
1331 if (count($converted["attachments"]) > 0) {
1332 $status_info["attachments"] = $converted["attachments"];
1335 if (count($converted["entities"]) > 0) {
1336 $status_info["entities"] = $converted["entities"];
1339 if ($status_info["source"] == 'web') {
1340 $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1341 } elseif (ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) != $status_info["source"]) {
1342 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']).')');
1345 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1346 unset($status_info["user"]["uid"]);
1347 unset($status_info["user"]["self"]);
1349 Logger::log('status_info: '.print_r($status_info, true), Logger::DEBUG);
1351 if ($type == "raw") {
1352 return $status_info;
1355 return api_format_data("statuses", $type, ['status' => $status_info]);
1360 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1361 * The author's most recent status will be returned inline.
1363 * @param string $type Return type (atom, rss, xml, json)
1364 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1366 function api_users_show($type)
1370 $user_info = api_get_user($a);
1372 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1373 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'private' => false];
1374 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1376 if (DBA::isResult($lastwall)) {
1377 $in_reply_to = api_in_reply_to($lastwall);
1379 $converted = api_convert_item($lastwall);
1381 if ($type == "xml") {
1382 $geo = "georss:point";
1387 $user_info['status'] = [
1388 'text' => $converted["text"],
1389 'truncated' => false,
1390 'created_at' => api_date($lastwall['created']),
1391 'in_reply_to_status_id' => $in_reply_to['status_id'],
1392 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1393 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1394 'id' => intval($lastwall['contact-id']),
1395 'id_str' => (string) $lastwall['contact-id'],
1396 'in_reply_to_user_id' => $in_reply_to['user_id'],
1397 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1398 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1400 'favorited' => $lastwall['starred'] ? true : false,
1401 'statusnet_html' => $converted["html"],
1402 'statusnet_conversation_id' => $lastwall['parent'],
1403 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1406 if (count($converted["attachments"]) > 0) {
1407 $user_info["status"]["attachments"] = $converted["attachments"];
1410 if (count($converted["entities"]) > 0) {
1411 $user_info["status"]["entities"] = $converted["entities"];
1414 if ($user_info["status"]["source"] == 'web') {
1415 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1418 if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
1419 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) . ')');
1423 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1424 unset($user_info["uid"]);
1425 unset($user_info["self"]);
1427 return api_format_data("user", $type, ['user' => $user_info]);
1430 /// @TODO move to top of file or somewhere better
1431 api_register_func('api/users/show', 'api_users_show');
1432 api_register_func('api/externalprofile/show', 'api_users_show');
1435 * Search a public user account.
1437 * @param string $type Return type (atom, rss, xml, json)
1439 * @return array|string
1440 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1442 function api_users_search($type)
1448 if (x($_GET, 'q')) {
1449 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1451 if (!DBA::isResult($r)) {
1452 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1455 if (DBA::isResult($r)) {
1457 foreach ($r as $user) {
1458 $user_info = api_get_user($a, $user["id"]);
1460 if ($type == "xml") {
1461 $userlist[$k++.":user"] = $user_info;
1463 $userlist[] = $user_info;
1466 $userlist = ["users" => $userlist];
1468 throw new BadRequestException("User ".$_GET["q"]." not found.");
1471 throw new BadRequestException("No user specified.");
1474 return api_format_data("users", $type, $userlist);
1477 /// @TODO move to top of file or somewhere better
1478 api_register_func('api/users/search', 'api_users_search');
1481 * Return user objects
1483 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1485 * @param string $type Return format: json or xml
1487 * @return array|string
1488 * @throws NotFoundException if the results are empty.
1490 function api_users_lookup($type)
1494 if (!empty($_REQUEST['user_id'])) {
1495 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1497 $users[] = api_get_user(get_app(), $id);
1502 if (empty($users)) {
1503 throw new NotFoundException;
1506 return api_format_data("users", $type, ['users' => $users]);
1509 /// @TODO move to top of file or somewhere better
1510 api_register_func('api/users/lookup', 'api_users_lookup', true);
1513 * Returns statuses that match a specified query.
1515 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1517 * @param string $type Return format: json, xml, atom, rss
1519 * @return array|string
1520 * @throws BadRequestException if the "q" parameter is missing.
1522 function api_search($type)
1525 $user_info = api_get_user($a);
1527 if (api_user() === false || $user_info === false) {
1528 throw new ForbiddenException();
1533 if (!x($_REQUEST, 'q')) {
1534 throw new BadRequestException("q parameter is required.");
1537 if (x($_REQUEST, 'rpp')) {
1538 $count = $_REQUEST['rpp'];
1539 } elseif (x($_REQUEST, 'count')) {
1540 $count = $_REQUEST['count'];
1545 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1546 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1547 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1549 $start = $page * $count;
1551 $condition = ["`gravity` IN (?, ?) AND `item`.`id` > ?
1552 AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1553 AND `item`.`body` LIKE CONCAT('%',?,'%')",
1554 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, api_user(), $_REQUEST['q']];
1557 $condition[0] .= " AND `item`.`id` <= ?";
1558 $condition[] = $max_id;
1561 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1562 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1564 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1566 return api_format_data("statuses", $type, $data);
1569 /// @TODO move to top of file or somewhere better
1570 api_register_func('api/search/tweets', 'api_search', true);
1571 api_register_func('api/search', 'api_search', true);
1574 * Returns the most recent statuses posted by the user and the users they follow.
1576 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1578 * @param string $type Return type (atom, rss, xml, json)
1580 * @todo Optional parameters
1581 * @todo Add reply info
1583 function api_statuses_home_timeline($type)
1586 $user_info = api_get_user($a);
1588 if (api_user() === false || $user_info === false) {
1589 throw new ForbiddenException();
1592 unset($_REQUEST["user_id"]);
1593 unset($_GET["user_id"]);
1595 unset($_REQUEST["screen_name"]);
1596 unset($_GET["screen_name"]);
1598 // get last network messages
1601 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1602 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1606 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1607 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1608 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1609 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1610 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1612 $start = $page * $count;
1614 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1615 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1618 $condition[0] .= " AND `item`.`id` <= ?";
1619 $condition[] = $max_id;
1621 if ($exclude_replies > 0) {
1622 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1624 if ($conversation_id > 0) {
1625 $condition[0] .= " AND `item`.`parent` = ?";
1626 $condition[] = $conversation_id;
1629 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1630 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1632 $items = Item::inArray($statuses);
1634 $ret = api_format_items($items, $user_info, false, $type);
1636 // Set all posts from the query above to seen
1638 foreach ($items as $item) {
1639 $idarray[] = intval($item["id"]);
1642 if (!empty($idarray)) {
1643 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1645 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1649 $data = ['status' => $ret];
1654 $data = api_rss_extra($a, $data, $user_info);
1658 return api_format_data("statuses", $type, $data);
1661 /// @TODO move to top of file or somewhere better
1662 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1663 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1666 * Returns the most recent statuses from public users.
1668 * @param string $type Return type (atom, rss, xml, json)
1670 * @return array|string
1672 function api_statuses_public_timeline($type)
1675 $user_info = api_get_user($a);
1677 if (api_user() === false || $user_info === false) {
1678 throw new ForbiddenException();
1681 // get last network messages
1684 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1685 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1689 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1690 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1691 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1692 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1693 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1695 $start = $page * $count;
1698 if ($exclude_replies && !$conversation_id) {
1699 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall`",
1700 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1703 $condition[0] .= " AND `thread`.`iid` <= ?";
1704 $condition[] = $max_id;
1707 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1708 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1710 $r = Item::inArray($statuses);
1712 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin`",
1713 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1716 $condition[0] .= " AND `item`.`id` <= ?";
1717 $condition[] = $max_id;
1719 if ($conversation_id > 0) {
1720 $condition[0] .= " AND `item`.`parent` = ?";
1721 $condition[] = $conversation_id;
1724 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1725 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1727 $r = Item::inArray($statuses);
1730 $ret = api_format_items($r, $user_info, false, $type);
1732 $data = ['status' => $ret];
1737 $data = api_rss_extra($a, $data, $user_info);
1741 return api_format_data("statuses", $type, $data);
1744 /// @TODO move to top of file or somewhere better
1745 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1748 * Returns the most recent statuses posted by users this node knows about.
1750 * @brief Returns the list of public federated posts this node knows about
1752 * @param string $type Return format: json, xml, atom, rss
1753 * @return array|string
1754 * @throws ForbiddenException
1756 function api_statuses_networkpublic_timeline($type)
1759 $user_info = api_get_user($a);
1761 if (api_user() === false || $user_info === false) {
1762 throw new ForbiddenException();
1765 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1766 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1769 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1770 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1774 $start = ($page - 1) * $count;
1776 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1777 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1780 $condition[0] .= " AND `thread`.`iid` <= ?";
1781 $condition[] = $max_id;
1784 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1785 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1787 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1789 $data = ['status' => $ret];
1794 $data = api_rss_extra($a, $data, $user_info);
1798 return api_format_data("statuses", $type, $data);
1801 /// @TODO move to top of file or somewhere better
1802 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1805 * Returns a single status.
1807 * @param string $type Return type (atom, rss, xml, json)
1809 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1811 function api_statuses_show($type)
1814 $user_info = api_get_user($a);
1816 if (api_user() === false || $user_info === false) {
1817 throw new ForbiddenException();
1821 $id = intval(defaults($a->argv, 3, 0));
1824 $id = intval(defaults($_REQUEST, 'id', 0));
1829 $id = intval(defaults($a->argv, 4, 0));
1832 Logger::log('API: api_statuses_show: ' . $id);
1834 $conversation = !empty($_REQUEST['conversation']);
1836 // try to fetch the item for the local user - or the public item, if there is no local one
1837 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1838 if (!DBA::isResult($uri_item)) {
1839 throw new BadRequestException("There is no status with this id.");
1842 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1843 if (!DBA::isResult($item)) {
1844 throw new BadRequestException("There is no status with this id.");
1849 if ($conversation) {
1850 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1851 $params = ['order' => ['id' => true]];
1853 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1857 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1859 /// @TODO How about copying this to above methods which don't check $r ?
1860 if (!DBA::isResult($statuses)) {
1861 throw new BadRequestException("There is no status with this id.");
1864 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1866 if ($conversation) {
1867 $data = ['status' => $ret];
1868 return api_format_data("statuses", $type, $data);
1870 $data = ['status' => $ret[0]];
1871 return api_format_data("status", $type, $data);
1875 /// @TODO move to top of file or somewhere better
1876 api_register_func('api/statuses/show', 'api_statuses_show', true);
1880 * @param string $type Return type (atom, rss, xml, json)
1882 * @todo nothing to say?
1884 function api_conversation_show($type)
1887 $user_info = api_get_user($a);
1889 if (api_user() === false || $user_info === false) {
1890 throw new ForbiddenException();
1894 $id = intval(defaults($a->argv , 3 , 0));
1895 $since_id = intval(defaults($_REQUEST, 'since_id', 0));
1896 $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
1897 $count = intval(defaults($_REQUEST, 'count' , 20));
1898 $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
1903 $start = $page * $count;
1906 $id = intval(defaults($_REQUEST, 'id', 0));
1911 $id = intval(defaults($a->argv, 4, 0));
1914 Logger::log('API: api_conversation_show: '.$id);
1916 // try to fetch the item for the local user - or the public item, if there is no local one
1917 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1918 if (!DBA::isResult($item)) {
1919 throw new BadRequestException("There is no status with this id.");
1922 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1923 if (!DBA::isResult($parent)) {
1924 throw new BadRequestException("There is no status with this id.");
1927 $id = $parent['id'];
1929 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1930 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1933 $condition[0] .= " AND `item`.`id` <= ?";
1934 $condition[] = $max_id;
1937 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1938 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1940 if (!DBA::isResult($statuses)) {
1941 throw new BadRequestException("There is no status with id $id.");
1944 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1946 $data = ['status' => $ret];
1947 return api_format_data("statuses", $type, $data);
1950 /// @TODO move to top of file or somewhere better
1951 api_register_func('api/conversation/show', 'api_conversation_show', true);
1952 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1957 * @param string $type Return type (atom, rss, xml, json)
1959 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1961 function api_statuses_repeat($type)
1967 if (api_user() === false) {
1968 throw new ForbiddenException();
1974 $id = intval(defaults($a->argv, 3, 0));
1977 $id = intval(defaults($_REQUEST, 'id', 0));
1982 $id = intval(defaults($a->argv, 4, 0));
1985 Logger::log('API: api_statuses_repeat: '.$id);
1987 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1988 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
1990 if (DBA::isResult($item) && $item['body'] != "") {
1991 if (strpos($item['body'], "[/share]") !== false) {
1992 $pos = strpos($item['body'], "[share");
1993 $post = substr($item['body'], $pos);
1995 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
1997 $post .= $item['body'];
1998 $post .= "[/share]";
2000 $_REQUEST['body'] = $post;
2001 $_REQUEST['profile_uid'] = api_user();
2002 $_REQUEST['api_source'] = true;
2004 if (!x($_REQUEST, "source")) {
2005 $_REQUEST["source"] = api_source();
2008 $item_id = item_post($a);
2010 throw new ForbiddenException();
2013 // output the post that we just posted.
2015 return api_status_show($type, $item_id);
2018 /// @TODO move to top of file or somewhere better
2019 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2022 * Destroys a specific status.
2024 * @param string $type Return type (atom, rss, xml, json)
2026 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2028 function api_statuses_destroy($type)
2032 if (api_user() === false) {
2033 throw new ForbiddenException();
2039 $id = intval(defaults($a->argv, 3, 0));
2042 $id = intval(defaults($_REQUEST, 'id', 0));
2047 $id = intval(defaults($a->argv, 4, 0));
2050 Logger::log('API: api_statuses_destroy: '.$id);
2052 $ret = api_statuses_show($type);
2054 Item::deleteForUser(['id' => $id], api_user());
2059 /// @TODO move to top of file or somewhere better
2060 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2063 * Returns the most recent mentions.
2065 * @param string $type Return type (atom, rss, xml, json)
2067 * @see http://developer.twitter.com/doc/get/statuses/mentions
2069 function api_statuses_mentions($type)
2072 $user_info = api_get_user($a);
2074 if (api_user() === false || $user_info === false) {
2075 throw new ForbiddenException();
2078 unset($_REQUEST["user_id"]);
2079 unset($_GET["user_id"]);
2081 unset($_REQUEST["screen_name"]);
2082 unset($_GET["screen_name"]);
2084 // get last network messages
2087 $since_id = defaults($_REQUEST, 'since_id', 0);
2088 $max_id = defaults($_REQUEST, 'max_id' , 0);
2089 $count = defaults($_REQUEST, 'count' , 20);
2090 $page = defaults($_REQUEST, 'page' , 1);
2095 $start = ($page - 1) * $count;
2097 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2098 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2099 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2102 $condition[0] .= " AND `item`.`id` <= ?";
2103 $condition[] = $max_id;
2106 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2107 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2109 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2111 $data = ['status' => $ret];
2116 $data = api_rss_extra($a, $data, $user_info);
2120 return api_format_data("statuses", $type, $data);
2123 /// @TODO move to top of file or somewhere better
2124 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2125 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2128 * Returns the most recent statuses posted by the user.
2130 * @brief Returns a user's public timeline
2132 * @param string $type Either "json" or "xml"
2133 * @return string|array
2134 * @throws ForbiddenException
2135 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2137 function api_statuses_user_timeline($type)
2140 $user_info = api_get_user($a);
2142 if (api_user() === false || $user_info === false) {
2143 throw new ForbiddenException();
2147 "api_statuses_user_timeline: api_user: ". api_user() .
2148 "\nuser_info: ".print_r($user_info, true) .
2149 "\n_REQUEST: ".print_r($_REQUEST, true),
2153 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2154 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2155 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2156 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2159 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2160 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2164 $start = ($page - 1) * $count;
2166 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2167 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2169 if ($user_info['self'] == 1) {
2170 $condition[0] .= ' AND `item`.`wall` ';
2173 if ($exclude_replies > 0) {
2174 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2177 if ($conversation_id > 0) {
2178 $condition[0] .= " AND `item`.`parent` = ?";
2179 $condition[] = $conversation_id;
2183 $condition[0] .= " AND `item`.`id` <= ?";
2184 $condition[] = $max_id;
2187 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2188 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2190 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2192 $data = ['status' => $ret];
2197 $data = api_rss_extra($a, $data, $user_info);
2201 return api_format_data("statuses", $type, $data);
2204 /// @TODO move to top of file or somewhere better
2205 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2208 * Star/unstar an item.
2209 * param: id : id of the item
2211 * @param string $type Return type (atom, rss, xml, json)
2213 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2215 function api_favorites_create_destroy($type)
2219 if (api_user() === false) {
2220 throw new ForbiddenException();
2223 // for versioned api.
2224 /// @TODO We need a better global soluton
2225 $action_argv_id = 2;
2226 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2227 $action_argv_id = 3;
2230 if ($a->argc <= $action_argv_id) {
2231 throw new BadRequestException("Invalid request.");
2233 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2234 if ($a->argc == $action_argv_id + 2) {
2235 $itemid = intval(defaults($a->argv, $action_argv_id + 1, 0));
2237 $itemid = intval(defaults($_REQUEST, 'id', 0));
2240 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2242 if (!DBA::isResult($item)) {
2243 throw new BadRequestException("Invalid item.");
2248 $item['starred'] = 1;
2251 $item['starred'] = 0;
2254 throw new BadRequestException("Invalid action ".$action);
2257 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2260 throw new InternalServerErrorException("DB error");
2264 $user_info = api_get_user($a);
2265 $rets = api_format_items([$item], $user_info, false, $type);
2268 $data = ['status' => $ret];
2273 $data = api_rss_extra($a, $data, $user_info);
2277 return api_format_data("status", $type, $data);
2280 /// @TODO move to top of file or somewhere better
2281 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2282 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2285 * Returns the most recent favorite statuses.
2287 * @param string $type Return type (atom, rss, xml, json)
2289 * @return string|array
2291 function api_favorites($type)
2296 $user_info = api_get_user($a);
2298 if (api_user() === false || $user_info === false) {
2299 throw new ForbiddenException();
2304 // in friendica starred item are private
2305 // return favorites only for self
2306 Logger::log('api_favorites: self:' . $user_info['self']);
2308 if ($user_info['self'] == 0) {
2312 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2313 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2314 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2315 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2320 $start = $page*$count;
2322 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2323 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2325 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2328 $condition[0] .= " AND `item`.`id` <= ?";
2329 $condition[] = $max_id;
2332 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2334 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2337 $data = ['status' => $ret];
2342 $data = api_rss_extra($a, $data, $user_info);
2346 return api_format_data("statuses", $type, $data);
2349 /// @TODO move to top of file or somewhere better
2350 api_register_func('api/favorites', 'api_favorites', true);
2354 * @param array $item
2355 * @param array $recipient
2356 * @param array $sender
2360 function api_format_messages($item, $recipient, $sender)
2362 // standard meta information
2364 'id' => $item['id'],
2365 'sender_id' => $sender['id'],
2367 'recipient_id' => $recipient['id'],
2368 'created_at' => api_date(defaults($item, 'created', DateTimeFormat::utcNow())),
2369 'sender_screen_name' => $sender['screen_name'],
2370 'recipient_screen_name' => $recipient['screen_name'],
2371 'sender' => $sender,
2372 'recipient' => $recipient,
2374 'friendica_seen' => defaults($item, 'seen', 0),
2375 'friendica_parent_uri' => defaults($item, 'parent-uri', ''),
2378 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2379 if (isset($ret['sender']['uid'])) {
2380 unset($ret['sender']['uid']);
2382 if (isset($ret['sender']['self'])) {
2383 unset($ret['sender']['self']);
2385 if (isset($ret['recipient']['uid'])) {
2386 unset($ret['recipient']['uid']);
2388 if (isset($ret['recipient']['self'])) {
2389 unset($ret['recipient']['self']);
2392 //don't send title to regular StatusNET requests to avoid confusing these apps
2393 if (x($_GET, 'getText')) {
2394 $ret['title'] = $item['title'];
2395 if ($_GET['getText'] == 'html') {
2396 $ret['text'] = BBCode::convert($item['body'], false);
2397 } elseif ($_GET['getText'] == 'plain') {
2398 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2401 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2403 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2404 unset($ret['sender']);
2405 unset($ret['recipient']);
2413 * @param array $item
2417 function api_convert_item($item)
2419 $body = $item['body'];
2420 $attachments = api_get_attachments($body);
2422 // Workaround for ostatus messages where the title is identically to the body
2423 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2424 $statusbody = trim(HTML::toPlaintext($html, 0));
2426 // handle data: images
2427 $statusbody = api_format_items_embeded_images($item, $statusbody);
2429 $statustitle = trim($item['title']);
2431 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2432 $statustext = trim($statusbody);
2434 $statustext = trim($statustitle."\n\n".$statusbody);
2437 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($statustext)> 1000)) {
2438 $statustext = substr($statustext, 0, 1000) . "... \n" . defaults($item, 'plink', '');
2441 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2443 // Workaround for clients with limited HTML parser functionality
2444 $search = ["<br>", "<blockquote>", "</blockquote>",
2445 "<h1>", "</h1>", "<h2>", "</h2>",
2446 "<h3>", "</h3>", "<h4>", "</h4>",
2447 "<h5>", "</h5>", "<h6>", "</h6>"];
2448 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2449 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2450 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2451 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2452 $statushtml = str_replace($search, $replace, $statushtml);
2454 if ($item['title'] != "") {
2455 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2459 $oldtext = $statushtml;
2460 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2461 } while ($oldtext != $statushtml);
2463 if (substr($statushtml, 0, 4) == '<br>') {
2464 $statushtml = substr($statushtml, 4);
2467 if (substr($statushtml, 0, -4) == '<br>') {
2468 $statushtml = substr($statushtml, -4);
2471 // feeds without body should contain the link
2472 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2473 $statushtml .= BBCode::convert($item['plink']);
2476 $entities = api_get_entitities($statustext, $body);
2479 "text" => $statustext,
2480 "html" => $statushtml,
2481 "attachments" => $attachments,
2482 "entities" => $entities
2488 * @param string $body
2492 function api_get_attachments(&$body)
2495 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2497 $URLSearchString = "^\[\]";
2498 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2506 foreach ($images[1] as $image) {
2507 $imagedata = Image::getInfoFromURL($image);
2510 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2514 if (strstr(defaults($_SERVER, 'HTTP_USER_AGENT', ''), "AndStatus")) {
2515 foreach ($images[0] as $orig) {
2516 $body = str_replace($orig, "", $body);
2520 return $attachments;
2525 * @param string $text
2526 * @param string $bbcode
2529 * @todo Links at the first character of the post
2531 function api_get_entitities(&$text, $bbcode)
2533 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2535 if ($include_entities != "true") {
2536 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2538 foreach ($images[1] as $image) {
2539 $replace = ProxyUtils::proxifyUrl($image);
2540 $text = str_replace($image, $replace, $text);
2545 $bbcode = BBCode::cleanPictureLinks($bbcode);
2547 // Change pure links in text to bbcode uris
2548 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2551 $entities["hashtags"] = [];
2552 $entities["symbols"] = [];
2553 $entities["urls"] = [];
2554 $entities["user_mentions"] = [];
2556 $URLSearchString = "^\[\]";
2558 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2560 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2561 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2562 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2564 $bbcode = preg_replace(
2565 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2566 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2569 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2571 $bbcode = preg_replace(
2572 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2573 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2576 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2578 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2580 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2581 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2584 foreach ($urls[1] as $id => $url) {
2585 //$start = strpos($text, $url, $offset);
2586 $start = iconv_strpos($text, $url, 0, "UTF-8");
2587 if (!($start === false)) {
2588 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2592 ksort($ordered_urls);
2595 //foreach ($urls[1] AS $id=>$url) {
2596 foreach ($ordered_urls as $url) {
2597 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2598 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2600 $display_url = $url["title"];
2602 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2603 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2605 if (strlen($display_url) > 26) {
2606 $display_url = substr($display_url, 0, 25)."…";
2610 //$start = strpos($text, $url, $offset);
2611 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2612 if (!($start === false)) {
2613 $entities["urls"][] = ["url" => $url["url"],
2614 "expanded_url" => $url["url"],
2615 "display_url" => $display_url,
2616 "indices" => [$start, $start+strlen($url["url"])]];
2617 $offset = $start + 1;
2621 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2622 $ordered_images = [];
2623 foreach ($images[1] as $image) {
2624 //$start = strpos($text, $url, $offset);
2625 $start = iconv_strpos($text, $image, 0, "UTF-8");
2626 if (!($start === false)) {
2627 $ordered_images[$start] = $image;
2630 //$entities["media"] = array();
2633 foreach ($ordered_images as $url) {
2634 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2635 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2637 if (strlen($display_url) > 26) {
2638 $display_url = substr($display_url, 0, 25)."…";
2641 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2642 if (!($start === false)) {
2643 $image = Image::getInfoFromURL($url);
2645 // If image cache is activated, then use the following sizes:
2646 // thumb (150), small (340), medium (600) and large (1024)
2647 if (!Config::get("system", "proxy_disabled")) {
2648 $media_url = ProxyUtils::proxifyUrl($url);
2651 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2652 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2654 if (($image[0] > 150) || ($image[1] > 150)) {
2655 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2656 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2659 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2660 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2662 if (($image[0] > 600) || ($image[1] > 600)) {
2663 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2664 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2668 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2671 $entities["media"][] = [
2673 "id_str" => (string)$start+1,
2674 "indices" => [$start, $start+strlen($url)],
2675 "media_url" => Strings::normaliseLink($media_url),
2676 "media_url_https" => $media_url,
2678 "display_url" => $display_url,
2679 "expanded_url" => $url,
2683 $offset = $start + 1;
2692 * @param array $item
2693 * @param string $text
2697 function api_format_items_embeded_images($item, $text)
2699 $text = preg_replace_callback(
2700 '|data:image/([^;]+)[^=]+=*|m',
2701 function () use ($item) {
2702 return System::baseUrl() . '/display/' . $item['guid'];
2710 * @brief return <a href='url'>name</a> as array
2712 * @param string $txt text
2717 function api_contactlink_to_array($txt)
2720 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2721 if ($r && count($match)==3) {
2723 'name' => $match[2],
2737 * @brief return likes, dislikes and attend status for item
2739 * @param array $item array
2740 * @param string $type Return type (atom, rss, xml, json)
2743 * likes => int count,
2744 * dislikes => int count
2746 function api_format_items_activities($item, $type = "json")
2755 'attendmaybe' => [],
2758 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2759 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2761 while ($parent_item = Item::fetch($ret)) {
2762 // not used as result should be structured like other user data
2763 //builtin_activity_puller($i, $activities);
2765 // get user data and add it to the array of the activity
2766 $user = api_get_user($a, $parent_item['author-id']);
2767 switch ($parent_item['verb']) {
2769 $activities['like'][] = $user;
2771 case ACTIVITY_DISLIKE:
2772 $activities['dislike'][] = $user;
2774 case ACTIVITY_ATTEND:
2775 $activities['attendyes'][] = $user;
2777 case ACTIVITY_ATTENDNO:
2778 $activities['attendno'][] = $user;
2780 case ACTIVITY_ATTENDMAYBE:
2781 $activities['attendmaybe'][] = $user;
2790 if ($type == "xml") {
2791 $xml_activities = [];
2792 foreach ($activities as $k => $v) {
2793 // change xml element from "like" to "friendica:like"
2794 $xml_activities["friendica:".$k] = $v;
2795 // add user data into xml output
2797 foreach ($v as $user) {
2798 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2801 $activities = $xml_activities;
2809 * @brief return data from profiles
2811 * @param array $profile_row array containing data from db table 'profile'
2814 function api_format_items_profiles($profile_row)
2817 'profile_id' => $profile_row['id'],
2818 'profile_name' => $profile_row['profile-name'],
2819 'is_default' => $profile_row['is-default'] ? true : false,
2820 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2821 'profile_photo' => $profile_row['photo'],
2822 'profile_thumb' => $profile_row['thumb'],
2823 'publish' => $profile_row['publish'] ? true : false,
2824 'net_publish' => $profile_row['net-publish'] ? true : false,
2825 'description' => $profile_row['pdesc'],
2826 'date_of_birth' => $profile_row['dob'],
2827 'address' => $profile_row['address'],
2828 'city' => $profile_row['locality'],
2829 'region' => $profile_row['region'],
2830 'postal_code' => $profile_row['postal-code'],
2831 'country' => $profile_row['country-name'],
2832 'hometown' => $profile_row['hometown'],
2833 'gender' => $profile_row['gender'],
2834 'marital' => $profile_row['marital'],
2835 'marital_with' => $profile_row['with'],
2836 'marital_since' => $profile_row['howlong'],
2837 'sexual' => $profile_row['sexual'],
2838 'politic' => $profile_row['politic'],
2839 'religion' => $profile_row['religion'],
2840 'public_keywords' => $profile_row['pub_keywords'],
2841 'private_keywords' => $profile_row['prv_keywords'],
2842 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2843 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2844 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2845 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2846 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2847 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2848 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2849 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2850 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2851 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2852 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2853 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2854 'homepage' => $profile_row['homepage'],
2861 * @brief format items to be returned by api
2863 * @param array $r array of items
2864 * @param array $user_info
2865 * @param bool $filter_user filter items by $user_info
2866 * @param string $type Return type (atom, rss, xml, json)
2868 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2874 foreach ($r as $item) {
2875 localize_item($item);
2876 list($status_user, $owner_user) = api_item_get_user($a, $item);
2878 // Look if the posts are matching if they should be filtered by user id
2879 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2883 $in_reply_to = api_in_reply_to($item);
2885 $converted = api_convert_item($item);
2887 if ($type == "xml") {
2888 $geo = "georss:point";
2894 'text' => $converted["text"],
2895 'truncated' => false,
2896 'created_at'=> api_date($item['created']),
2897 'in_reply_to_status_id' => $in_reply_to['status_id'],
2898 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2899 'source' => (($item['app']) ? $item['app'] : 'web'),
2900 'id' => intval($item['id']),
2901 'id_str' => (string) intval($item['id']),
2902 'in_reply_to_user_id' => $in_reply_to['user_id'],
2903 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2904 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2906 'favorited' => $item['starred'] ? true : false,
2907 'user' => $status_user,
2908 'friendica_owner' => $owner_user,
2909 'friendica_private' => $item['private'] == 1,
2910 //'entities' => NULL,
2911 'statusnet_html' => $converted["html"],
2912 'statusnet_conversation_id' => $item['parent'],
2913 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2914 'friendica_activities' => api_format_items_activities($item, $type),
2917 if (count($converted["attachments"]) > 0) {
2918 $status["attachments"] = $converted["attachments"];
2921 if (count($converted["entities"]) > 0) {
2922 $status["entities"] = $converted["entities"];
2925 if ($status["source"] == 'web') {
2926 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
2927 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
2928 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
2931 if ($item["id"] == $item["parent"]) {
2932 $retweeted_item = api_share_as_retweet($item);
2933 if ($retweeted_item !== false) {
2934 $retweeted_status = $status;
2935 $status['user'] = $status['friendica_owner'];
2937 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
2938 } catch (BadRequestException $e) {
2939 // user not found. should be found?
2940 /// @todo check if the user should be always found
2941 $retweeted_status["user"] = [];
2944 $rt_converted = api_convert_item($retweeted_item);
2946 $retweeted_status['text'] = $rt_converted["text"];
2947 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2948 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2949 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2950 $status['retweeted_status'] = $retweeted_status;
2954 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2955 unset($status["user"]["uid"]);
2956 unset($status["user"]["self"]);
2958 if ($item["coord"] != "") {
2959 $coords = explode(' ', $item["coord"]);
2960 if (count($coords) == 2) {
2961 if ($type == "json") {
2962 $status["geo"] = ['type' => 'Point',
2963 'coordinates' => [(float) $coords[0],
2964 (float) $coords[1]]];
2965 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2966 $status["georss:point"] = $item["coord"];
2976 * Returns the remaining number of API requests available to the user before the API limit is reached.
2978 * @param string $type Return type (atom, rss, xml, json)
2980 * @return array|string
2982 function api_account_rate_limit_status($type)
2984 if ($type == "xml") {
2986 'remaining-hits' => '150',
2987 '@attributes' => ["type" => "integer"],
2988 'hourly-limit' => '150',
2989 '@attributes2' => ["type" => "integer"],
2990 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
2991 '@attributes3' => ["type" => "datetime"],
2992 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2993 '@attributes4' => ["type" => "integer"],
2997 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2998 'remaining_hits' => '150',
2999 'hourly_limit' => '150',
3000 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3004 return api_format_data('hash', $type, ['hash' => $hash]);
3007 /// @TODO move to top of file or somewhere better
3008 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3011 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3013 * @param string $type Return type (atom, rss, xml, json)
3015 * @return array|string
3017 function api_help_test($type)
3019 if ($type == 'xml') {
3025 return api_format_data('ok', $type, ["ok" => $ok]);
3028 /// @TODO move to top of file or somewhere better
3029 api_register_func('api/help/test', 'api_help_test', false);
3032 * Returns all lists the user subscribes to.
3034 * @param string $type Return type (atom, rss, xml, json)
3036 * @return array|string
3037 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3039 function api_lists_list($type)
3042 /// @TODO $ret is not filled here?
3043 return api_format_data('lists', $type, ["lists_list" => $ret]);
3046 /// @TODO move to top of file or somewhere better
3047 api_register_func('api/lists/list', 'api_lists_list', true);
3048 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3051 * Returns all groups the user owns.
3053 * @param string $type Return type (atom, rss, xml, json)
3055 * @return array|string
3056 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3058 function api_lists_ownerships($type)
3062 if (api_user() === false) {
3063 throw new ForbiddenException();
3067 $user_info = api_get_user($a);
3068 $uid = $user_info['uid'];
3070 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3072 // loop through all groups
3074 foreach ($groups as $group) {
3075 if ($group['visible']) {
3081 'name' => $group['name'],
3082 'id' => intval($group['id']),
3083 'id_str' => (string) $group['id'],
3084 'user' => $user_info,
3088 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3091 /// @TODO move to top of file or somewhere better
3092 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3095 * Returns recent statuses from users in the specified group.
3097 * @param string $type Return type (atom, rss, xml, json)
3099 * @return array|string
3100 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3102 function api_lists_statuses($type)
3106 $user_info = api_get_user($a);
3107 if (api_user() === false || $user_info === false) {
3108 throw new ForbiddenException();
3111 unset($_REQUEST["user_id"]);
3112 unset($_GET["user_id"]);
3114 unset($_REQUEST["screen_name"]);
3115 unset($_GET["screen_name"]);
3117 if (empty($_REQUEST['list_id'])) {
3118 throw new BadRequestException('list_id not specified');
3122 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
3123 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
3127 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3128 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3129 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
3130 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
3132 $start = $page * $count;
3134 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3135 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3138 $condition[0] .= " AND `item`.`id` <= ?";
3139 $condition[] = $max_id;
3141 if ($exclude_replies > 0) {
3142 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3144 if ($conversation_id > 0) {
3145 $condition[0] .= " AND `item`.`parent` = ?";
3146 $condition[] = $conversation_id;
3149 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3150 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3152 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3154 $data = ['status' => $items];
3159 $data = api_rss_extra($a, $data, $user_info);
3163 return api_format_data("statuses", $type, $data);
3166 /// @TODO move to top of file or somewhere better
3167 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3170 * Considers friends and followers lists to be private and won't return
3171 * anything if any user_id parameter is passed.
3173 * @brief Returns either the friends of the follower list
3175 * @param string $qtype Either "friends" or "followers"
3176 * @return boolean|array
3177 * @throws ForbiddenException
3179 function api_statuses_f($qtype)
3183 if (api_user() === false) {
3184 throw new ForbiddenException();
3188 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3189 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3193 $start = ($page - 1) * $count;
3195 $user_info = api_get_user($a);
3197 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3198 /* this is to stop Hotot to load friends multiple times
3199 * I'm not sure if I'm missing return something or
3200 * is a bug in hotot. Workaround, meantime
3204 return array('$users' => $ret);*/
3209 if ($qtype == 'friends') {
3210 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3211 } elseif ($qtype == 'followers') {
3212 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3215 // friends and followers only for self
3216 if ($user_info['self'] == 0) {
3217 $sql_extra = " AND false ";
3220 if ($qtype == 'blocks') {
3221 $sql_filter = 'AND `blocked` AND NOT `pending`';
3222 } elseif ($qtype == 'incoming') {
3223 $sql_filter = 'AND `pending`';
3225 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3243 foreach ($r as $cid) {
3244 $user = api_get_user($a, $cid['nurl']);
3245 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3246 unset($user["uid"]);
3247 unset($user["self"]);
3254 return ['user' => $ret];
3259 * Returns the user's friends.
3261 * @brief Returns the list of friends of the provided user
3263 * @deprecated By Twitter API in favor of friends/list
3265 * @param string $type Either "json" or "xml"
3266 * @return boolean|string|array
3268 function api_statuses_friends($type)
3270 $data = api_statuses_f("friends");
3271 if ($data === false) {
3274 return api_format_data("users", $type, $data);
3278 * Returns the user's followers.
3280 * @brief Returns the list of followers of the provided user
3282 * @deprecated By Twitter API in favor of friends/list
3284 * @param string $type Either "json" or "xml"
3285 * @return boolean|string|array
3287 function api_statuses_followers($type)
3289 $data = api_statuses_f("followers");
3290 if ($data === false) {
3293 return api_format_data("users", $type, $data);
3296 /// @TODO move to top of file or somewhere better
3297 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3298 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3301 * Returns the list of blocked users
3303 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3305 * @param string $type Either "json" or "xml"
3307 * @return boolean|string|array
3309 function api_blocks_list($type)
3311 $data = api_statuses_f('blocks');
3312 if ($data === false) {
3315 return api_format_data("users", $type, $data);
3318 /// @TODO move to top of file or somewhere better
3319 api_register_func('api/blocks/list', 'api_blocks_list', true);
3322 * Returns the list of pending users IDs
3324 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3326 * @param string $type Either "json" or "xml"
3328 * @return boolean|string|array
3330 function api_friendships_incoming($type)
3332 $data = api_statuses_f('incoming');
3333 if ($data === false) {
3338 foreach ($data['user'] as $user) {
3339 $ids[] = $user['id'];
3342 return api_format_data("ids", $type, ['id' => $ids]);
3345 /// @TODO move to top of file or somewhere better
3346 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3349 * Returns the instance's configuration information.
3351 * @param string $type Return type (atom, rss, xml, json)
3353 * @return array|string
3355 function api_statusnet_config($type)
3359 $name = Config::get('config', 'sitename');
3360 $server = $a->getHostName();
3361 $logo = System::baseUrl() . '/images/friendica-64.png';
3362 $email = Config::get('config', 'admin_email');
3363 $closed = intval(Config::get('config', 'register_policy')) === REGISTER_CLOSED ? 'true' : 'false';
3364 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3365 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3366 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3367 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3370 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3371 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3372 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3373 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3374 'shorturllength' => '30',
3376 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3377 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3378 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3379 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3384 return api_format_data('config', $type, ['config' => $config]);
3387 /// @TODO move to top of file or somewhere better
3388 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3389 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3393 * @param string $type Return type (atom, rss, xml, json)
3395 * @return array|string
3397 function api_statusnet_version($type)
3400 $fake_statusnet_version = "0.9.7";
3402 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3405 /// @TODO move to top of file or somewhere better
3406 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3407 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3411 * @param string $type Return type (atom, rss, xml, json)
3413 * @todo use api_format_data() to return data
3415 function api_ff_ids($type)
3418 throw new ForbiddenException();
3425 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3428 "SELECT `pcontact`.`id` FROM `contact`
3429 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3430 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3433 if (!DBA::isResult($r)) {
3438 foreach ($r as $rr) {
3439 if ($stringify_ids) {
3442 $ids[] = intval($rr['id']);
3446 return api_format_data("ids", $type, ['id' => $ids]);
3450 * Returns the ID of every user the user is following.
3452 * @param string $type Return type (atom, rss, xml, json)
3454 * @return array|string
3455 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3457 function api_friends_ids($type)
3459 return api_ff_ids($type);
3463 * Returns the ID of every user following the user.
3465 * @param string $type Return type (atom, rss, xml, json)
3467 * @return array|string
3468 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3470 function api_followers_ids($type)
3472 return api_ff_ids($type);
3475 /// @TODO move to top of file or somewhere better
3476 api_register_func('api/friends/ids', 'api_friends_ids', true);
3477 api_register_func('api/followers/ids', 'api_followers_ids', true);
3480 * Sends a new direct message.
3482 * @param string $type Return type (atom, rss, xml, json)
3484 * @return array|string
3485 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3487 function api_direct_messages_new($type)
3491 if (api_user() === false) {
3492 throw new ForbiddenException();
3495 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3499 $sender = api_get_user($a);
3502 if (!empty($_POST['screen_name'])) {
3504 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3506 DBA::escape($_POST['screen_name'])
3509 if (DBA::isResult($r)) {
3510 // Selecting the id by priority, friendica first
3511 api_best_nickname($r);
3513 $recipient = api_get_user($a, $r[0]['nurl']);
3516 $recipient = api_get_user($a, $_POST['user_id']);
3519 if (empty($recipient)) {
3520 throw new NotFoundException('Recipient not found');
3525 if (x($_REQUEST, 'replyto')) {
3527 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3529 intval($_REQUEST['replyto'])
3531 $replyto = $r[0]['parent-uri'];
3532 $sub = $r[0]['title'];
3534 if (x($_REQUEST, 'title')) {
3535 $sub = $_REQUEST['title'];
3537 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3541 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3544 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3545 $ret = api_format_messages($r[0], $recipient, $sender);
3547 $ret = ["error"=>$id];
3550 $data = ['direct_message'=>$ret];
3556 $data = api_rss_extra($a, $data, $sender);
3560 return api_format_data("direct-messages", $type, $data);
3563 /// @TODO move to top of file or somewhere better
3564 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3567 * Destroys a direct message.
3569 * @brief delete a direct_message from mail table through api
3571 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3572 * @return string|array
3573 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3575 function api_direct_messages_destroy($type)
3579 if (api_user() === false) {
3580 throw new ForbiddenException();
3584 $user_info = api_get_user($a);
3586 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3588 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3589 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3590 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3592 $uid = $user_info['uid'];
3593 // error if no id or parenturi specified (for clients posting parent-uri as well)
3594 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3595 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3596 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3599 // BadRequestException if no id specified (for clients using Twitter API)
3601 throw new BadRequestException('Message id not specified');
3604 // add parent-uri to sql command if specified by calling app
3605 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3607 // get data of the specified message id
3609 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3614 // error message if specified id is not in database
3615 if (!DBA::isResult($r)) {
3616 if ($verbose == "true") {
3617 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3618 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3620 /// @todo BadRequestException ok for Twitter API clients?
3621 throw new BadRequestException('message id not in database');
3626 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3631 if ($verbose == "true") {
3634 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3635 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3637 $answer = ['result' => 'error', 'message' => 'unknown error'];
3638 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3641 /// @todo return JSON data like Twitter API not yet implemented
3644 /// @TODO move to top of file or somewhere better
3645 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3650 * @brief unfollow contact
3652 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3653 * @return string|array
3654 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3656 function api_friendships_destroy($type)
3660 if ($uid === false) {
3661 throw new ForbiddenException();
3664 $contact_id = defaults($_REQUEST, 'user_id');
3666 if (empty($contact_id)) {
3667 Logger::log("No user_id specified", Logger::DEBUG);
3668 throw new BadRequestException("no user_id specified");
3671 // Get Contact by given id
3672 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3674 if(!DBA::isResult($contact)) {
3675 Logger::log("No contact found for ID" . $contact_id, Logger::DEBUG);
3676 throw new NotFoundException("no contact found to given ID");
3679 $url = $contact["url"];
3681 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3682 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3683 Strings::normaliseLink($url), $url];
3684 $contact = DBA::selectFirst('contact', [], $condition);
3686 if (!DBA::isResult($contact)) {
3687 Logger::log("Not following Contact", Logger::DEBUG);
3688 throw new NotFoundException("Not following Contact");
3691 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3692 Logger::log("Not supported", Logger::DEBUG);
3693 throw new ExpectationFailedException("Not supported");
3696 $dissolve = ($contact['rel'] == Contact::SHARING);
3698 $owner = User::getOwnerDataById($uid);
3700 Contact::terminateFriendship($owner, $contact, $dissolve);
3703 Logger::log("No owner found", Logger::DEBUG);
3704 throw new NotFoundException("Error Processing Request");
3707 // Sharing-only contacts get deleted as there no relationship any more
3709 Contact::remove($contact['id']);
3711 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3714 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3715 unset($contact["uid"]);
3716 unset($contact["self"]);
3718 // Set screen_name since Twidere requests it
3719 $contact["screen_name"] = $contact["nick"];
3721 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3723 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3727 * @param string $type Return type (atom, rss, xml, json)
3728 * @param string $box
3729 * @param string $verbose
3731 * @return array|string
3733 function api_direct_messages_box($type, $box, $verbose)
3736 if (api_user() === false) {
3737 throw new ForbiddenException();
3740 $count = defaults($_GET, 'count', 20);
3741 $page = defaults($_REQUEST, 'page', 1) - 1;
3746 $since_id = defaults($_REQUEST, 'since_id', 0);
3747 $max_id = defaults($_REQUEST, 'max_id', 0);
3749 $user_id = defaults($_REQUEST, 'user_id', '');
3750 $screen_name = defaults($_REQUEST, 'screen_name', '');
3753 unset($_REQUEST["user_id"]);
3754 unset($_GET["user_id"]);
3756 unset($_REQUEST["screen_name"]);
3757 unset($_GET["screen_name"]);
3759 $user_info = api_get_user($a);
3760 if ($user_info === false) {
3761 throw new ForbiddenException();
3763 $profile_url = $user_info["url"];
3766 $start = $page * $count;
3771 if ($box=="sentbox") {
3772 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3773 } elseif ($box == "conversation") {
3774 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape(defaults($_GET, 'uri', '')) . "'";
3775 } elseif ($box == "all") {
3776 $sql_extra = "true";
3777 } elseif ($box == "inbox") {
3778 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3782 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3785 if ($user_id != "") {
3786 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3787 } elseif ($screen_name !="") {
3788 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3792 "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",
3798 if ($verbose == "true" && !DBA::isResult($r)) {
3799 $answer = ['result' => 'error', 'message' => 'no mails available'];
3800 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3804 foreach ($r as $item) {
3805 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3806 $recipient = $user_info;
3807 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3808 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3809 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3810 $sender = $user_info;
3813 if (isset($recipient) && isset($sender)) {
3814 $ret[] = api_format_messages($item, $recipient, $sender);
3819 $data = ['direct_message' => $ret];
3824 $data = api_rss_extra($a, $data, $user_info);
3828 return api_format_data("direct-messages", $type, $data);
3832 * Returns the most recent direct messages sent by the user.
3834 * @param string $type Return type (atom, rss, xml, json)
3836 * @return array|string
3837 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3839 function api_direct_messages_sentbox($type)
3841 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3842 return api_direct_messages_box($type, "sentbox", $verbose);
3846 * Returns the most recent direct messages sent to the user.
3848 * @param string $type Return type (atom, rss, xml, json)
3850 * @return array|string
3851 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3853 function api_direct_messages_inbox($type)
3855 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3856 return api_direct_messages_box($type, "inbox", $verbose);
3861 * @param string $type Return type (atom, rss, xml, json)
3863 * @return array|string
3865 function api_direct_messages_all($type)
3867 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3868 return api_direct_messages_box($type, "all", $verbose);
3873 * @param string $type Return type (atom, rss, xml, json)
3875 * @return array|string
3877 function api_direct_messages_conversation($type)
3879 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3880 return api_direct_messages_box($type, "conversation", $verbose);
3883 /// @TODO move to top of file or somewhere better
3884 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3885 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3886 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3887 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3890 * Returns an OAuth Request Token.
3892 * @see https://oauth.net/core/1.0/#auth_step1
3894 function api_oauth_request_token()
3896 $oauth1 = new FKOAuth1();
3898 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3899 } catch (Exception $e) {
3900 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3908 * Returns an OAuth Access Token.
3910 * @return array|string
3911 * @see https://oauth.net/core/1.0/#auth_step3
3913 function api_oauth_access_token()
3915 $oauth1 = new FKOAuth1();
3917 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3918 } catch (Exception $e) {
3919 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3926 /// @TODO move to top of file or somewhere better
3927 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3928 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3932 * @brief delete a complete photoalbum with all containing photos from database through api
3934 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3935 * @return string|array
3937 function api_fr_photoalbum_delete($type)
3939 if (api_user() === false) {
3940 throw new ForbiddenException();
3943 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3945 // we do not allow calls without album string
3947 throw new BadRequestException("no albumname specified");
3949 // check if album is existing
3951 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3955 if (!DBA::isResult($r)) {
3956 throw new BadRequestException("album not available");
3959 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3960 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3961 foreach ($r as $rr) {
3962 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
3963 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
3965 if (!DBA::isResult($photo_item)) {
3966 throw new InternalServerErrorException("problem with deleting items occured");
3968 Item::deleteForUser(['id' => $photo_item['id']], api_user());
3971 // now let's delete all photos from the album
3972 $result = DBA::delete('photo', ['uid' => api_user(), 'album' => $album]);
3974 // return success of deletion or error message
3976 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
3977 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
3979 throw new InternalServerErrorException("unknown error - deleting from database failed");
3984 * @brief update the name of the album for all photos of an album
3986 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3987 * @return string|array
3989 function api_fr_photoalbum_update($type)
3991 if (api_user() === false) {
3992 throw new ForbiddenException();
3995 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3996 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3998 // we do not allow calls without album string
4000 throw new BadRequestException("no albumname specified");
4002 if ($album_new == "") {
4003 throw new BadRequestException("no new albumname specified");
4005 // check if album is existing
4006 if (!DBA::exists('photo', ['uid' => api_user(), 'album' => $album])) {
4007 throw new BadRequestException("album not available");
4009 // now let's update all photos to the albumname
4010 $result = DBA::update('photo', ['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4012 // return success of updating or error message
4014 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4015 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4017 throw new InternalServerErrorException("unknown error - updating in database failed");
4023 * @brief list all photos of the authenticated user
4025 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4026 * @return string|array
4028 function api_fr_photos_list($type)
4030 if (api_user() === false) {
4031 throw new ForbiddenException();
4034 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4035 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4036 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4037 intval(local_user())
4040 'image/jpeg' => 'jpg',
4041 'image/png' => 'png',
4042 'image/gif' => 'gif'
4044 $data = ['photo'=>[]];
4045 if (DBA::isResult($r)) {
4046 foreach ($r as $rr) {
4048 $photo['id'] = $rr['resource-id'];
4049 $photo['album'] = $rr['album'];
4050 $photo['filename'] = $rr['filename'];
4051 $photo['type'] = $rr['type'];
4052 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4053 $photo['created'] = $rr['created'];
4054 $photo['edited'] = $rr['edited'];
4055 $photo['desc'] = $rr['desc'];
4057 if ($type == "xml") {
4058 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4060 $photo['thumb'] = $thumb;
4061 $data['photo'][] = $photo;
4065 return api_format_data("photos", $type, $data);
4069 * @brief upload a new photo or change an existing photo
4071 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4072 * @return string|array
4074 function api_fr_photo_create_update($type)
4076 if (api_user() === false) {
4077 throw new ForbiddenException();
4080 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4081 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4082 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4083 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4084 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4085 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4086 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4087 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4088 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4090 // do several checks on input parameters
4091 // we do not allow calls without album string
4092 if ($album == null) {
4093 throw new BadRequestException("no albumname specified");
4095 // if photo_id == null --> we are uploading a new photo
4096 if ($photo_id == null) {
4099 // error if no media posted in create-mode
4100 if (!x($_FILES, 'media')) {
4102 throw new BadRequestException("no media data submitted");
4105 // album_new will be ignored in create-mode
4110 // check if photo is existing in database
4112 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4114 DBA::escape($photo_id),
4117 if (!DBA::isResult($r)) {
4118 throw new BadRequestException("photo not available");
4122 // checks on acl strings provided by clients
4123 $acl_input_error = false;
4124 $acl_input_error |= check_acl_input($allow_cid);
4125 $acl_input_error |= check_acl_input($deny_cid);
4126 $acl_input_error |= check_acl_input($allow_gid);
4127 $acl_input_error |= check_acl_input($deny_gid);
4128 if ($acl_input_error) {
4129 throw new BadRequestException("acl data invalid");
4131 // now let's upload the new media in create-mode
4132 if ($mode == "create") {
4133 $media = $_FILES['media'];
4134 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4136 // return success of updating or error message
4137 if (!is_null($data)) {
4138 return api_format_data("photo_create", $type, $data);
4140 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4144 // now let's do the changes in update-mode
4145 if ($mode == "update") {
4148 if (!is_null($desc)) {
4149 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4152 if (!is_null($album_new)) {
4153 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4156 if (!is_null($allow_cid)) {
4157 $allow_cid = trim($allow_cid);
4158 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4161 if (!is_null($deny_cid)) {
4162 $deny_cid = trim($deny_cid);
4163 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4166 if (!is_null($allow_gid)) {
4167 $allow_gid = trim($allow_gid);
4168 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4171 if (!is_null($deny_gid)) {
4172 $deny_gid = trim($deny_gid);
4173 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4177 if ($sql_extra != "") {
4178 $nothingtodo = false;
4180 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4182 DateTimeFormat::utcNow(), // update edited timestamp
4184 DBA::escape($photo_id),
4188 $nothingtodo = true;
4191 if (x($_FILES, 'media')) {
4192 $nothingtodo = false;
4193 $media = $_FILES['media'];
4194 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4195 if (!is_null($data)) {
4196 return api_format_data("photo_update", $type, $data);
4200 // return success of updating or error message
4202 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4203 return api_format_data("photo_update", $type, ['$result' => $answer]);
4206 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4207 return api_format_data("photo_update", $type, ['$result' => $answer]);
4209 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4212 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4216 * @brief delete a single photo from the database through api
4218 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4219 * @return string|array
4221 function api_fr_photo_delete($type)
4223 if (api_user() === false) {
4224 throw new ForbiddenException();
4227 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4229 // do several checks on input parameters
4230 // we do not allow calls without photo id
4231 if ($photo_id == null) {
4232 throw new BadRequestException("no photo_id specified");
4234 // check if photo is existing in database
4236 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4238 DBA::escape($photo_id)
4240 if (!DBA::isResult($r)) {
4241 throw new BadRequestException("photo not available");
4243 // now we can perform on the deletion of the photo
4244 $result = DBA::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4246 // return success of deletion or error message
4248 // retrieve the id of the parent element (the photo element)
4249 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4250 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4252 if (!DBA::isResult($photo_item)) {
4253 throw new InternalServerErrorException("problem with deleting items occured");
4255 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4256 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4257 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4259 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4260 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4262 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4268 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4270 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4271 * @return string|array
4273 function api_fr_photo_detail($type)
4275 if (api_user() === false) {
4276 throw new ForbiddenException();
4278 if (!x($_REQUEST, 'photo_id')) {
4279 throw new BadRequestException("No photo id.");
4282 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4283 $photo_id = $_REQUEST['photo_id'];
4285 // prepare json/xml output with data from database for the requested photo
4286 $data = prepare_photo_data($type, $scale, $photo_id);
4288 return api_format_data("photo_detail", $type, $data);
4293 * Updates the user’s profile image.
4295 * @brief updates the profile image for the user (either a specified profile or the default profile)
4297 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4299 * @return string|array
4300 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4302 function api_account_update_profile_image($type)
4304 if (api_user() === false) {
4305 throw new ForbiddenException();
4308 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4310 // error if image data is missing
4311 if (!x($_FILES, 'image')) {
4312 throw new BadRequestException("no media data submitted");
4315 // check if specified profile id is valid
4316 if ($profile_id != 0) {
4317 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4318 // error message if specified profile id is not in database
4319 if (!DBA::isResult($profile)) {
4320 throw new BadRequestException("profile_id not available");
4322 $is_default_profile = $profile['is-default'];
4324 $is_default_profile = 1;
4327 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4329 if (x($_FILES, 'image')) {
4330 $media = $_FILES['image'];
4331 } elseif (x($_FILES, 'media')) {
4332 $media = $_FILES['media'];
4334 // save new profile image
4335 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4338 if (is_array($media['type'])) {
4339 $filetype = $media['type'][0];
4341 $filetype = $media['type'];
4343 if ($filetype == "image/jpeg") {
4345 } elseif ($filetype == "image/png") {
4348 throw new InternalServerErrorException('Unsupported filetype');
4351 // change specified profile or all profiles to the new resource-id
4352 if ($is_default_profile) {
4353 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4354 DBA::update('photo', ['profile' => false], $condition);
4356 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype,
4357 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype];
4358 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4361 Contact::updateSelfFromUserID(api_user(), true);
4363 // Update global directory in background
4364 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4365 if ($url && strlen(Config::get('system', 'directory'))) {
4366 Worker::add(PRIORITY_LOW, "Directory", $url);
4369 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4371 // output for client
4373 return api_account_verify_credentials($type);
4375 // SaveMediaToDatabase failed for some reason
4376 throw new InternalServerErrorException("image upload failed");
4380 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4381 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4382 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4383 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4384 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4385 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4386 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4387 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4388 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4391 * Update user profile
4393 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4395 * @return array|string
4397 function api_account_update_profile($type)
4399 $local_user = api_user();
4400 $api_user = api_get_user(get_app());
4402 if (!empty($_POST['name'])) {
4403 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4404 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4405 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4406 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4409 if (isset($_POST['description'])) {
4410 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4411 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4412 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4415 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4416 // Update global directory in background
4417 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4418 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4421 return api_account_verify_credentials($type);
4424 /// @TODO move to top of file or somewhere better
4425 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4429 * @param string $acl_string
4431 function check_acl_input($acl_string)
4433 if ($acl_string == null || $acl_string == " ") {
4436 $contact_not_found = false;
4438 // split <x><y><z> into array of cid's
4439 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4441 // check for each cid if it is available on server
4442 $cid_array = $array[0];
4443 foreach ($cid_array as $cid) {
4444 $cid = str_replace("<", "", $cid);
4445 $cid = str_replace(">", "", $cid);
4446 $condition = ['id' => $cid, 'uid' => api_user()];
4447 $contact_not_found |= !DBA::exists('contact', $condition);
4449 return $contact_not_found;
4454 * @param string $mediatype
4455 * @param array $media
4456 * @param string $type
4457 * @param string $album
4458 * @param string $allow_cid
4459 * @param string $deny_cid
4460 * @param string $allow_gid
4461 * @param string $deny_gid
4462 * @param string $desc
4463 * @param integer $profile
4464 * @param boolean $visibility
4465 * @param string $photo_id
4467 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)
4475 if (is_array($media)) {
4476 if (is_array($media['tmp_name'])) {
4477 $src = $media['tmp_name'][0];
4479 $src = $media['tmp_name'];
4481 if (is_array($media['name'])) {
4482 $filename = basename($media['name'][0]);
4484 $filename = basename($media['name']);
4486 if (is_array($media['size'])) {
4487 $filesize = intval($media['size'][0]);
4489 $filesize = intval($media['size']);
4491 if (is_array($media['type'])) {
4492 $filetype = $media['type'][0];
4494 $filetype = $media['type'];
4498 if ($filetype == "") {
4499 $filetype=Image::guessType($filename);
4501 $imagedata = @getimagesize($src);
4503 $filetype = $imagedata['mime'];
4506 "File upload src: " . $src . " - filename: " . $filename .
4507 " - size: " . $filesize . " - type: " . $filetype,
4511 // check if there was a php upload error
4512 if ($filesize == 0 && $media['error'] == 1) {
4513 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4515 // check against max upload size within Friendica instance
4516 $maximagesize = Config::get('system', 'maximagesize');
4517 if ($maximagesize && ($filesize > $maximagesize)) {
4518 $formattedBytes = Strings::formatBytes($maximagesize);
4519 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4522 // create Photo instance with the data of the image
4523 $imagedata = @file_get_contents($src);
4524 $Image = new Image($imagedata, $filetype);
4525 if (!$Image->isValid()) {
4526 throw new InternalServerErrorException("unable to process image data");
4529 // check orientation of image
4530 $Image->orient($src);
4533 // check max length of images on server
4534 $max_length = Config::get('system', 'max_image_length');
4536 $max_length = MAX_IMAGE_LENGTH;
4538 if ($max_length > 0) {
4539 $Image->scaleDown($max_length);
4540 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4542 $width = $Image->getWidth();
4543 $height = $Image->getHeight();
4545 // create a new resource-id if not already provided
4546 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4548 if ($mediatype == "photo") {
4549 // upload normal image (scales 0, 1, 2)
4550 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4552 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4554 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4556 if ($width > 640 || $height > 640) {
4557 $Image->scaleDown(640);
4558 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4560 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4564 if ($width > 320 || $height > 320) {
4565 $Image->scaleDown(320);
4566 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4568 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4571 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4572 } elseif ($mediatype == "profileimage") {
4573 // upload profile image (scales 4, 5, 6)
4574 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4576 if ($width > 300 || $height > 300) {
4577 $Image->scaleDown(300);
4578 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4580 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4584 if ($width > 80 || $height > 80) {
4585 $Image->scaleDown(80);
4586 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4588 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4592 if ($width > 48 || $height > 48) {
4593 $Image->scaleDown(48);
4594 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4596 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4599 $Image->__destruct();
4600 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4603 if (isset($r) && $r) {
4604 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4605 if ($photo_id == null && $mediatype == "photo") {
4606 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4608 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4609 return prepare_photo_data($type, false, $hash);
4611 throw new InternalServerErrorException("image upload failed");
4617 * @param string $hash
4618 * @param string $allow_cid
4619 * @param string $deny_cid
4620 * @param string $allow_gid
4621 * @param string $deny_gid
4622 * @param string $filetype
4623 * @param boolean $visibility
4625 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4627 // get data about the api authenticated user
4628 $uri = Item::newURI(intval(api_user()));
4629 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4632 $arr['guid'] = System::createUUID();
4633 $arr['uid'] = intval(api_user());
4635 $arr['parent-uri'] = $uri;
4636 $arr['type'] = 'photo';
4638 $arr['resource-id'] = $hash;
4639 $arr['contact-id'] = $owner_record['id'];
4640 $arr['owner-name'] = $owner_record['name'];
4641 $arr['owner-link'] = $owner_record['url'];
4642 $arr['owner-avatar'] = $owner_record['thumb'];
4643 $arr['author-name'] = $owner_record['name'];
4644 $arr['author-link'] = $owner_record['url'];
4645 $arr['author-avatar'] = $owner_record['thumb'];
4647 $arr['allow_cid'] = $allow_cid;
4648 $arr['allow_gid'] = $allow_gid;
4649 $arr['deny_cid'] = $deny_cid;
4650 $arr['deny_gid'] = $deny_gid;
4651 $arr['visible'] = $visibility;
4655 'image/jpeg' => 'jpg',
4656 'image/png' => 'png',
4657 'image/gif' => 'gif'
4660 // adds link to the thumbnail scale photo
4661 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4662 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4665 // do the magic for storing the item in the database and trigger the federation to other contacts
4671 * @param string $type
4673 * @param string $photo_id
4677 function prepare_photo_data($type, $scale, $photo_id)
4680 $user_info = api_get_user($a);
4682 if ($user_info === false) {
4683 throw new ForbiddenException();
4686 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4687 $data_sql = ($scale === false ? "" : "data, ");
4689 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4690 // clients needs to convert this in their way for further processing
4692 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4693 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4694 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4695 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4697 intval(local_user()),
4698 DBA::escape($photo_id),
4703 'image/jpeg' => 'jpg',
4704 'image/png' => 'png',
4705 'image/gif' => 'gif'
4708 // prepare output data for photo
4709 if (DBA::isResult($r)) {
4710 $data = ['photo' => $r[0]];
4711 $data['photo']['id'] = $data['photo']['resource-id'];
4712 if ($scale !== false) {
4713 $data['photo']['data'] = base64_encode($data['photo']['data']);
4715 unset($data['photo']['datasize']); //needed only with scale param
4717 if ($type == "xml") {
4718 $data['photo']['links'] = [];
4719 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4720 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4722 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4725 $data['photo']['link'] = [];
4726 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4728 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4729 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4733 unset($data['photo']['resource-id']);
4734 unset($data['photo']['minscale']);
4735 unset($data['photo']['maxscale']);
4737 throw new NotFoundException();
4740 // retrieve item element for getting activities (like, dislike etc.) related to photo
4741 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4742 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4744 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4746 // retrieve comments on photo
4747 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4748 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4750 $statuses = Item::selectForUser(api_user(), [], $condition);
4752 // prepare output of comments
4753 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
4755 if ($type == "xml") {
4757 foreach ($commentData as $comment) {
4758 $comments[$k++ . ":comment"] = $comment;
4761 foreach ($commentData as $comment) {
4762 $comments[] = $comment;
4765 $data['photo']['friendica_comments'] = $comments;
4767 // include info if rights on photo and rights on item are mismatching
4768 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4769 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4770 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4771 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4772 $data['photo']['rights_mismatch'] = $rights_mismatch;
4779 * Similar as /mod/redir.php
4780 * redirect to 'url' after dfrn auth
4782 * Why this when there is mod/redir.php already?
4783 * This use api_user() and api_login()
4786 * c_url: url of remote contact to auth to
4787 * url: string, url to redirect after auth
4789 function api_friendica_remoteauth()
4791 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4792 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4794 if ($url === '' || $c_url === '') {
4795 throw new BadRequestException("Wrong parameters.");
4798 $c_url = Strings::normaliseLink($c_url);
4802 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4804 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
4805 throw new BadRequestException("Unknown contact");
4808 $cid = $contact['id'];
4810 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4812 if ($contact['duplex'] && $contact['issued-id']) {
4813 $orig_id = $contact['issued-id'];
4814 $dfrn_id = '1:' . $orig_id;
4816 if ($contact['duplex'] && $contact['dfrn-id']) {
4817 $orig_id = $contact['dfrn-id'];
4818 $dfrn_id = '0:' . $orig_id;
4821 $sec = Strings::getRandomHex();
4823 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4824 'sec' => $sec, 'expire' => time() + 45];
4825 DBA::insert('profile_check', $fields);
4827 Logger::log($contact['name'] . ' ' . $sec, Logger::DEBUG);
4828 $dest = ($url ? '&destination_url=' . $url : '');
4830 System::externalRedirect(
4831 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4832 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4833 . '&type=profile&sec=' . $sec . $dest
4836 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4839 * @brief Return the item shared, if the item contains only the [share] tag
4841 * @param array $item Sharer item
4842 * @return array|false Shared item or false if not a reshare
4844 function api_share_as_retweet(&$item)
4846 $body = trim($item["body"]);
4848 if (Diaspora::isReshare($body, false) === false) {
4849 if ($item['author-id'] == $item['owner-id']) {
4852 // Reshares from OStatus, ActivityPub and Twitter
4853 $reshared_item = $item;
4854 $reshared_item['owner-id'] = $reshared_item['author-id'];
4855 $reshared_item['owner-link'] = $reshared_item['author-link'];
4856 $reshared_item['owner-name'] = $reshared_item['author-name'];
4857 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
4858 return $reshared_item;
4862 /// @TODO "$1" should maybe mean '$1' ?
4863 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4865 * Skip if there is no shared message in there
4866 * we already checked this in diaspora::isReshare()
4867 * but better one more than one less...
4869 if (($body == $attributes) || empty($attributes)) {
4873 // build the fake reshared item
4874 $reshared_item = $item;
4877 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4878 if (!empty($matches[1])) {
4879 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4882 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4883 if (!empty($matches[1])) {
4884 $author = $matches[1];
4888 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4889 if (!empty($matches[1])) {
4890 $profile = $matches[1];
4893 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4894 if (!empty($matches[1])) {
4895 $profile = $matches[1];
4899 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4900 if (!empty($matches[1])) {
4901 $avatar = $matches[1];
4904 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4905 if (!empty($matches[1])) {
4906 $avatar = $matches[1];
4910 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4911 if (!empty($matches[1])) {
4912 $link = $matches[1];
4915 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4916 if (!empty($matches[1])) {
4917 $link = $matches[1];
4921 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4922 if (!empty($matches[1])) {
4923 $posted = $matches[1];
4926 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4927 if (!empty($matches[1])) {
4928 $posted = $matches[1];
4931 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4933 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4937 $reshared_item["body"] = $shared_body;
4938 $reshared_item["author-name"] = $author;
4939 $reshared_item["author-link"] = $profile;
4940 $reshared_item["author-avatar"] = $avatar;
4941 $reshared_item["plink"] = $link;
4942 $reshared_item["created"] = $posted;
4943 $reshared_item["edited"] = $posted;
4945 return $reshared_item;
4950 * @param string $profile
4952 * @return string|false
4953 * @todo remove trailing junk from profile url
4954 * @todo pump.io check has to check the website
4956 function api_get_nick($profile)
4961 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4962 DBA::escape(Strings::normaliseLink($profile))
4965 if (DBA::isResult($r)) {
4966 $nick = $r[0]["nick"];
4971 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4972 DBA::escape(Strings::normaliseLink($profile))
4975 if (DBA::isResult($r)) {
4976 $nick = $r[0]["nick"];
4981 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4982 if ($friendica != $profile) {
4988 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4989 if ($diaspora != $profile) {
4995 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4996 if ($twitter != $profile) {
5003 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5004 if ($StatusnetHost != $profile) {
5005 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5006 if ($StatusnetUser != $profile) {
5007 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5008 $user = json_decode($UserData);
5010 $nick = $user->screen_name;
5016 // To-Do: look at the page if its really a pumpio site
5017 //if (!$nick == "") {
5018 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5019 // if ($pumpio != $profile)
5021 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5034 * @param array $item
5038 function api_in_reply_to($item)
5042 $in_reply_to['status_id'] = null;
5043 $in_reply_to['user_id'] = null;
5044 $in_reply_to['status_id_str'] = null;
5045 $in_reply_to['user_id_str'] = null;
5046 $in_reply_to['screen_name'] = null;
5048 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5049 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5050 if (DBA::isResult($parent)) {
5051 $in_reply_to['status_id'] = intval($parent['id']);
5053 $in_reply_to['status_id'] = intval($item['parent']);
5056 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5058 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5059 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5061 if (DBA::isResult($parent)) {
5062 if ($parent['author-nick'] == "") {
5063 $parent['author-nick'] = api_get_nick($parent['author-link']);
5066 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5067 $in_reply_to['user_id'] = intval($parent['author-id']);
5068 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5071 // There seems to be situation, where both fields are identical:
5072 // https://github.com/friendica/friendica/issues/1010
5073 // This is a bugfix for that.
5074 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5075 Logger::log('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], Logger::DEBUG);
5076 $in_reply_to['status_id'] = null;
5077 $in_reply_to['user_id'] = null;
5078 $in_reply_to['status_id_str'] = null;
5079 $in_reply_to['user_id_str'] = null;
5080 $in_reply_to['screen_name'] = null;
5084 return $in_reply_to;
5089 * @param string $text
5093 function api_clean_plain_items($text)
5095 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5097 $text = BBCode::cleanPictureLinks($text);
5098 $URLSearchString = "^\[\]";
5100 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5102 if ($include_entities == "true") {
5103 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5106 // Simplify "attachment" element
5107 $text = api_clean_attachments($text);
5113 * @brief Removes most sharing information for API text export
5115 * @param string $body The original body
5117 * @return string Cleaned body
5119 function api_clean_attachments($body)
5121 $data = BBCode::getAttachmentData($body);
5128 if (isset($data["text"])) {
5129 $body = $data["text"];
5131 if (($body == "") && isset($data["title"])) {
5132 $body = $data["title"];
5134 if (isset($data["url"])) {
5135 $body .= "\n".$data["url"];
5137 $body .= $data["after"];
5144 * @param array $contacts
5148 function api_best_nickname(&$contacts)
5152 if (count($contacts) == 0) {
5156 foreach ($contacts as $contact) {
5157 if ($contact["network"] == "") {
5158 $contact["network"] = "dfrn";
5159 $best_contact = [$contact];
5163 if (sizeof($best_contact) == 0) {
5164 foreach ($contacts as $contact) {
5165 if ($contact["network"] == "dfrn") {
5166 $best_contact = [$contact];
5171 if (sizeof($best_contact) == 0) {
5172 foreach ($contacts as $contact) {
5173 if ($contact["network"] == "dspr") {
5174 $best_contact = [$contact];
5179 if (sizeof($best_contact) == 0) {
5180 foreach ($contacts as $contact) {
5181 if ($contact["network"] == "stat") {
5182 $best_contact = [$contact];
5187 if (sizeof($best_contact) == 0) {
5188 foreach ($contacts as $contact) {
5189 if ($contact["network"] == "pump") {
5190 $best_contact = [$contact];
5195 if (sizeof($best_contact) == 0) {
5196 foreach ($contacts as $contact) {
5197 if ($contact["network"] == "twit") {
5198 $best_contact = [$contact];
5203 if (sizeof($best_contact) == 1) {
5204 $contacts = $best_contact;
5206 $contacts = [$contacts[0]];
5211 * Return all or a specified group of the user with the containing contacts.
5213 * @param string $type Return type (atom, rss, xml, json)
5215 * @return array|string
5217 function api_friendica_group_show($type)
5221 if (api_user() === false) {
5222 throw new ForbiddenException();
5226 $user_info = api_get_user($a);
5227 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5228 $uid = $user_info['uid'];
5230 // get data of the specified group id or all groups if not specified
5233 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5237 // error message if specified gid is not in database
5238 if (!DBA::isResult($r)) {
5239 throw new BadRequestException("gid not available");
5243 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5248 // loop through all groups and retrieve all members for adding data in the user array
5250 foreach ($r as $rr) {
5251 $members = Contact::getByGroupId($rr['id']);
5254 if ($type == "xml") {
5255 $user_element = "users";
5257 foreach ($members as $member) {
5258 $user = api_get_user($a, $member['nurl']);
5259 $users[$k++.":user"] = $user;
5262 $user_element = "user";
5263 foreach ($members as $member) {
5264 $user = api_get_user($a, $member['nurl']);
5268 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5270 return api_format_data("groups", $type, ['group' => $grps]);
5272 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5276 * Delete the specified group of the user.
5278 * @param string $type Return type (atom, rss, xml, json)
5280 * @return array|string
5282 function api_friendica_group_delete($type)
5286 if (api_user() === false) {
5287 throw new ForbiddenException();
5291 $user_info = api_get_user($a);
5292 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5293 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5294 $uid = $user_info['uid'];
5296 // error if no gid specified
5297 if ($gid == 0 || $name == "") {
5298 throw new BadRequestException('gid or name not specified');
5301 // get data of the specified group id
5303 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5307 // error message if specified gid is not in database
5308 if (!DBA::isResult($r)) {
5309 throw new BadRequestException('gid not available');
5312 // get data of the specified group id and group name
5314 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5319 // error message if specified gid is not in database
5320 if (!DBA::isResult($rname)) {
5321 throw new BadRequestException('wrong group name');
5325 $ret = Group::removeByName($uid, $name);
5328 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5329 return api_format_data("group_delete", $type, ['result' => $success]);
5331 throw new BadRequestException('other API error');
5334 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5339 * @param string $type Return type (atom, rss, xml, json)
5341 * @return array|string
5342 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5344 function api_lists_destroy($type)
5348 if (api_user() === false) {
5349 throw new ForbiddenException();
5353 $user_info = api_get_user($a);
5354 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5355 $uid = $user_info['uid'];
5357 // error if no gid specified
5359 throw new BadRequestException('gid not specified');
5362 // get data of the specified group id
5363 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5364 // error message if specified gid is not in database
5366 throw new BadRequestException('gid not available');
5369 if (Group::remove($gid)) {
5371 'name' => $group['name'],
5372 'id' => intval($gid),
5373 'id_str' => (string) $gid,
5374 'user' => $user_info
5377 return api_format_data("lists", $type, ['lists' => $list]);
5380 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5383 * Add a new group to the database.
5385 * @param string $name Group name
5386 * @param int $uid User ID
5387 * @param array $users List of users to add to the group
5391 function group_create($name, $uid, $users = [])
5393 // error if no name specified
5395 throw new BadRequestException('group name not specified');
5398 // get data of the specified group name
5400 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5404 // error message if specified group name already exists
5405 if (DBA::isResult($rname)) {
5406 throw new BadRequestException('group name already exists');
5409 // check if specified group name is a deleted group
5411 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5415 // error message if specified group name already exists
5416 if (DBA::isResult($rname)) {
5417 $reactivate_group = true;
5421 $ret = Group::create($uid, $name);
5423 $gid = Group::getIdByName($uid, $name);
5425 throw new BadRequestException('other API error');
5429 $erroraddinguser = false;
5431 foreach ($users as $user) {
5432 $cid = $user['cid'];
5433 // check if user really exists as contact
5435 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5439 if (count($contact)) {
5440 Group::addMember($gid, $cid);
5442 $erroraddinguser = true;
5443 $errorusers[] = $cid;
5447 // return success message incl. missing users in array
5448 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5450 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5454 * Create the specified group with the posted array of contacts.
5456 * @param string $type Return type (atom, rss, xml, json)
5458 * @return array|string
5460 function api_friendica_group_create($type)
5464 if (api_user() === false) {
5465 throw new ForbiddenException();
5469 $user_info = api_get_user($a);
5470 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5471 $uid = $user_info['uid'];
5472 $json = json_decode($_POST['json'], true);
5473 $users = $json['user'];
5475 $success = group_create($name, $uid, $users);
5477 return api_format_data("group_create", $type, ['result' => $success]);
5479 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5482 * Create a new group.
5484 * @param string $type Return type (atom, rss, xml, json)
5486 * @return array|string
5487 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5489 function api_lists_create($type)
5493 if (api_user() === false) {
5494 throw new ForbiddenException();
5498 $user_info = api_get_user($a);
5499 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5500 $uid = $user_info['uid'];
5502 $success = group_create($name, $uid);
5503 if ($success['success']) {
5505 'name' => $success['name'],
5506 'id' => intval($success['gid']),
5507 'id_str' => (string) $success['gid'],
5508 'user' => $user_info
5511 return api_format_data("lists", $type, ['lists'=>$grp]);
5514 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5517 * Update the specified group with the posted array of contacts.
5519 * @param string $type Return type (atom, rss, xml, json)
5521 * @return array|string
5523 function api_friendica_group_update($type)
5527 if (api_user() === false) {
5528 throw new ForbiddenException();
5532 $user_info = api_get_user($a);
5533 $uid = $user_info['uid'];
5534 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5535 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5536 $json = json_decode($_POST['json'], true);
5537 $users = $json['user'];
5539 // error if no name specified
5541 throw new BadRequestException('group name not specified');
5544 // error if no gid specified
5546 throw new BadRequestException('gid not specified');
5550 $members = Contact::getByGroupId($gid);
5551 foreach ($members as $member) {
5552 $cid = $member['id'];
5553 foreach ($users as $user) {
5554 $found = ($user['cid'] == $cid ? true : false);
5556 if (!isset($found) || !$found) {
5557 Group::removeMemberByName($uid, $name, $cid);
5562 $erroraddinguser = false;
5564 foreach ($users as $user) {
5565 $cid = $user['cid'];
5566 // check if user really exists as contact
5568 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5573 if (count($contact)) {
5574 Group::addMember($gid, $cid);
5576 $erroraddinguser = true;
5577 $errorusers[] = $cid;
5581 // return success message incl. missing users in array
5582 $status = ($erroraddinguser ? "missing user" : "ok");
5583 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5584 return api_format_data("group_update", $type, ['result' => $success]);
5587 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5590 * Update information about a group.
5592 * @param string $type Return type (atom, rss, xml, json)
5594 * @return array|string
5595 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5597 function api_lists_update($type)
5601 if (api_user() === false) {
5602 throw new ForbiddenException();
5606 $user_info = api_get_user($a);
5607 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5608 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5609 $uid = $user_info['uid'];
5611 // error if no gid specified
5613 throw new BadRequestException('gid not specified');
5616 // get data of the specified group id
5617 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5618 // error message if specified gid is not in database
5620 throw new BadRequestException('gid not available');
5623 if (Group::update($gid, $name)) {
5626 'id' => intval($gid),
5627 'id_str' => (string) $gid,
5628 'user' => $user_info
5631 return api_format_data("lists", $type, ['lists' => $list]);
5635 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5639 * @param string $type Return type (atom, rss, xml, json)
5641 * @return array|string
5643 function api_friendica_activity($type)
5647 if (api_user() === false) {
5648 throw new ForbiddenException();
5650 $verb = strtolower($a->argv[3]);
5651 $verb = preg_replace("|\..*$|", "", $verb);
5653 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5655 $res = Item::performLike($id, $verb);
5658 if ($type == "xml") {
5663 return api_format_data('ok', $type, ['ok' => $ok]);
5665 throw new BadRequestException('Error adding activity');
5669 /// @TODO move to top of file or somewhere better
5670 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5671 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5672 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5673 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5674 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5675 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5676 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5677 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5678 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5679 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5682 * @brief Returns notifications
5684 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5685 * @return string|array
5687 function api_friendica_notification($type)
5691 if (api_user() === false) {
5692 throw new ForbiddenException();
5695 throw new BadRequestException("Invalid argument count");
5697 $nm = new NotificationsManager();
5699 $notes = $nm->getAll([], "+seen -date", 50);
5701 if ($type == "xml") {
5703 if (!empty($notes)) {
5704 foreach ($notes as $note) {
5705 $xmlnotes[] = ["@attributes" => $note];
5712 return api_format_data("notes", $type, ['note' => $notes]);
5716 * POST request with 'id' param as notification id
5718 * @brief Set notification as seen and returns associated item (if possible)
5720 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5721 * @return string|array
5723 function api_friendica_notification_seen($type)
5726 $user_info = api_get_user($a);
5728 if (api_user() === false || $user_info === false) {
5729 throw new ForbiddenException();
5732 throw new BadRequestException("Invalid argument count");
5735 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5737 $nm = new NotificationsManager();
5738 $note = $nm->getByID($id);
5739 if (is_null($note)) {
5740 throw new BadRequestException("Invalid argument");
5743 $nm->setSeen($note);
5744 if ($note['otype']=='item') {
5745 // would be really better with an ItemsManager and $im->getByID() :-P
5746 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5747 if (DBA::isResult($item)) {
5748 // we found the item, return it to the user
5749 $ret = api_format_items([$item], $user_info, false, $type);
5750 $data = ['status' => $ret];
5751 return api_format_data("status", $type, $data);
5753 // the item can't be found, but we set the note as seen, so we count this as a success
5755 return api_format_data('result', $type, ['result' => "success"]);
5758 /// @TODO move to top of file or somewhere better
5759 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5760 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5763 * @brief update a direct_message to seen state
5765 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5766 * @return string|array (success result=ok, error result=error with error message)
5768 function api_friendica_direct_messages_setseen($type)
5771 if (api_user() === false) {
5772 throw new ForbiddenException();
5776 $user_info = api_get_user($a);
5777 $uid = $user_info['uid'];
5778 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5780 // return error if id is zero
5782 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5783 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5786 // error message if specified id is not in database
5787 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5788 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5789 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5792 // update seen indicator
5793 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5797 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5798 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5800 $answer = ['result' => 'error', 'message' => 'unknown error'];
5801 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5805 /// @TODO move to top of file or somewhere better
5806 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5809 * @brief search for direct_messages containing a searchstring through api
5811 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5812 * @param string $box
5813 * @return string|array (success: success=true if found and search_result contains found messages,
5814 * success=false if nothing was found, search_result='nothing found',
5815 * error: result=error with error message)
5817 function api_friendica_direct_messages_search($type, $box = "")
5821 if (api_user() === false) {
5822 throw new ForbiddenException();
5826 $user_info = api_get_user($a);
5827 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5828 $uid = $user_info['uid'];
5830 // error if no searchstring specified
5831 if ($searchstring == "") {
5832 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5833 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5836 // get data for the specified searchstring
5838 "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",
5840 DBA::escape('%'.$searchstring.'%')
5843 $profile_url = $user_info["url"];
5845 // message if nothing was found
5846 if (!DBA::isResult($r)) {
5847 $success = ['success' => false, 'search_results' => 'problem with query'];
5848 } elseif (count($r) == 0) {
5849 $success = ['success' => false, 'search_results' => 'nothing found'];
5852 foreach ($r as $item) {
5853 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5854 $recipient = $user_info;
5855 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5856 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5857 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5858 $sender = $user_info;
5861 if (isset($recipient) && isset($sender)) {
5862 $ret[] = api_format_messages($item, $recipient, $sender);
5865 $success = ['success' => true, 'search_results' => $ret];
5868 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5871 /// @TODO move to top of file or somewhere better
5872 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5875 * @brief return data of all the profiles a user has to the client
5877 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5878 * @return string|array
5880 function api_friendica_profile_show($type)
5884 if (api_user() === false) {
5885 throw new ForbiddenException();
5889 $profile_id = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5891 // retrieve general information about profiles for user
5892 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5893 $directory = Config::get('system', 'directory');
5895 // get data of the specified profile id or all profiles of the user if not specified
5896 if ($profile_id != 0) {
5898 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5903 // error message if specified gid is not in database
5904 if (!DBA::isResult($r)) {
5905 throw new BadRequestException("profile_id not available");
5909 "SELECT * FROM `profile` WHERE `uid` = %d",
5913 // loop through all returned profiles and retrieve data and users
5916 foreach ($r as $rr) {
5917 $profile = api_format_items_profiles($rr);
5919 // select all users from contact table, loop and prepare standard return for user data
5922 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5927 foreach ($nurls as $nurl) {
5928 $user = api_get_user($a, $nurl['nurl']);
5929 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5931 $profile['users'] = $users;
5933 // add prepared profile data to array for final return
5934 if ($type == "xml") {
5935 $profiles[$k++ . ":profile"] = $profile;
5937 $profiles[] = $profile;
5941 // return settings, authenticated user and profiles data
5942 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
5944 $result = ['multi_profiles' => $multi_profiles ? true : false,
5945 'global_dir' => $directory,
5946 'friendica_owner' => api_get_user($a, $self['nurl']),
5947 'profiles' => $profiles];
5948 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5950 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5953 * Returns a list of saved searches.
5955 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5957 * @param string $type Return format: json or xml
5959 * @return string|array
5961 function api_saved_searches_list($type)
5963 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
5966 while ($term = $terms->fetch()) {
5968 'created_at' => api_date(time()),
5969 'id' => intval($term['id']),
5970 'id_str' => $term['id'],
5971 'name' => $term['term'],
5973 'query' => $term['term']
5979 return api_format_data("terms", $type, ['terms' => $result]);
5982 /// @TODO move to top of file or somewhere better
5983 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5986 @TODO Maybe open to implement?
5988 [pagename] => api/1.1/statuses/lookup.json
5989 [id] => 605138389168451584
5990 [include_cards] => true
5991 [cards_platform] => Android-12
5992 [include_entities] => true
5993 [include_my_retweet] => 1
5995 [include_reply_count] => true
5996 [include_descendent_reply_count] => true
6000 Not implemented by now:
6001 statuses/retweets_of_me
6006 account/update_location
6007 account/update_profile_background_image
6010 friendica/profile/update
6011 friendica/profile/create
6012 friendica/profile/delete
6014 Not implemented in status.net:
6015 statuses/retweeted_to_me
6016 statuses/retweeted_by_me
6017 direct_messages/destroy
6019 account/update_delivery_device
6020 notifications/follow