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\XML;
48 require_once 'include/conversation.php';
49 require_once 'mod/share.php';
50 require_once 'mod/item.php';
51 require_once 'mod/wall_upload.php';
53 define('API_METHOD_ANY', '*');
54 define('API_METHOD_GET', 'GET');
55 define('API_METHOD_POST', 'POST,PUT');
56 define('API_METHOD_DELETE', 'POST,DELETE');
62 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
63 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
64 * into a page, and visitors will post something without noticing it).
66 * @brief Auth API user
70 if (x($_SESSION, 'allow_api')) {
78 * Clients can send 'source' parameter to be show in post metadata
79 * as "sent via <source>".
80 * Some clients doesn't send a source param, we support ones we know
83 * @brief Get source name from API client
86 * Client source name, default to "api" if unset/unknown
90 if (requestdata('source')) {
91 return requestdata('source');
94 // Support for known clients that doesn't send a source name
95 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
96 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
100 Logger::log("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], Logger::DEBUG);
102 Logger::log("Empty user-agent", Logger::DEBUG);
109 * @brief Format date for API
111 * @param string $str Source date, as UTC
112 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
114 function api_date($str)
116 // Wed May 23 06:01:13 +0000 2007
117 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
121 * Register a function to be the endpoint for defined API path.
123 * @brief Register API endpoint
125 * @param string $path API URL path, relative to System::baseUrl()
126 * @param string $func Function name to call on path request
127 * @param bool $auth API need logged user
128 * @param string $method HTTP method reqiured to call this endpoint.
129 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
130 * Default to API_METHOD_ANY
132 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
142 // Workaround for hotot
143 $path = str_replace("api/", "api/1.1/", $path);
153 * Log in user via OAuth1 or Simple HTTP Auth.
154 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
156 * @brief Login API user
158 * @param object $a App
159 * @hook 'authenticate'
161 * 'username' => username from login form
162 * 'password' => password from login form
163 * 'authenticated' => return status,
164 * 'user_record' => return authenticated user record
166 * array $user logged user record
168 function api_login(App $a)
170 $oauth1 = new FKOAuth1();
173 $request = OAuthRequest::from_request();
174 list($consumer, $token) = $oauth1->verify_request($request);
175 if (!is_null($token)) {
176 $oauth1->loginUser($token->uid);
177 Addon::callHooks('logged_in', $a->user);
180 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
181 var_dump($consumer, $token);
183 } catch (Exception $e) {
187 // workaround for HTTP-auth in CGI mode
188 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
189 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
190 if (strlen($userpass)) {
191 list($name, $password) = explode(':', $userpass);
192 $_SERVER['PHP_AUTH_USER'] = $name;
193 $_SERVER['PHP_AUTH_PW'] = $password;
197 if (!x($_SERVER, 'PHP_AUTH_USER')) {
198 Logger::log('API_login: ' . print_r($_SERVER, true), Logger::DEBUG);
199 header('WWW-Authenticate: Basic realm="Friendica"');
200 throw new UnauthorizedException("This API requires login");
203 $user = defaults($_SERVER, 'PHP_AUTH_USER', '');
204 $password = defaults($_SERVER, 'PHP_AUTH_PW', '');
206 // allow "user@server" login (but ignore 'server' part)
207 $at = strstr($user, "@", true);
212 // next code from mod/auth.php. needs better solution
216 'username' => trim($user),
217 'password' => trim($password),
218 'authenticated' => 0,
219 'user_record' => null,
223 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
224 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
225 * and later addons should not interfere with an earlier one that succeeded.
227 Addon::callHooks('authenticate', $addon_auth);
229 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
230 $record = $addon_auth['user_record'];
232 $user_id = User::authenticate(trim($user), trim($password));
233 if ($user_id !== false) {
234 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
238 if (!DBA::isResult($record)) {
239 Logger::log('API_login failure: ' . print_r($_SERVER, true), Logger::DEBUG);
240 header('WWW-Authenticate: Basic realm="Friendica"');
241 //header('HTTP/1.0 401 Unauthorized');
242 //die('This api requires login');
243 throw new UnauthorizedException("This API requires login");
246 Authentication::setAuthenticatedSessionForUser($record);
248 $_SESSION["allow_api"] = true;
250 Addon::callHooks('logged_in', $a->user);
254 * API endpoints can define which HTTP method to accept when called.
255 * This function check the current HTTP method agains endpoint
258 * @brief Check HTTP method of called API
260 * @param string $method Required methods, uppercase, separated by comma
263 function api_check_method($method)
265 if ($method == "*") {
268 return (stripos($method, defaults($_SERVER, 'REQUEST_METHOD', 'GET')) !== false);
272 * Authenticate user, call registered API function, set HTTP headers
274 * @brief Main API entry point
276 * @param object $a App
277 * @return string|array API call result
279 function api_call(App $a)
281 global $API, $called_api;
284 if (strpos($a->query_string, ".xml") > 0) {
287 if (strpos($a->query_string, ".json") > 0) {
290 if (strpos($a->query_string, ".rss") > 0) {
293 if (strpos($a->query_string, ".atom") > 0) {
298 foreach ($API as $p => $info) {
299 if (strpos($a->query_string, $p) === 0) {
300 if (!api_check_method($info['method'])) {
301 throw new MethodNotAllowedException();
304 $called_api = explode("/", $p);
305 //unset($_SERVER['PHP_AUTH_USER']);
307 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
308 if (!empty($info['auth']) && api_user() === false) {
312 Logger::log('API call for ' . $a->user['username'] . ': ' . $a->query_string);
313 Logger::log('API parameters: ' . print_r($_REQUEST, true));
315 $stamp = microtime(true);
316 $return = call_user_func($info['func'], $type);
317 $duration = (float) (microtime(true) - $stamp);
318 Logger::log("API call duration: " . round($duration, 2) . "\t" . $a->query_string, Logger::DEBUG);
320 if (Config::get("system", "profiler")) {
321 $duration = microtime(true)-$a->performance["start"];
323 /// @TODO round() really everywhere?
325 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
326 "Database: %s/%s, Cache %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
327 round($a->performance["database"] - $a->performance["database_write"], 3),
328 round($a->performance["database_write"], 3),
329 round($a->performance["cache"], 3),
330 round($a->performance["cache_write"], 3),
331 round($a->performance["network"], 2),
332 round($a->performance["file"], 2),
333 round($duration - ($a->performance["database"]
334 + $a->performance["cache"] + $a->performance["cache_write"]
335 + $a->performance["network"] + $a->performance["file"]), 2),
341 if (Config::get("rendertime", "callstack")) {
342 $o = "Database Read:\n";
343 foreach ($a->callstack["database"] as $func => $time) {
344 $time = round($time, 3);
346 $o .= $func . ": " . $time . "\n";
349 $o .= "\nDatabase Write:\n";
350 foreach ($a->callstack["database_write"] as $func => $time) {
351 $time = round($time, 3);
353 $o .= $func . ": " . $time . "\n";
357 $o = "Cache Read:\n";
358 foreach ($a->callstack["cache"] as $func => $time) {
359 $time = round($time, 3);
361 $o .= $func . ": " . $time . "\n";
364 $o .= "\nCache Write:\n";
365 foreach ($a->callstack["cache_write"] as $func => $time) {
366 $time = round($time, 3);
368 $o .= $func . ": " . $time . "\n";
372 $o .= "\nNetwork:\n";
373 foreach ($a->callstack["network"] as $func => $time) {
374 $time = round($time, 3);
376 $o .= $func . ": " . $time . "\n";
379 Logger::log($o, Logger::DEBUG);
383 if (false === $return) {
385 * api function returned false withour throw an
386 * exception. This should not happend, throw a 500
388 throw new InternalServerErrorException();
393 header("Content-Type: text/xml");
396 header("Content-Type: application/json");
397 $json = json_encode(end($return));
398 if (x($_GET, 'callback')) {
399 $json = $_GET['callback'] . "(" . $json . ")";
404 header("Content-Type: application/rss+xml");
405 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
408 header("Content-Type: application/atom+xml");
409 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
416 Logger::log('API call not implemented: ' . $a->query_string);
417 throw new NotImplementedException();
418 } catch (HTTPException $e) {
419 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
420 return api_error($type, $e);
425 * @brief Format API error string
427 * @param string $type Return type (xml, json, rss, as)
428 * @param object $e HTTPException Error object
429 * @return string|array error message formatted as $type
431 function api_error($type, $e)
435 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
436 /// @TODO: https://dev.twitter.com/overview/api/response-codes
438 $error = ["error" => $error,
439 "code" => $e->httpcode . " " . $e->httpdesc,
440 "request" => $a->query_string];
442 $return = api_format_data('status', $type, ['status' => $error]);
446 header("Content-Type: text/xml");
449 header("Content-Type: application/json");
450 $return = json_encode($return);
453 header("Content-Type: application/rss+xml");
456 header("Content-Type: application/atom+xml");
464 * @brief Set values for RSS template
467 * @param array $arr Array to be passed to template
468 * @param array $user_info User info
470 * @todo find proper type-hints
472 function api_rss_extra(App $a, $arr, $user_info)
474 if (is_null($user_info)) {
475 $user_info = api_get_user($a);
478 $arr['$user'] = $user_info;
480 'alternate' => $user_info['url'],
481 'self' => System::baseUrl() . "/" . $a->query_string,
482 'base' => System::baseUrl(),
483 'updated' => api_date(null),
484 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
485 'language' => $user_info['lang'],
486 'logo' => System::baseUrl() . "/images/friendica-32.png",
494 * @brief Unique contact to contact url.
496 * @param int $id Contact id
497 * @return bool|string
498 * Contact url or False if contact id is unknown
500 function api_unique_id_to_nurl($id)
502 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
504 if (DBA::isResult($r)) {
512 * @brief Get user info array.
514 * @param object $a App
515 * @param int|string $contact_id Contact ID or URL
517 function api_get_user(App $a, $contact_id = null)
525 Logger::log("api_get_user: Fetching user data for user ".$contact_id, Logger::DEBUG);
527 // Searching for contact URL
528 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
529 $user = DBA::escape(normalise_link($contact_id));
531 $extra_query = "AND `contact`.`nurl` = '%s' ";
532 if (api_user() !== false) {
533 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
537 // Searching for contact id with uid = 0
538 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
539 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
542 throw new BadRequestException("User ID ".$contact_id." not found.");
546 $extra_query = "AND `contact`.`nurl` = '%s' ";
547 if (api_user() !== false) {
548 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
552 if (is_null($user) && x($_GET, 'user_id')) {
553 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
556 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
560 $extra_query = "AND `contact`.`nurl` = '%s' ";
561 if (api_user() !== false) {
562 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
565 if (is_null($user) && x($_GET, 'screen_name')) {
566 $user = DBA::escape($_GET['screen_name']);
567 $extra_query = "AND `contact`.`nick` = '%s' ";
568 if (api_user() !== false) {
569 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
573 if (is_null($user) && x($_GET, 'profileurl')) {
574 $user = DBA::escape(normalise_link($_GET['profileurl']));
575 $extra_query = "AND `contact`.`nurl` = '%s' ";
576 if (api_user() !== false) {
577 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
581 // $called_api is the API path exploded on / and is expected to have at least 2 elements
582 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
583 $argid = count($called_api);
584 if (!empty($a->argv[$argid])) {
585 $data = explode(".", $a->argv[$argid]);
586 if (count($data) > 1) {
587 list($user, $null) = $data;
590 if (is_numeric($user)) {
591 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
595 $extra_query = "AND `contact`.`nurl` = '%s' ";
596 if (api_user() !== false) {
597 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
601 $user = DBA::escape($user);
602 $extra_query = "AND `contact`.`nick` = '%s' ";
603 if (api_user() !== false) {
604 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
609 Logger::log("api_get_user: user ".$user, Logger::DEBUG);
612 if (api_user() === false) {
616 $user = $_SESSION['uid'];
617 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
621 Logger::log('api_user: ' . $extra_query . ', user: ' . $user);
625 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
631 // Selecting the id by priority, friendica first
632 if (is_array($uinfo)) {
633 api_best_nickname($uinfo);
636 // if the contact wasn't found, fetch it from the contacts with uid = 0
637 if (!DBA::isResult($uinfo)) {
639 throw new BadRequestException("User not found.");
642 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => normalise_link($url)]);
644 if (DBA::isResult($contact)) {
645 $network_name = ContactSelector::networkToName($contact['network'], $contact['url']);
647 // If no nick where given, extract it from the address
648 if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
649 $contact['nick'] = api_get_nick($contact["url"]);
653 'id' => $contact["id"],
654 'id_str' => (string) $contact["id"],
655 'name' => $contact["name"],
656 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
657 'location' => ($contact["location"] != "") ? $contact["location"] : $network_name,
658 'description' => $contact["about"],
659 'profile_image_url' => $contact["micro"],
660 'profile_image_url_https' => $contact["micro"],
661 'profile_image_url_profile_size' => $contact["thumb"],
662 'profile_image_url_large' => $contact["photo"],
663 'url' => $contact["url"],
664 'protected' => false,
665 'followers_count' => 0,
666 'friends_count' => 0,
668 'created_at' => api_date($contact["created"]),
669 'favourites_count' => 0,
671 'time_zone' => 'UTC',
672 'geo_enabled' => false,
674 'statuses_count' => 0,
676 'contributors_enabled' => false,
677 'is_translator' => false,
678 'is_translation_enabled' => false,
679 'following' => false,
680 'follow_request_sent' => false,
681 'statusnet_blocking' => false,
682 'notifications' => false,
683 'statusnet_profile_url' => $contact["url"],
685 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
686 'pid' => Contact::getIdForURL($contact["url"], 0, true),
688 'network' => $contact["network"],
693 throw new BadRequestException("User ".$url." not found.");
697 if ($uinfo[0]['self']) {
698 if ($uinfo[0]['network'] == "") {
699 $uinfo[0]['network'] = Protocol::DFRN;
702 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
703 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
710 // Add a nick if it isn't present there
711 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
712 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
715 $network_name = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
717 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
719 if (!empty($profile['about'])) {
720 $description = $profile['about'];
722 $description = $uinfo[0]["about"];
725 if (!empty($usr['default-location'])) {
726 $location = $usr['default-location'];
727 } elseif (!empty($uinfo[0]["location"])) {
728 $location = $uinfo[0]["location"];
730 $location = $network_name;
734 'id' => intval($pcontact_id),
735 'id_str' => (string) intval($pcontact_id),
736 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
737 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
738 'location' => $location,
739 'description' => $description,
740 'profile_image_url' => $uinfo[0]['micro'],
741 'profile_image_url_https' => $uinfo[0]['micro'],
742 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
743 'profile_image_url_large' => $uinfo[0]["photo"],
744 'url' => $uinfo[0]['url'],
745 'protected' => false,
746 'followers_count' => intval($countfollowers),
747 'friends_count' => intval($countfriends),
749 'created_at' => api_date($uinfo[0]['created']),
750 'favourites_count' => intval($starred),
752 'time_zone' => 'UTC',
753 'geo_enabled' => false,
755 'statuses_count' => intval($countitems),
757 'contributors_enabled' => false,
758 'is_translator' => false,
759 'is_translation_enabled' => false,
760 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
761 'follow_request_sent' => false,
762 'statusnet_blocking' => false,
763 'notifications' => false,
765 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
766 'statusnet_profile_url' => $uinfo[0]['url'],
767 'uid' => intval($uinfo[0]['uid']),
768 'cid' => intval($uinfo[0]['cid']),
769 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
770 'self' => $uinfo[0]['self'],
771 'network' => $uinfo[0]['network'],
774 // If this is a local user and it uses Frio, we can get its color preferences.
776 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
777 if ($theme_info['theme'] === 'frio') {
778 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
780 if ($schema && ($schema != '---')) {
781 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
782 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
783 require_once $schemefile;
786 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
787 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
788 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
790 if (empty($nav_bg)) {
793 if (empty($link_color)) {
794 $link_color = "#6fdbe8";
796 if (empty($bgcolor)) {
797 $bgcolor = "#ededed";
800 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
801 $ret['profile_link_color'] = str_replace('#', '', $link_color);
802 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
810 * @brief return api-formatted array for item's author and owner
812 * @param object $a App
813 * @param array $item item from db
814 * @return array(array:author, array:owner)
816 function api_item_get_user(App $a, $item)
818 $status_user = api_get_user($a, defaults($item, 'author-id', null));
820 $status_user["protected"] = defaults($item, 'private', 0);
822 if (defaults($item, 'thr-parent', '') == defaults($item, 'uri', '')) {
823 $owner_user = api_get_user($a, defaults($item, 'owner-id', null));
825 $owner_user = $status_user;
828 return ([$status_user, $owner_user]);
832 * @brief walks recursively through an array with the possibility to change value and key
834 * @param array $array The array to walk through
835 * @param string $callback The callback function
837 * @return array the transformed array
839 function api_walk_recursive(array &$array, callable $callback)
843 foreach ($array as $k => $v) {
845 if ($callback($v, $k)) {
846 $new_array[$k] = api_walk_recursive($v, $callback);
849 if ($callback($v, $k)) {
860 * @brief Callback function to transform the array in an array that can be transformed in a XML file
862 * @param mixed $item Array item value
863 * @param string $key Array key
865 * @return boolean Should the array item be deleted?
867 function api_reformat_xml(&$item, &$key)
869 if (is_bool($item)) {
870 $item = ($item ? "true" : "false");
873 if (substr($key, 0, 10) == "statusnet_") {
874 $key = "statusnet:".substr($key, 10);
875 } elseif (substr($key, 0, 10) == "friendica_") {
876 $key = "friendica:".substr($key, 10);
878 /// @TODO old-lost code?
880 // $key = "default:".$key;
886 * @brief Creates the XML from a JSON style array
888 * @param array $data JSON style array
889 * @param string $root_element Name of the root element
891 * @return string The XML data
893 function api_create_xml(array $data, $root_element)
895 $childname = key($data);
896 $data2 = array_pop($data);
898 $namespaces = ["" => "http://api.twitter.com",
899 "statusnet" => "http://status.net/schema/api/1/",
900 "friendica" => "http://friendi.ca/schema/api/1/",
901 "georss" => "http://www.georss.org/georss"];
903 /// @todo Auto detection of needed namespaces
904 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
908 if (is_array($data2)) {
910 api_walk_recursive($data2, "api_reformat_xml");
916 foreach ($data2 as $item) {
917 $data4[$i++ . ":" . $childname] = $item;
924 $data3 = [$root_element => $data2];
926 $ret = XML::fromArray($data3, $xml, false, $namespaces);
931 * @brief Formats the data according to the data type
933 * @param string $root_element Name of the root element
934 * @param string $type Return type (atom, rss, xml, json)
935 * @param array $data JSON style array
937 * @return (string|array) XML data or JSON data
939 function api_format_data($root_element, $type, $data)
945 $ret = api_create_xml($data, $root_element);
961 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
962 * returns a 401 status code and an error message if not.
963 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
965 * @param string $type Return type (atom, rss, xml, json)
967 function api_account_verify_credentials($type)
972 if (api_user() === false) {
973 throw new ForbiddenException();
976 unset($_REQUEST["user_id"]);
977 unset($_GET["user_id"]);
979 unset($_REQUEST["screen_name"]);
980 unset($_GET["screen_name"]);
982 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
984 $user_info = api_get_user($a);
986 // "verified" isn't used here in the standard
987 unset($user_info["verified"]);
989 // - Adding last status
991 $user_info["status"] = api_status_show("raw");
992 if (!count($user_info["status"])) {
993 unset($user_info["status"]);
995 unset($user_info["status"]["user"]);
999 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1000 unset($user_info["uid"]);
1001 unset($user_info["self"]);
1003 return api_format_data("user", $type, ['user' => $user_info]);
1006 /// @TODO move to top of file or somewhere better
1007 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1010 * Get data from $_POST or $_GET
1014 function requestdata($k)
1016 if (x($_POST, $k)) {
1026 * Deprecated function to upload media.
1028 * @param string $type Return type (atom, rss, xml, json)
1030 * @return array|string
1032 function api_statuses_mediap($type)
1036 if (api_user() === false) {
1037 Logger::log('api_statuses_update: no user');
1038 throw new ForbiddenException();
1040 $user_info = api_get_user($a);
1042 $_REQUEST['profile_uid'] = api_user();
1043 $_REQUEST['api_source'] = true;
1044 $txt = requestdata('status');
1045 /// @TODO old-lost code?
1046 //$txt = urldecode(requestdata('status'));
1048 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1049 $txt = html2bb_video($txt);
1050 $config = HTMLPurifier_Config::createDefault();
1051 $config->set('Cache.DefinitionImpl', null);
1052 $purifier = new HTMLPurifier($config);
1053 $txt = $purifier->purify($txt);
1055 $txt = HTML::toBBCode($txt);
1057 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1059 $picture = wall_upload_post($a, false);
1061 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1062 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1063 $item_id = item_post($a);
1065 // output the post that we just posted.
1066 return api_status_show($type, $item_id);
1069 /// @TODO move this to top of file or somewhere better!
1070 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1073 * Updates the user’s current status.
1075 * @param string $type Return type (atom, rss, xml, json)
1077 * @return array|string
1078 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1080 function api_statuses_update($type)
1084 if (api_user() === false) {
1085 Logger::log('api_statuses_update: no user');
1086 throw new ForbiddenException();
1091 // convert $_POST array items to the form we use for web posts.
1092 if (requestdata('htmlstatus')) {
1093 $txt = requestdata('htmlstatus');
1094 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1095 $txt = html2bb_video($txt);
1097 $config = HTMLPurifier_Config::createDefault();
1098 $config->set('Cache.DefinitionImpl', null);
1100 $purifier = new HTMLPurifier($config);
1101 $txt = $purifier->purify($txt);
1103 $_REQUEST['body'] = HTML::toBBCode($txt);
1106 $_REQUEST['body'] = requestdata('status');
1109 $_REQUEST['title'] = requestdata('title');
1111 $parent = requestdata('in_reply_to_status_id');
1113 // Twidere sends "-1" if it is no reply ...
1114 if ($parent == -1) {
1118 if (ctype_digit($parent)) {
1119 $_REQUEST['parent'] = $parent;
1121 $_REQUEST['parent_uri'] = $parent;
1124 if (requestdata('lat') && requestdata('long')) {
1125 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1127 $_REQUEST['profile_uid'] = api_user();
1130 // Check for throttling (maximum posts per day, week and month)
1131 $throttle_day = Config::get('system', 'throttle_limit_day');
1132 if ($throttle_day > 0) {
1133 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1135 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1136 $posts_day = DBA::count('thread', $condition);
1138 if ($posts_day > $throttle_day) {
1139 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1140 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1141 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));
1145 $throttle_week = Config::get('system', 'throttle_limit_week');
1146 if ($throttle_week > 0) {
1147 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1149 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1150 $posts_week = DBA::count('thread', $condition);
1152 if ($posts_week > $throttle_week) {
1153 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1154 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1155 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));
1159 $throttle_month = Config::get('system', 'throttle_limit_month');
1160 if ($throttle_month > 0) {
1161 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1163 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1164 $posts_month = DBA::count('thread', $condition);
1166 if ($posts_month > $throttle_month) {
1167 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1168 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1169 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));
1174 if (x($_FILES, 'media')) {
1175 // upload the image if we have one
1176 $picture = wall_upload_post($a, false);
1177 if (is_array($picture)) {
1178 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1182 // To-Do: Multiple IDs
1183 if (requestdata('media_ids')) {
1185 "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",
1186 intval(requestdata('media_ids')),
1189 if (DBA::isResult($r)) {
1190 $phototypes = Image::supportedTypes();
1191 $ext = $phototypes[$r[0]['type']];
1192 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1193 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1197 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1199 $_REQUEST['api_source'] = true;
1201 if (!x($_REQUEST, "source")) {
1202 $_REQUEST["source"] = api_source();
1205 // call out normal post function
1206 $item_id = item_post($a);
1208 // output the post that we just posted.
1209 return api_status_show($type, $item_id);
1212 /// @TODO move to top of file or somewhere better
1213 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1214 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1217 * Uploads an image to Friendica.
1220 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1222 function api_media_upload()
1226 if (api_user() === false) {
1227 Logger::log('no user');
1228 throw new ForbiddenException();
1233 if (!x($_FILES, 'media')) {
1235 throw new BadRequestException("No media.");
1238 $media = wall_upload_post($a, false);
1241 throw new InternalServerErrorException();
1245 $returndata["media_id"] = $media["id"];
1246 $returndata["media_id_string"] = (string)$media["id"];
1247 $returndata["size"] = $media["size"];
1248 $returndata["image"] = ["w" => $media["width"],
1249 "h" => $media["height"],
1250 "image_type" => $media["type"]];
1252 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1254 return ["media" => $returndata];
1257 /// @TODO move to top of file or somewhere better
1258 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1262 * @param string $type Return type (atom, rss, xml, json)
1264 * @return array|string
1266 function api_status_show($type, $item_id = 0)
1270 $user_info = api_get_user($a);
1272 Logger::log('api_status_show: user_info: '.print_r($user_info, true), Logger::DEBUG);
1274 if ($type == "raw") {
1275 $privacy_sql = "AND NOT `private`";
1280 if (!empty($item_id)) {
1281 // Get the item with the given id
1282 $condition = ['id' => $item_id];
1284 // get last public wall message
1285 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1286 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1288 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1290 if (DBA::isResult($lastwall)) {
1291 $in_reply_to = api_in_reply_to($lastwall);
1293 $converted = api_convert_item($lastwall);
1295 if ($type == "xml") {
1296 $geo = "georss:point";
1302 'created_at' => api_date($lastwall['created']),
1303 'id' => intval($lastwall['id']),
1304 'id_str' => (string) $lastwall['id'],
1305 'text' => $converted["text"],
1306 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1307 'truncated' => false,
1308 'in_reply_to_status_id' => $in_reply_to['status_id'],
1309 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1310 'in_reply_to_user_id' => $in_reply_to['user_id'],
1311 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1312 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1313 'user' => $user_info,
1315 'coordinates' => '',
1317 'contributors' => '',
1318 'is_quote_status' => false,
1319 'retweet_count' => 0,
1320 'favorite_count' => 0,
1321 'favorited' => $lastwall['starred'] ? true : false,
1322 'retweeted' => false,
1323 'possibly_sensitive' => false,
1325 'statusnet_html' => $converted["html"],
1326 'statusnet_conversation_id' => $lastwall['parent'],
1327 'external_url' => System::baseUrl() . '/display/' . $lastwall['guid'],
1330 if (count($converted["attachments"]) > 0) {
1331 $status_info["attachments"] = $converted["attachments"];
1334 if (count($converted["entities"]) > 0) {
1335 $status_info["entities"] = $converted["entities"];
1338 if ($status_info["source"] == 'web') {
1339 $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1340 } elseif (ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) != $status_info["source"]) {
1341 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']).')');
1344 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1345 unset($status_info["user"]["uid"]);
1346 unset($status_info["user"]["self"]);
1348 Logger::log('status_info: '.print_r($status_info, true), Logger::DEBUG);
1350 if ($type == "raw") {
1351 return $status_info;
1354 return api_format_data("statuses", $type, ['status' => $status_info]);
1359 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1360 * The author's most recent status will be returned inline.
1362 * @param string $type Return type (atom, rss, xml, json)
1363 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1365 function api_users_show($type)
1369 $user_info = api_get_user($a);
1371 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1372 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'private' => false];
1373 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1375 if (DBA::isResult($lastwall)) {
1376 $in_reply_to = api_in_reply_to($lastwall);
1378 $converted = api_convert_item($lastwall);
1380 if ($type == "xml") {
1381 $geo = "georss:point";
1386 $user_info['status'] = [
1387 'text' => $converted["text"],
1388 'truncated' => false,
1389 'created_at' => api_date($lastwall['created']),
1390 'in_reply_to_status_id' => $in_reply_to['status_id'],
1391 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1392 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1393 'id' => intval($lastwall['contact-id']),
1394 'id_str' => (string) $lastwall['contact-id'],
1395 'in_reply_to_user_id' => $in_reply_to['user_id'],
1396 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1397 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1399 'favorited' => $lastwall['starred'] ? true : false,
1400 'statusnet_html' => $converted["html"],
1401 'statusnet_conversation_id' => $lastwall['parent'],
1402 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1405 if (count($converted["attachments"]) > 0) {
1406 $user_info["status"]["attachments"] = $converted["attachments"];
1409 if (count($converted["entities"]) > 0) {
1410 $user_info["status"]["entities"] = $converted["entities"];
1413 if ($user_info["status"]["source"] == 'web') {
1414 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1417 if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
1418 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) . ')');
1422 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1423 unset($user_info["uid"]);
1424 unset($user_info["self"]);
1426 return api_format_data("user", $type, ['user' => $user_info]);
1429 /// @TODO move to top of file or somewhere better
1430 api_register_func('api/users/show', 'api_users_show');
1431 api_register_func('api/externalprofile/show', 'api_users_show');
1434 * Search a public user account.
1436 * @param string $type Return type (atom, rss, xml, json)
1438 * @return array|string
1439 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1441 function api_users_search($type)
1447 if (x($_GET, 'q')) {
1448 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1450 if (!DBA::isResult($r)) {
1451 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1454 if (DBA::isResult($r)) {
1456 foreach ($r as $user) {
1457 $user_info = api_get_user($a, $user["id"]);
1459 if ($type == "xml") {
1460 $userlist[$k++.":user"] = $user_info;
1462 $userlist[] = $user_info;
1465 $userlist = ["users" => $userlist];
1467 throw new BadRequestException("User ".$_GET["q"]." not found.");
1470 throw new BadRequestException("No user specified.");
1473 return api_format_data("users", $type, $userlist);
1476 /// @TODO move to top of file or somewhere better
1477 api_register_func('api/users/search', 'api_users_search');
1480 * Return user objects
1482 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1484 * @param string $type Return format: json or xml
1486 * @return array|string
1487 * @throws NotFoundException if the results are empty.
1489 function api_users_lookup($type)
1493 if (!empty($_REQUEST['user_id'])) {
1494 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1496 $users[] = api_get_user(get_app(), $id);
1501 if (empty($users)) {
1502 throw new NotFoundException;
1505 return api_format_data("users", $type, ['users' => $users]);
1508 /// @TODO move to top of file or somewhere better
1509 api_register_func('api/users/lookup', 'api_users_lookup', true);
1512 * Returns statuses that match a specified query.
1514 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1516 * @param string $type Return format: json, xml, atom, rss
1518 * @return array|string
1519 * @throws BadRequestException if the "q" parameter is missing.
1521 function api_search($type)
1524 $user_info = api_get_user($a);
1526 if (api_user() === false || $user_info === false) {
1527 throw new ForbiddenException();
1532 if (!x($_REQUEST, 'q')) {
1533 throw new BadRequestException("q parameter is required.");
1536 if (x($_REQUEST, 'rpp')) {
1537 $count = $_REQUEST['rpp'];
1538 } elseif (x($_REQUEST, 'count')) {
1539 $count = $_REQUEST['count'];
1544 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1545 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1546 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1548 $start = $page * $count;
1550 $condition = ["`gravity` IN (?, ?) AND `item`.`id` > ?
1551 AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1552 AND `item`.`body` LIKE CONCAT('%',?,'%')",
1553 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, api_user(), $_REQUEST['q']];
1556 $condition[0] .= " AND `item`.`id` <= ?";
1557 $condition[] = $max_id;
1560 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1561 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1563 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1565 return api_format_data("statuses", $type, $data);
1568 /// @TODO move to top of file or somewhere better
1569 api_register_func('api/search/tweets', 'api_search', true);
1570 api_register_func('api/search', 'api_search', true);
1573 * Returns the most recent statuses posted by the user and the users they follow.
1575 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1577 * @param string $type Return type (atom, rss, xml, json)
1579 * @todo Optional parameters
1580 * @todo Add reply info
1582 function api_statuses_home_timeline($type)
1585 $user_info = api_get_user($a);
1587 if (api_user() === false || $user_info === false) {
1588 throw new ForbiddenException();
1591 unset($_REQUEST["user_id"]);
1592 unset($_GET["user_id"]);
1594 unset($_REQUEST["screen_name"]);
1595 unset($_GET["screen_name"]);
1597 // get last network messages
1600 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1601 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1605 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1606 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1607 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1608 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1609 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1611 $start = $page * $count;
1613 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1614 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1617 $condition[0] .= " AND `item`.`id` <= ?";
1618 $condition[] = $max_id;
1620 if ($exclude_replies > 0) {
1621 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1623 if ($conversation_id > 0) {
1624 $condition[0] .= " AND `item`.`parent` = ?";
1625 $condition[] = $conversation_id;
1628 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1629 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1631 $items = Item::inArray($statuses);
1633 $ret = api_format_items($items, $user_info, false, $type);
1635 // Set all posts from the query above to seen
1637 foreach ($items as $item) {
1638 $idarray[] = intval($item["id"]);
1641 if (!empty($idarray)) {
1642 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1644 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1648 $data = ['status' => $ret];
1652 $data = api_rss_extra($a, $data, $user_info);
1656 return api_format_data("statuses", $type, $data);
1659 /// @TODO move to top of file or somewhere better
1660 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1661 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1664 * Returns the most recent statuses from public users.
1666 * @param string $type Return type (atom, rss, xml, json)
1668 * @return array|string
1670 function api_statuses_public_timeline($type)
1673 $user_info = api_get_user($a);
1675 if (api_user() === false || $user_info === false) {
1676 throw new ForbiddenException();
1679 // get last network messages
1682 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1683 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1687 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1688 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1689 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1690 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1691 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1693 $start = $page * $count;
1696 if ($exclude_replies && !$conversation_id) {
1697 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall`",
1698 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1701 $condition[0] .= " AND `thread`.`iid` <= ?";
1702 $condition[] = $max_id;
1705 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1706 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1708 $r = Item::inArray($statuses);
1710 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin`",
1711 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1714 $condition[0] .= " AND `item`.`id` <= ?";
1715 $condition[] = $max_id;
1717 if ($conversation_id > 0) {
1718 $condition[0] .= " AND `item`.`parent` = ?";
1719 $condition[] = $conversation_id;
1722 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1723 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1725 $r = Item::inArray($statuses);
1728 $ret = api_format_items($r, $user_info, false, $type);
1730 $data = ['status' => $ret];
1734 $data = api_rss_extra($a, $data, $user_info);
1738 return api_format_data("statuses", $type, $data);
1741 /// @TODO move to top of file or somewhere better
1742 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1745 * Returns the most recent statuses posted by users this node knows about.
1747 * @brief Returns the list of public federated posts this node knows about
1749 * @param string $type Return format: json, xml, atom, rss
1750 * @return array|string
1751 * @throws ForbiddenException
1753 function api_statuses_networkpublic_timeline($type)
1756 $user_info = api_get_user($a);
1758 if (api_user() === false || $user_info === false) {
1759 throw new ForbiddenException();
1762 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1763 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1766 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1767 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1771 $start = ($page - 1) * $count;
1773 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1774 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1777 $condition[0] .= " AND `thread`.`iid` <= ?";
1778 $condition[] = $max_id;
1781 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1782 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1784 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1786 $data = ['status' => $ret];
1790 $data = api_rss_extra($a, $data, $user_info);
1794 return api_format_data("statuses", $type, $data);
1797 /// @TODO move to top of file or somewhere better
1798 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1801 * Returns a single status.
1803 * @param string $type Return type (atom, rss, xml, json)
1805 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1807 function api_statuses_show($type)
1810 $user_info = api_get_user($a);
1812 if (api_user() === false || $user_info === false) {
1813 throw new ForbiddenException();
1817 $id = intval(defaults($a->argv, 3, 0));
1820 $id = intval(defaults($_REQUEST, 'id', 0));
1825 $id = intval(defaults($a->argv, 4, 0));
1828 Logger::log('API: api_statuses_show: ' . $id);
1830 $conversation = !empty($_REQUEST['conversation']);
1832 // try to fetch the item for the local user - or the public item, if there is no local one
1833 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1834 if (!DBA::isResult($uri_item)) {
1835 throw new BadRequestException("There is no status with this id.");
1838 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1839 if (!DBA::isResult($item)) {
1840 throw new BadRequestException("There is no status with this id.");
1845 if ($conversation) {
1846 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1847 $params = ['order' => ['id' => true]];
1849 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1853 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1855 /// @TODO How about copying this to above methods which don't check $r ?
1856 if (!DBA::isResult($statuses)) {
1857 throw new BadRequestException("There is no status with this id.");
1860 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1862 if ($conversation) {
1863 $data = ['status' => $ret];
1864 return api_format_data("statuses", $type, $data);
1866 $data = ['status' => $ret[0]];
1867 return api_format_data("status", $type, $data);
1871 /// @TODO move to top of file or somewhere better
1872 api_register_func('api/statuses/show', 'api_statuses_show', true);
1876 * @param string $type Return type (atom, rss, xml, json)
1878 * @todo nothing to say?
1880 function api_conversation_show($type)
1883 $user_info = api_get_user($a);
1885 if (api_user() === false || $user_info === false) {
1886 throw new ForbiddenException();
1890 $id = intval(defaults($a->argv , 3 , 0));
1891 $since_id = intval(defaults($_REQUEST, 'since_id', 0));
1892 $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
1893 $count = intval(defaults($_REQUEST, 'count' , 20));
1894 $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
1899 $start = $page * $count;
1902 $id = intval(defaults($_REQUEST, 'id', 0));
1907 $id = intval(defaults($a->argv, 4, 0));
1910 Logger::log('API: api_conversation_show: '.$id);
1912 // try to fetch the item for the local user - or the public item, if there is no local one
1913 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1914 if (!DBA::isResult($item)) {
1915 throw new BadRequestException("There is no status with this id.");
1918 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1919 if (!DBA::isResult($parent)) {
1920 throw new BadRequestException("There is no status with this id.");
1923 $id = $parent['id'];
1925 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1926 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1929 $condition[0] .= " AND `item`.`id` <= ?";
1930 $condition[] = $max_id;
1933 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1934 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1936 if (!DBA::isResult($statuses)) {
1937 throw new BadRequestException("There is no status with id $id.");
1940 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1942 $data = ['status' => $ret];
1943 return api_format_data("statuses", $type, $data);
1946 /// @TODO move to top of file or somewhere better
1947 api_register_func('api/conversation/show', 'api_conversation_show', true);
1948 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1953 * @param string $type Return type (atom, rss, xml, json)
1955 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1957 function api_statuses_repeat($type)
1963 if (api_user() === false) {
1964 throw new ForbiddenException();
1970 $id = intval(defaults($a->argv, 3, 0));
1973 $id = intval(defaults($_REQUEST, 'id', 0));
1978 $id = intval(defaults($a->argv, 4, 0));
1981 Logger::log('API: api_statuses_repeat: '.$id);
1983 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1984 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
1986 if (DBA::isResult($item) && $item['body'] != "") {
1987 if (strpos($item['body'], "[/share]") !== false) {
1988 $pos = strpos($item['body'], "[share");
1989 $post = substr($item['body'], $pos);
1991 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
1993 $post .= $item['body'];
1994 $post .= "[/share]";
1996 $_REQUEST['body'] = $post;
1997 $_REQUEST['profile_uid'] = api_user();
1998 $_REQUEST['api_source'] = true;
2000 if (!x($_REQUEST, "source")) {
2001 $_REQUEST["source"] = api_source();
2004 $item_id = item_post($a);
2006 throw new ForbiddenException();
2009 // output the post that we just posted.
2011 return api_status_show($type, $item_id);
2014 /// @TODO move to top of file or somewhere better
2015 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2018 * Destroys a specific status.
2020 * @param string $type Return type (atom, rss, xml, json)
2022 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2024 function api_statuses_destroy($type)
2028 if (api_user() === false) {
2029 throw new ForbiddenException();
2035 $id = intval(defaults($a->argv, 3, 0));
2038 $id = intval(defaults($_REQUEST, 'id', 0));
2043 $id = intval(defaults($a->argv, 4, 0));
2046 Logger::log('API: api_statuses_destroy: '.$id);
2048 $ret = api_statuses_show($type);
2050 Item::deleteForUser(['id' => $id], api_user());
2055 /// @TODO move to top of file or somewhere better
2056 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2059 * Returns the most recent mentions.
2061 * @param string $type Return type (atom, rss, xml, json)
2063 * @see http://developer.twitter.com/doc/get/statuses/mentions
2065 function api_statuses_mentions($type)
2068 $user_info = api_get_user($a);
2070 if (api_user() === false || $user_info === false) {
2071 throw new ForbiddenException();
2074 unset($_REQUEST["user_id"]);
2075 unset($_GET["user_id"]);
2077 unset($_REQUEST["screen_name"]);
2078 unset($_GET["screen_name"]);
2080 // get last network messages
2083 $since_id = defaults($_REQUEST, 'since_id', 0);
2084 $max_id = defaults($_REQUEST, 'max_id' , 0);
2085 $count = defaults($_REQUEST, 'count' , 20);
2086 $page = defaults($_REQUEST, 'page' , 1);
2091 $start = ($page - 1) * $count;
2093 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2094 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2095 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2098 $condition[0] .= " AND `item`.`id` <= ?";
2099 $condition[] = $max_id;
2102 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2103 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2105 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2107 $data = ['status' => $ret];
2111 $data = api_rss_extra($a, $data, $user_info);
2115 return api_format_data("statuses", $type, $data);
2118 /// @TODO move to top of file or somewhere better
2119 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2120 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2123 * Returns the most recent statuses posted by the user.
2125 * @brief Returns a user's public timeline
2127 * @param string $type Either "json" or "xml"
2128 * @return string|array
2129 * @throws ForbiddenException
2130 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2132 function api_statuses_user_timeline($type)
2135 $user_info = api_get_user($a);
2137 if (api_user() === false || $user_info === false) {
2138 throw new ForbiddenException();
2142 "api_statuses_user_timeline: api_user: ". api_user() .
2143 "\nuser_info: ".print_r($user_info, true) .
2144 "\n_REQUEST: ".print_r($_REQUEST, true),
2148 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2149 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2150 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2151 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2154 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2155 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2159 $start = ($page - 1) * $count;
2161 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2162 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2164 if ($user_info['self'] == 1) {
2165 $condition[0] .= ' AND `item`.`wall` ';
2168 if ($exclude_replies > 0) {
2169 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2172 if ($conversation_id > 0) {
2173 $condition[0] .= " AND `item`.`parent` = ?";
2174 $condition[] = $conversation_id;
2178 $condition[0] .= " AND `item`.`id` <= ?";
2179 $condition[] = $max_id;
2182 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2183 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2185 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2187 $data = ['status' => $ret];
2191 $data = api_rss_extra($a, $data, $user_info);
2195 return api_format_data("statuses", $type, $data);
2198 /// @TODO move to top of file or somewhere better
2199 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2202 * Star/unstar an item.
2203 * param: id : id of the item
2205 * @param string $type Return type (atom, rss, xml, json)
2207 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2209 function api_favorites_create_destroy($type)
2213 if (api_user() === false) {
2214 throw new ForbiddenException();
2217 // for versioned api.
2218 /// @TODO We need a better global soluton
2219 $action_argv_id = 2;
2220 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2221 $action_argv_id = 3;
2224 if ($a->argc <= $action_argv_id) {
2225 throw new BadRequestException("Invalid request.");
2227 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2228 if ($a->argc == $action_argv_id + 2) {
2229 $itemid = intval(defaults($a->argv, $action_argv_id + 1, 0));
2231 $itemid = intval(defaults($_REQUEST, 'id', 0));
2234 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2236 if (!DBA::isResult($item)) {
2237 throw new BadRequestException("Invalid item.");
2242 $item['starred'] = 1;
2245 $item['starred'] = 0;
2248 throw new BadRequestException("Invalid action ".$action);
2251 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2254 throw new InternalServerErrorException("DB error");
2258 $user_info = api_get_user($a);
2259 $rets = api_format_items([$item], $user_info, false, $type);
2262 $data = ['status' => $ret];
2266 $data = api_rss_extra($a, $data, $user_info);
2269 return api_format_data("status", $type, $data);
2272 /// @TODO move to top of file or somewhere better
2273 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2274 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2277 * Returns the most recent favorite statuses.
2279 * @param string $type Return type (atom, rss, xml, json)
2281 * @return string|array
2283 function api_favorites($type)
2288 $user_info = api_get_user($a);
2290 if (api_user() === false || $user_info === false) {
2291 throw new ForbiddenException();
2296 // in friendica starred item are private
2297 // return favorites only for self
2298 Logger::log('api_favorites: self:' . $user_info['self']);
2300 if ($user_info['self'] == 0) {
2304 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2305 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2306 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2307 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2312 $start = $page*$count;
2314 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2315 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2317 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2320 $condition[0] .= " AND `item`.`id` <= ?";
2321 $condition[] = $max_id;
2324 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2326 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2329 $data = ['status' => $ret];
2333 $data = api_rss_extra($a, $data, $user_info);
2336 return api_format_data("statuses", $type, $data);
2339 /// @TODO move to top of file or somewhere better
2340 api_register_func('api/favorites', 'api_favorites', true);
2344 * @param array $item
2345 * @param array $recipient
2346 * @param array $sender
2350 function api_format_messages($item, $recipient, $sender)
2352 // standard meta information
2354 'id' => $item['id'],
2355 'sender_id' => $sender['id'],
2357 'recipient_id' => $recipient['id'],
2358 'created_at' => api_date(defaults($item, 'created', DateTimeFormat::utcNow())),
2359 'sender_screen_name' => $sender['screen_name'],
2360 'recipient_screen_name' => $recipient['screen_name'],
2361 'sender' => $sender,
2362 'recipient' => $recipient,
2364 'friendica_seen' => defaults($item, 'seen', 0),
2365 'friendica_parent_uri' => defaults($item, 'parent-uri', ''),
2368 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2369 if (isset($ret['sender']['uid'])) {
2370 unset($ret['sender']['uid']);
2372 if (isset($ret['sender']['self'])) {
2373 unset($ret['sender']['self']);
2375 if (isset($ret['recipient']['uid'])) {
2376 unset($ret['recipient']['uid']);
2378 if (isset($ret['recipient']['self'])) {
2379 unset($ret['recipient']['self']);
2382 //don't send title to regular StatusNET requests to avoid confusing these apps
2383 if (x($_GET, 'getText')) {
2384 $ret['title'] = $item['title'];
2385 if ($_GET['getText'] == 'html') {
2386 $ret['text'] = BBCode::convert($item['body'], false);
2387 } elseif ($_GET['getText'] == 'plain') {
2388 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2391 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2393 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2394 unset($ret['sender']);
2395 unset($ret['recipient']);
2403 * @param array $item
2407 function api_convert_item($item)
2409 $body = $item['body'];
2410 $attachments = api_get_attachments($body);
2412 // Workaround for ostatus messages where the title is identically to the body
2413 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2414 $statusbody = trim(HTML::toPlaintext($html, 0));
2416 // handle data: images
2417 $statusbody = api_format_items_embeded_images($item, $statusbody);
2419 $statustitle = trim($item['title']);
2421 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2422 $statustext = trim($statusbody);
2424 $statustext = trim($statustitle."\n\n".$statusbody);
2427 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($statustext)> 1000)) {
2428 $statustext = substr($statustext, 0, 1000) . "... \n" . defaults($item, 'plink', '');
2431 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2433 // Workaround for clients with limited HTML parser functionality
2434 $search = ["<br>", "<blockquote>", "</blockquote>",
2435 "<h1>", "</h1>", "<h2>", "</h2>",
2436 "<h3>", "</h3>", "<h4>", "</h4>",
2437 "<h5>", "</h5>", "<h6>", "</h6>"];
2438 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2439 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2440 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2441 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2442 $statushtml = str_replace($search, $replace, $statushtml);
2444 if ($item['title'] != "") {
2445 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2449 $oldtext = $statushtml;
2450 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2451 } while ($oldtext != $statushtml);
2453 if (substr($statushtml, 0, 4) == '<br>') {
2454 $statushtml = substr($statushtml, 4);
2457 if (substr($statushtml, 0, -4) == '<br>') {
2458 $statushtml = substr($statushtml, -4);
2461 // feeds without body should contain the link
2462 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2463 $statushtml .= BBCode::convert($item['plink']);
2466 $entities = api_get_entitities($statustext, $body);
2469 "text" => $statustext,
2470 "html" => $statushtml,
2471 "attachments" => $attachments,
2472 "entities" => $entities
2478 * @param string $body
2482 function api_get_attachments(&$body)
2485 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2487 $URLSearchString = "^\[\]";
2488 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2496 foreach ($images[1] as $image) {
2497 $imagedata = Image::getInfoFromURL($image);
2500 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2504 if (strstr(defaults($_SERVER, 'HTTP_USER_AGENT', ''), "AndStatus")) {
2505 foreach ($images[0] as $orig) {
2506 $body = str_replace($orig, "", $body);
2510 return $attachments;
2515 * @param string $text
2516 * @param string $bbcode
2519 * @todo Links at the first character of the post
2521 function api_get_entitities(&$text, $bbcode)
2523 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2525 if ($include_entities != "true") {
2526 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2528 foreach ($images[1] as $image) {
2529 $replace = ProxyUtils::proxifyUrl($image);
2530 $text = str_replace($image, $replace, $text);
2535 $bbcode = BBCode::cleanPictureLinks($bbcode);
2537 // Change pure links in text to bbcode uris
2538 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2541 $entities["hashtags"] = [];
2542 $entities["symbols"] = [];
2543 $entities["urls"] = [];
2544 $entities["user_mentions"] = [];
2546 $URLSearchString = "^\[\]";
2548 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2550 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2551 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2552 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2554 $bbcode = preg_replace(
2555 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2556 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2559 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2561 $bbcode = preg_replace(
2562 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2563 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2566 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2568 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2570 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2571 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2574 foreach ($urls[1] as $id => $url) {
2575 //$start = strpos($text, $url, $offset);
2576 $start = iconv_strpos($text, $url, 0, "UTF-8");
2577 if (!($start === false)) {
2578 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2582 ksort($ordered_urls);
2585 //foreach ($urls[1] AS $id=>$url) {
2586 foreach ($ordered_urls as $url) {
2587 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2588 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2590 $display_url = $url["title"];
2592 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2593 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2595 if (strlen($display_url) > 26) {
2596 $display_url = substr($display_url, 0, 25)."…";
2600 //$start = strpos($text, $url, $offset);
2601 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2602 if (!($start === false)) {
2603 $entities["urls"][] = ["url" => $url["url"],
2604 "expanded_url" => $url["url"],
2605 "display_url" => $display_url,
2606 "indices" => [$start, $start+strlen($url["url"])]];
2607 $offset = $start + 1;
2611 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2612 $ordered_images = [];
2613 foreach ($images[1] as $image) {
2614 //$start = strpos($text, $url, $offset);
2615 $start = iconv_strpos($text, $image, 0, "UTF-8");
2616 if (!($start === false)) {
2617 $ordered_images[$start] = $image;
2620 //$entities["media"] = array();
2623 foreach ($ordered_images as $url) {
2624 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2625 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2627 if (strlen($display_url) > 26) {
2628 $display_url = substr($display_url, 0, 25)."…";
2631 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2632 if (!($start === false)) {
2633 $image = Image::getInfoFromURL($url);
2635 // If image cache is activated, then use the following sizes:
2636 // thumb (150), small (340), medium (600) and large (1024)
2637 if (!Config::get("system", "proxy_disabled")) {
2638 $media_url = ProxyUtils::proxifyUrl($url);
2641 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2642 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2644 if (($image[0] > 150) || ($image[1] > 150)) {
2645 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2646 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2649 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2650 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2652 if (($image[0] > 600) || ($image[1] > 600)) {
2653 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2654 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2658 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2661 $entities["media"][] = [
2663 "id_str" => (string)$start+1,
2664 "indices" => [$start, $start+strlen($url)],
2665 "media_url" => normalise_link($media_url),
2666 "media_url_https" => $media_url,
2668 "display_url" => $display_url,
2669 "expanded_url" => $url,
2673 $offset = $start + 1;
2682 * @param array $item
2683 * @param string $text
2687 function api_format_items_embeded_images($item, $text)
2689 $text = preg_replace_callback(
2690 '|data:image/([^;]+)[^=]+=*|m',
2691 function () use ($item) {
2692 return System::baseUrl() . '/display/' . $item['guid'];
2700 * @brief return <a href='url'>name</a> as array
2702 * @param string $txt text
2707 function api_contactlink_to_array($txt)
2710 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2711 if ($r && count($match)==3) {
2713 'name' => $match[2],
2727 * @brief return likes, dislikes and attend status for item
2729 * @param array $item array
2730 * @param string $type Return type (atom, rss, xml, json)
2733 * likes => int count,
2734 * dislikes => int count
2736 function api_format_items_activities($item, $type = "json")
2745 'attendmaybe' => [],
2748 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2749 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2751 while ($parent_item = Item::fetch($ret)) {
2752 // not used as result should be structured like other user data
2753 //builtin_activity_puller($i, $activities);
2755 // get user data and add it to the array of the activity
2756 $user = api_get_user($a, $parent_item['author-id']);
2757 switch ($parent_item['verb']) {
2759 $activities['like'][] = $user;
2761 case ACTIVITY_DISLIKE:
2762 $activities['dislike'][] = $user;
2764 case ACTIVITY_ATTEND:
2765 $activities['attendyes'][] = $user;
2767 case ACTIVITY_ATTENDNO:
2768 $activities['attendno'][] = $user;
2770 case ACTIVITY_ATTENDMAYBE:
2771 $activities['attendmaybe'][] = $user;
2780 if ($type == "xml") {
2781 $xml_activities = [];
2782 foreach ($activities as $k => $v) {
2783 // change xml element from "like" to "friendica:like"
2784 $xml_activities["friendica:".$k] = $v;
2785 // add user data into xml output
2787 foreach ($v as $user) {
2788 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2791 $activities = $xml_activities;
2799 * @brief return data from profiles
2801 * @param array $profile_row array containing data from db table 'profile'
2804 function api_format_items_profiles($profile_row)
2807 'profile_id' => $profile_row['id'],
2808 'profile_name' => $profile_row['profile-name'],
2809 'is_default' => $profile_row['is-default'] ? true : false,
2810 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2811 'profile_photo' => $profile_row['photo'],
2812 'profile_thumb' => $profile_row['thumb'],
2813 'publish' => $profile_row['publish'] ? true : false,
2814 'net_publish' => $profile_row['net-publish'] ? true : false,
2815 'description' => $profile_row['pdesc'],
2816 'date_of_birth' => $profile_row['dob'],
2817 'address' => $profile_row['address'],
2818 'city' => $profile_row['locality'],
2819 'region' => $profile_row['region'],
2820 'postal_code' => $profile_row['postal-code'],
2821 'country' => $profile_row['country-name'],
2822 'hometown' => $profile_row['hometown'],
2823 'gender' => $profile_row['gender'],
2824 'marital' => $profile_row['marital'],
2825 'marital_with' => $profile_row['with'],
2826 'marital_since' => $profile_row['howlong'],
2827 'sexual' => $profile_row['sexual'],
2828 'politic' => $profile_row['politic'],
2829 'religion' => $profile_row['religion'],
2830 'public_keywords' => $profile_row['pub_keywords'],
2831 'private_keywords' => $profile_row['prv_keywords'],
2832 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2833 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2834 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2835 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2836 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2837 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2838 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2839 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2840 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2841 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2842 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2843 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2844 'homepage' => $profile_row['homepage'],
2851 * @brief format items to be returned by api
2853 * @param array $r array of items
2854 * @param array $user_info
2855 * @param bool $filter_user filter items by $user_info
2856 * @param string $type Return type (atom, rss, xml, json)
2858 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2864 foreach ($r as $item) {
2865 localize_item($item);
2866 list($status_user, $owner_user) = api_item_get_user($a, $item);
2868 // Look if the posts are matching if they should be filtered by user id
2869 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2873 $in_reply_to = api_in_reply_to($item);
2875 $converted = api_convert_item($item);
2877 if ($type == "xml") {
2878 $geo = "georss:point";
2884 'text' => $converted["text"],
2885 'truncated' => false,
2886 'created_at'=> api_date($item['created']),
2887 'in_reply_to_status_id' => $in_reply_to['status_id'],
2888 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2889 'source' => (($item['app']) ? $item['app'] : 'web'),
2890 'id' => intval($item['id']),
2891 'id_str' => (string) intval($item['id']),
2892 'in_reply_to_user_id' => $in_reply_to['user_id'],
2893 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2894 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2896 'favorited' => $item['starred'] ? true : false,
2897 'user' => $status_user,
2898 'friendica_owner' => $owner_user,
2899 'friendica_private' => $item['private'] == 1,
2900 //'entities' => NULL,
2901 'statusnet_html' => $converted["html"],
2902 'statusnet_conversation_id' => $item['parent'],
2903 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2904 'friendica_activities' => api_format_items_activities($item, $type),
2907 if (count($converted["attachments"]) > 0) {
2908 $status["attachments"] = $converted["attachments"];
2911 if (count($converted["entities"]) > 0) {
2912 $status["entities"] = $converted["entities"];
2915 if ($status["source"] == 'web') {
2916 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
2917 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
2918 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
2921 if ($item["id"] == $item["parent"]) {
2922 $retweeted_item = api_share_as_retweet($item);
2923 if ($retweeted_item !== false) {
2924 $retweeted_status = $status;
2926 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
2927 } catch (BadRequestException $e) {
2928 // user not found. should be found?
2929 /// @todo check if the user should be always found
2930 $retweeted_status["user"] = [];
2933 $rt_converted = api_convert_item($retweeted_item);
2935 $retweeted_status['text'] = $rt_converted["text"];
2936 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2937 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2938 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2939 $status['retweeted_status'] = $retweeted_status;
2943 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2944 unset($status["user"]["uid"]);
2945 unset($status["user"]["self"]);
2947 if ($item["coord"] != "") {
2948 $coords = explode(' ', $item["coord"]);
2949 if (count($coords) == 2) {
2950 if ($type == "json") {
2951 $status["geo"] = ['type' => 'Point',
2952 'coordinates' => [(float) $coords[0],
2953 (float) $coords[1]]];
2954 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2955 $status["georss:point"] = $item["coord"];
2965 * Returns the remaining number of API requests available to the user before the API limit is reached.
2967 * @param string $type Return type (atom, rss, xml, json)
2969 * @return array|string
2971 function api_account_rate_limit_status($type)
2973 if ($type == "xml") {
2975 'remaining-hits' => '150',
2976 '@attributes' => ["type" => "integer"],
2977 'hourly-limit' => '150',
2978 '@attributes2' => ["type" => "integer"],
2979 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
2980 '@attributes3' => ["type" => "datetime"],
2981 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2982 '@attributes4' => ["type" => "integer"],
2986 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2987 'remaining_hits' => '150',
2988 'hourly_limit' => '150',
2989 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
2993 return api_format_data('hash', $type, ['hash' => $hash]);
2996 /// @TODO move to top of file or somewhere better
2997 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3000 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3002 * @param string $type Return type (atom, rss, xml, json)
3004 * @return array|string
3006 function api_help_test($type)
3008 if ($type == 'xml') {
3014 return api_format_data('ok', $type, ["ok" => $ok]);
3017 /// @TODO move to top of file or somewhere better
3018 api_register_func('api/help/test', 'api_help_test', false);
3021 * Returns all lists the user subscribes to.
3023 * @param string $type Return type (atom, rss, xml, json)
3025 * @return array|string
3026 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3028 function api_lists_list($type)
3031 /// @TODO $ret is not filled here?
3032 return api_format_data('lists', $type, ["lists_list" => $ret]);
3035 /// @TODO move to top of file or somewhere better
3036 api_register_func('api/lists/list', 'api_lists_list', true);
3037 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3040 * Returns all groups the user owns.
3042 * @param string $type Return type (atom, rss, xml, json)
3044 * @return array|string
3045 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3047 function api_lists_ownerships($type)
3051 if (api_user() === false) {
3052 throw new ForbiddenException();
3056 $user_info = api_get_user($a);
3057 $uid = $user_info['uid'];
3059 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3061 // loop through all groups
3063 foreach ($groups as $group) {
3064 if ($group['visible']) {
3070 'name' => $group['name'],
3071 'id' => intval($group['id']),
3072 'id_str' => (string) $group['id'],
3073 'user' => $user_info,
3077 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3080 /// @TODO move to top of file or somewhere better
3081 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3084 * Returns recent statuses from users in the specified group.
3086 * @param string $type Return type (atom, rss, xml, json)
3088 * @return array|string
3089 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3091 function api_lists_statuses($type)
3095 $user_info = api_get_user($a);
3096 if (api_user() === false || $user_info === false) {
3097 throw new ForbiddenException();
3100 unset($_REQUEST["user_id"]);
3101 unset($_GET["user_id"]);
3103 unset($_REQUEST["screen_name"]);
3104 unset($_GET["screen_name"]);
3106 if (empty($_REQUEST['list_id'])) {
3107 throw new BadRequestException('list_id not specified');
3111 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
3112 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
3116 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3117 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3118 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
3119 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
3121 $start = $page * $count;
3123 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3124 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3127 $condition[0] .= " AND `item`.`id` <= ?";
3128 $condition[] = $max_id;
3130 if ($exclude_replies > 0) {
3131 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3133 if ($conversation_id > 0) {
3134 $condition[0] .= " AND `item`.`parent` = ?";
3135 $condition[] = $conversation_id;
3138 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3139 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3141 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3143 $data = ['status' => $items];
3147 $data = api_rss_extra($a, $data, $user_info);
3151 return api_format_data("statuses", $type, $data);
3154 /// @TODO move to top of file or somewhere better
3155 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3158 * Considers friends and followers lists to be private and won't return
3159 * anything if any user_id parameter is passed.
3161 * @brief Returns either the friends of the follower list
3163 * @param string $qtype Either "friends" or "followers"
3164 * @return boolean|array
3165 * @throws ForbiddenException
3167 function api_statuses_f($qtype)
3171 if (api_user() === false) {
3172 throw new ForbiddenException();
3176 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3177 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3181 $start = ($page - 1) * $count;
3183 $user_info = api_get_user($a);
3185 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3186 /* this is to stop Hotot to load friends multiple times
3187 * I'm not sure if I'm missing return something or
3188 * is a bug in hotot. Workaround, meantime
3192 return array('$users' => $ret);*/
3197 if ($qtype == 'friends') {
3198 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3199 } elseif ($qtype == 'followers') {
3200 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3203 // friends and followers only for self
3204 if ($user_info['self'] == 0) {
3205 $sql_extra = " AND false ";
3208 if ($qtype == 'blocks') {
3209 $sql_filter = 'AND `blocked` AND NOT `pending`';
3210 } elseif ($qtype == 'incoming') {
3211 $sql_filter = 'AND `pending`';
3213 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3231 foreach ($r as $cid) {
3232 $user = api_get_user($a, $cid['nurl']);
3233 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3234 unset($user["uid"]);
3235 unset($user["self"]);
3242 return ['user' => $ret];
3247 * Returns the user's friends.
3249 * @brief Returns the list of friends of the provided user
3251 * @deprecated By Twitter API in favor of friends/list
3253 * @param string $type Either "json" or "xml"
3254 * @return boolean|string|array
3256 function api_statuses_friends($type)
3258 $data = api_statuses_f("friends");
3259 if ($data === false) {
3262 return api_format_data("users", $type, $data);
3266 * Returns the user's followers.
3268 * @brief Returns the list of followers of the provided user
3270 * @deprecated By Twitter API in favor of friends/list
3272 * @param string $type Either "json" or "xml"
3273 * @return boolean|string|array
3275 function api_statuses_followers($type)
3277 $data = api_statuses_f("followers");
3278 if ($data === false) {
3281 return api_format_data("users", $type, $data);
3284 /// @TODO move to top of file or somewhere better
3285 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3286 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3289 * Returns the list of blocked users
3291 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3293 * @param string $type Either "json" or "xml"
3295 * @return boolean|string|array
3297 function api_blocks_list($type)
3299 $data = api_statuses_f('blocks');
3300 if ($data === false) {
3303 return api_format_data("users", $type, $data);
3306 /// @TODO move to top of file or somewhere better
3307 api_register_func('api/blocks/list', 'api_blocks_list', true);
3310 * Returns the list of pending users IDs
3312 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3314 * @param string $type Either "json" or "xml"
3316 * @return boolean|string|array
3318 function api_friendships_incoming($type)
3320 $data = api_statuses_f('incoming');
3321 if ($data === false) {
3326 foreach ($data['user'] as $user) {
3327 $ids[] = $user['id'];
3330 return api_format_data("ids", $type, ['id' => $ids]);
3333 /// @TODO move to top of file or somewhere better
3334 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3337 * Returns the instance's configuration information.
3339 * @param string $type Return type (atom, rss, xml, json)
3341 * @return array|string
3343 function api_statusnet_config($type)
3347 $name = Config::get('config', 'sitename');
3348 $server = $a->getHostName();
3349 $logo = System::baseUrl() . '/images/friendica-64.png';
3350 $email = Config::get('config', 'admin_email');
3351 $closed = intval(Config::get('config', 'register_policy')) === REGISTER_CLOSED ? 'true' : 'false';
3352 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3353 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3354 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3355 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3358 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3359 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3360 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3361 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3362 'shorturllength' => '30',
3364 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3365 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3366 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3367 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3372 return api_format_data('config', $type, ['config' => $config]);
3375 /// @TODO move to top of file or somewhere better
3376 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3377 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3381 * @param string $type Return type (atom, rss, xml, json)
3383 * @return array|string
3385 function api_statusnet_version($type)
3388 $fake_statusnet_version = "0.9.7";
3390 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3393 /// @TODO move to top of file or somewhere better
3394 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3395 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3399 * @param string $type Return type (atom, rss, xml, json)
3401 * @todo use api_format_data() to return data
3403 function api_ff_ids($type)
3406 throw new ForbiddenException();
3413 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3416 "SELECT `pcontact`.`id` FROM `contact`
3417 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3418 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3421 if (!DBA::isResult($r)) {
3426 foreach ($r as $rr) {
3427 if ($stringify_ids) {
3430 $ids[] = intval($rr['id']);
3434 return api_format_data("ids", $type, ['id' => $ids]);
3438 * Returns the ID of every user the user is following.
3440 * @param string $type Return type (atom, rss, xml, json)
3442 * @return array|string
3443 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3445 function api_friends_ids($type)
3447 return api_ff_ids($type);
3451 * Returns the ID of every user following the user.
3453 * @param string $type Return type (atom, rss, xml, json)
3455 * @return array|string
3456 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3458 function api_followers_ids($type)
3460 return api_ff_ids($type);
3463 /// @TODO move to top of file or somewhere better
3464 api_register_func('api/friends/ids', 'api_friends_ids', true);
3465 api_register_func('api/followers/ids', 'api_followers_ids', true);
3468 * Sends a new direct message.
3470 * @param string $type Return type (atom, rss, xml, json)
3472 * @return array|string
3473 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3475 function api_direct_messages_new($type)
3479 if (api_user() === false) {
3480 throw new ForbiddenException();
3483 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3487 $sender = api_get_user($a);
3490 if (!empty($_POST['screen_name'])) {
3492 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3494 DBA::escape($_POST['screen_name'])
3497 if (DBA::isResult($r)) {
3498 // Selecting the id by priority, friendica first
3499 api_best_nickname($r);
3501 $recipient = api_get_user($a, $r[0]['nurl']);
3504 $recipient = api_get_user($a, $_POST['user_id']);
3507 if (empty($recipient)) {
3508 throw new NotFoundException('Recipient not found');
3513 if (x($_REQUEST, 'replyto')) {
3515 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3517 intval($_REQUEST['replyto'])
3519 $replyto = $r[0]['parent-uri'];
3520 $sub = $r[0]['title'];
3522 if (x($_REQUEST, 'title')) {
3523 $sub = $_REQUEST['title'];
3525 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3529 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3532 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3533 $ret = api_format_messages($r[0], $recipient, $sender);
3535 $ret = ["error"=>$id];
3538 $data = ['direct_message'=>$ret];
3543 $data = api_rss_extra($a, $data, $sender);
3546 return api_format_data("direct-messages", $type, $data);
3549 /// @TODO move to top of file or somewhere better
3550 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3553 * Destroys a direct message.
3555 * @brief delete a direct_message from mail table through api
3557 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3558 * @return string|array
3559 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3561 function api_direct_messages_destroy($type)
3565 if (api_user() === false) {
3566 throw new ForbiddenException();
3570 $user_info = api_get_user($a);
3572 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3574 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3575 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3576 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3578 $uid = $user_info['uid'];
3579 // error if no id or parenturi specified (for clients posting parent-uri as well)
3580 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3581 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3582 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3585 // BadRequestException if no id specified (for clients using Twitter API)
3587 throw new BadRequestException('Message id not specified');
3590 // add parent-uri to sql command if specified by calling app
3591 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3593 // get data of the specified message id
3595 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3600 // error message if specified id is not in database
3601 if (!DBA::isResult($r)) {
3602 if ($verbose == "true") {
3603 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3604 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3606 /// @todo BadRequestException ok for Twitter API clients?
3607 throw new BadRequestException('message id not in database');
3612 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3617 if ($verbose == "true") {
3620 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3621 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3623 $answer = ['result' => 'error', 'message' => 'unknown error'];
3624 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3627 /// @todo return JSON data like Twitter API not yet implemented
3630 /// @TODO move to top of file or somewhere better
3631 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3636 * @brief unfollow contact
3638 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3639 * @return string|array
3640 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3642 function api_friendships_destroy($type)
3646 if ($uid === false) {
3647 throw new ForbiddenException();
3650 $contact_id = defaults($_REQUEST, 'user_id');
3652 if (empty($contact_id)) {
3653 Logger::log("No user_id specified", Logger::DEBUG);
3654 throw new BadRequestException("no user_id specified");
3657 // Get Contact by given id
3658 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3660 if(!DBA::isResult($contact)) {
3661 Logger::log("No contact found for ID" . $contact_id, Logger::DEBUG);
3662 throw new NotFoundException("no contact found to given ID");
3665 $url = $contact["url"];
3667 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3668 $uid, Contact::SHARING, Contact::FRIEND, normalise_link($url),
3669 normalise_link($url), $url];
3670 $contact = DBA::selectFirst('contact', [], $condition);
3672 if (!DBA::isResult($contact)) {
3673 Logger::log("Not following Contact", Logger::DEBUG);
3674 throw new NotFoundException("Not following Contact");
3677 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3678 Logger::log("Not supported", Logger::DEBUG);
3679 throw new ExpectationFailedException("Not supported");
3682 $dissolve = ($contact['rel'] == Contact::SHARING);
3684 $owner = User::getOwnerDataById($uid);
3686 Contact::terminateFriendship($owner, $contact, $dissolve);
3689 Logger::log("No owner found", Logger::DEBUG);
3690 throw new NotFoundException("Error Processing Request");
3693 // Sharing-only contacts get deleted as there no relationship any more
3695 Contact::remove($contact['id']);
3697 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3700 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3701 unset($contact["uid"]);
3702 unset($contact["self"]);
3704 // Set screen_name since Twidere requests it
3705 $contact["screen_name"] = $contact["nick"];
3707 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3709 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3713 * @param string $type Return type (atom, rss, xml, json)
3714 * @param string $box
3715 * @param string $verbose
3717 * @return array|string
3719 function api_direct_messages_box($type, $box, $verbose)
3722 if (api_user() === false) {
3723 throw new ForbiddenException();
3726 $count = defaults($_GET, 'count', 20);
3727 $page = defaults($_REQUEST, 'page', 1) - 1;
3732 $since_id = defaults($_REQUEST, 'since_id', 0);
3733 $max_id = defaults($_REQUEST, 'max_id', 0);
3735 $user_id = defaults($_REQUEST, 'user_id', '');
3736 $screen_name = defaults($_REQUEST, 'screen_name', '');
3739 unset($_REQUEST["user_id"]);
3740 unset($_GET["user_id"]);
3742 unset($_REQUEST["screen_name"]);
3743 unset($_GET["screen_name"]);
3745 $user_info = api_get_user($a);
3746 if ($user_info === false) {
3747 throw new ForbiddenException();
3749 $profile_url = $user_info["url"];
3752 $start = $page * $count;
3757 if ($box=="sentbox") {
3758 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3759 } elseif ($box == "conversation") {
3760 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape(defaults($_GET, 'uri', '')) . "'";
3761 } elseif ($box == "all") {
3762 $sql_extra = "true";
3763 } elseif ($box == "inbox") {
3764 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3768 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3771 if ($user_id != "") {
3772 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3773 } elseif ($screen_name !="") {
3774 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3778 "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",
3784 if ($verbose == "true" && !DBA::isResult($r)) {
3785 $answer = ['result' => 'error', 'message' => 'no mails available'];
3786 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3790 foreach ($r as $item) {
3791 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3792 $recipient = $user_info;
3793 $sender = api_get_user($a, normalise_link($item['contact-url']));
3794 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3795 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3796 $sender = $user_info;
3799 if (isset($recipient) && isset($sender)) {
3800 $ret[] = api_format_messages($item, $recipient, $sender);
3805 $data = ['direct_message' => $ret];
3809 $data = api_rss_extra($a, $data, $user_info);
3812 return api_format_data("direct-messages", $type, $data);
3816 * Returns the most recent direct messages sent by the user.
3818 * @param string $type Return type (atom, rss, xml, json)
3820 * @return array|string
3821 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3823 function api_direct_messages_sentbox($type)
3825 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3826 return api_direct_messages_box($type, "sentbox", $verbose);
3830 * Returns the most recent direct messages sent to the user.
3832 * @param string $type Return type (atom, rss, xml, json)
3834 * @return array|string
3835 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3837 function api_direct_messages_inbox($type)
3839 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3840 return api_direct_messages_box($type, "inbox", $verbose);
3845 * @param string $type Return type (atom, rss, xml, json)
3847 * @return array|string
3849 function api_direct_messages_all($type)
3851 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3852 return api_direct_messages_box($type, "all", $verbose);
3857 * @param string $type Return type (atom, rss, xml, json)
3859 * @return array|string
3861 function api_direct_messages_conversation($type)
3863 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3864 return api_direct_messages_box($type, "conversation", $verbose);
3867 /// @TODO move to top of file or somewhere better
3868 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3869 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3870 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3871 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3874 * Returns an OAuth Request Token.
3876 * @see https://oauth.net/core/1.0/#auth_step1
3878 function api_oauth_request_token()
3880 $oauth1 = new FKOAuth1();
3882 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3883 } catch (Exception $e) {
3884 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3892 * Returns an OAuth Access Token.
3894 * @return array|string
3895 * @see https://oauth.net/core/1.0/#auth_step3
3897 function api_oauth_access_token()
3899 $oauth1 = new FKOAuth1();
3901 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3902 } catch (Exception $e) {
3903 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3910 /// @TODO move to top of file or somewhere better
3911 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3912 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3916 * @brief delete a complete photoalbum with all containing photos from database through api
3918 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3919 * @return string|array
3921 function api_fr_photoalbum_delete($type)
3923 if (api_user() === false) {
3924 throw new ForbiddenException();
3927 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3929 // we do not allow calls without album string
3931 throw new BadRequestException("no albumname specified");
3933 // check if album is existing
3935 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3939 if (!DBA::isResult($r)) {
3940 throw new BadRequestException("album not available");
3943 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3944 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3945 foreach ($r as $rr) {
3946 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
3947 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
3949 if (!DBA::isResult($photo_item)) {
3950 throw new InternalServerErrorException("problem with deleting items occured");
3952 Item::deleteForUser(['id' => $photo_item['id']], api_user());
3955 // now let's delete all photos from the album
3956 $result = DBA::delete('photo', ['uid' => api_user(), 'album' => $album]);
3958 // return success of deletion or error message
3960 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
3961 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
3963 throw new InternalServerErrorException("unknown error - deleting from database failed");
3968 * @brief update the name of the album for all photos of an album
3970 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3971 * @return string|array
3973 function api_fr_photoalbum_update($type)
3975 if (api_user() === false) {
3976 throw new ForbiddenException();
3979 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3980 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3982 // we do not allow calls without album string
3984 throw new BadRequestException("no albumname specified");
3986 if ($album_new == "") {
3987 throw new BadRequestException("no new albumname specified");
3989 // check if album is existing
3990 if (!DBA::exists('photo', ['uid' => api_user(), 'album' => $album])) {
3991 throw new BadRequestException("album not available");
3993 // now let's update all photos to the albumname
3994 $result = DBA::update('photo', ['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
3996 // return success of updating or error message
3998 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
3999 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4001 throw new InternalServerErrorException("unknown error - updating in database failed");
4007 * @brief list all photos of the authenticated user
4009 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4010 * @return string|array
4012 function api_fr_photos_list($type)
4014 if (api_user() === false) {
4015 throw new ForbiddenException();
4018 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4019 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4020 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4021 intval(local_user())
4024 'image/jpeg' => 'jpg',
4025 'image/png' => 'png',
4026 'image/gif' => 'gif'
4028 $data = ['photo'=>[]];
4029 if (DBA::isResult($r)) {
4030 foreach ($r as $rr) {
4032 $photo['id'] = $rr['resource-id'];
4033 $photo['album'] = $rr['album'];
4034 $photo['filename'] = $rr['filename'];
4035 $photo['type'] = $rr['type'];
4036 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4037 $photo['created'] = $rr['created'];
4038 $photo['edited'] = $rr['edited'];
4039 $photo['desc'] = $rr['desc'];
4041 if ($type == "xml") {
4042 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4044 $photo['thumb'] = $thumb;
4045 $data['photo'][] = $photo;
4049 return api_format_data("photos", $type, $data);
4053 * @brief upload a new photo or change an existing photo
4055 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4056 * @return string|array
4058 function api_fr_photo_create_update($type)
4060 if (api_user() === false) {
4061 throw new ForbiddenException();
4064 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4065 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4066 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4067 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4068 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4069 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4070 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4071 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4072 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4074 // do several checks on input parameters
4075 // we do not allow calls without album string
4076 if ($album == null) {
4077 throw new BadRequestException("no albumname specified");
4079 // if photo_id == null --> we are uploading a new photo
4080 if ($photo_id == null) {
4083 // error if no media posted in create-mode
4084 if (!x($_FILES, 'media')) {
4086 throw new BadRequestException("no media data submitted");
4089 // album_new will be ignored in create-mode
4094 // check if photo is existing in database
4096 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4098 DBA::escape($photo_id),
4101 if (!DBA::isResult($r)) {
4102 throw new BadRequestException("photo not available");
4106 // checks on acl strings provided by clients
4107 $acl_input_error = false;
4108 $acl_input_error |= check_acl_input($allow_cid);
4109 $acl_input_error |= check_acl_input($deny_cid);
4110 $acl_input_error |= check_acl_input($allow_gid);
4111 $acl_input_error |= check_acl_input($deny_gid);
4112 if ($acl_input_error) {
4113 throw new BadRequestException("acl data invalid");
4115 // now let's upload the new media in create-mode
4116 if ($mode == "create") {
4117 $media = $_FILES['media'];
4118 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4120 // return success of updating or error message
4121 if (!is_null($data)) {
4122 return api_format_data("photo_create", $type, $data);
4124 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4128 // now let's do the changes in update-mode
4129 if ($mode == "update") {
4132 if (!is_null($desc)) {
4133 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4136 if (!is_null($album_new)) {
4137 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4140 if (!is_null($allow_cid)) {
4141 $allow_cid = trim($allow_cid);
4142 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4145 if (!is_null($deny_cid)) {
4146 $deny_cid = trim($deny_cid);
4147 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4150 if (!is_null($allow_gid)) {
4151 $allow_gid = trim($allow_gid);
4152 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4155 if (!is_null($deny_gid)) {
4156 $deny_gid = trim($deny_gid);
4157 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4161 if ($sql_extra != "") {
4162 $nothingtodo = false;
4164 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4166 DateTimeFormat::utcNow(), // update edited timestamp
4168 DBA::escape($photo_id),
4172 $nothingtodo = true;
4175 if (x($_FILES, 'media')) {
4176 $nothingtodo = false;
4177 $media = $_FILES['media'];
4178 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4179 if (!is_null($data)) {
4180 return api_format_data("photo_update", $type, $data);
4184 // return success of updating or error message
4186 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4187 return api_format_data("photo_update", $type, ['$result' => $answer]);
4190 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4191 return api_format_data("photo_update", $type, ['$result' => $answer]);
4193 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4196 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4200 * @brief delete a single photo from the database through api
4202 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4203 * @return string|array
4205 function api_fr_photo_delete($type)
4207 if (api_user() === false) {
4208 throw new ForbiddenException();
4211 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4213 // do several checks on input parameters
4214 // we do not allow calls without photo id
4215 if ($photo_id == null) {
4216 throw new BadRequestException("no photo_id specified");
4218 // check if photo is existing in database
4220 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4222 DBA::escape($photo_id)
4224 if (!DBA::isResult($r)) {
4225 throw new BadRequestException("photo not available");
4227 // now we can perform on the deletion of the photo
4228 $result = DBA::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4230 // return success of deletion or error message
4232 // retrieve the id of the parent element (the photo element)
4233 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4234 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4236 if (!DBA::isResult($photo_item)) {
4237 throw new InternalServerErrorException("problem with deleting items occured");
4239 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4240 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4241 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4243 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4244 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4246 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4252 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4254 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4255 * @return string|array
4257 function api_fr_photo_detail($type)
4259 if (api_user() === false) {
4260 throw new ForbiddenException();
4262 if (!x($_REQUEST, 'photo_id')) {
4263 throw new BadRequestException("No photo id.");
4266 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4267 $photo_id = $_REQUEST['photo_id'];
4269 // prepare json/xml output with data from database for the requested photo
4270 $data = prepare_photo_data($type, $scale, $photo_id);
4272 return api_format_data("photo_detail", $type, $data);
4277 * Updates the user’s profile image.
4279 * @brief updates the profile image for the user (either a specified profile or the default profile)
4281 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4283 * @return string|array
4284 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4286 function api_account_update_profile_image($type)
4288 if (api_user() === false) {
4289 throw new ForbiddenException();
4292 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4294 // error if image data is missing
4295 if (!x($_FILES, 'image')) {
4296 throw new BadRequestException("no media data submitted");
4299 // check if specified profile id is valid
4300 if ($profile_id != 0) {
4301 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4302 // error message if specified profile id is not in database
4303 if (!DBA::isResult($profile)) {
4304 throw new BadRequestException("profile_id not available");
4306 $is_default_profile = $profile['is-default'];
4308 $is_default_profile = 1;
4311 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4313 if (x($_FILES, 'image')) {
4314 $media = $_FILES['image'];
4315 } elseif (x($_FILES, 'media')) {
4316 $media = $_FILES['media'];
4318 // save new profile image
4319 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4322 if (is_array($media['type'])) {
4323 $filetype = $media['type'][0];
4325 $filetype = $media['type'];
4327 if ($filetype == "image/jpeg") {
4329 } elseif ($filetype == "image/png") {
4332 throw new InternalServerErrorException('Unsupported filetype');
4335 // change specified profile or all profiles to the new resource-id
4336 if ($is_default_profile) {
4337 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4338 DBA::update('photo', ['profile' => false], $condition);
4340 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype,
4341 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype];
4342 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4345 Contact::updateSelfFromUserID(api_user(), true);
4347 // Update global directory in background
4348 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4349 if ($url && strlen(Config::get('system', 'directory'))) {
4350 Worker::add(PRIORITY_LOW, "Directory", $url);
4353 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4355 // output for client
4357 return api_account_verify_credentials($type);
4359 // SaveMediaToDatabase failed for some reason
4360 throw new InternalServerErrorException("image upload failed");
4364 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4365 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4366 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4367 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4368 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4369 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4370 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4371 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4372 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4375 * Update user profile
4377 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4379 * @return array|string
4381 function api_account_update_profile($type)
4383 $local_user = api_user();
4384 $api_user = api_get_user(get_app());
4386 if (!empty($_POST['name'])) {
4387 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4388 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4389 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4390 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4393 if (isset($_POST['description'])) {
4394 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4395 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4396 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4399 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4400 // Update global directory in background
4401 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4402 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4405 return api_account_verify_credentials($type);
4408 /// @TODO move to top of file or somewhere better
4409 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4413 * @param string $acl_string
4415 function check_acl_input($acl_string)
4417 if ($acl_string == null || $acl_string == " ") {
4420 $contact_not_found = false;
4422 // split <x><y><z> into array of cid's
4423 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4425 // check for each cid if it is available on server
4426 $cid_array = $array[0];
4427 foreach ($cid_array as $cid) {
4428 $cid = str_replace("<", "", $cid);
4429 $cid = str_replace(">", "", $cid);
4430 $condition = ['id' => $cid, 'uid' => api_user()];
4431 $contact_not_found |= !DBA::exists('contact', $condition);
4433 return $contact_not_found;
4438 * @param string $mediatype
4439 * @param array $media
4440 * @param string $type
4441 * @param string $album
4442 * @param string $allow_cid
4443 * @param string $deny_cid
4444 * @param string $allow_gid
4445 * @param string $deny_gid
4446 * @param string $desc
4447 * @param integer $profile
4448 * @param boolean $visibility
4449 * @param string $photo_id
4451 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)
4459 if (is_array($media)) {
4460 if (is_array($media['tmp_name'])) {
4461 $src = $media['tmp_name'][0];
4463 $src = $media['tmp_name'];
4465 if (is_array($media['name'])) {
4466 $filename = basename($media['name'][0]);
4468 $filename = basename($media['name']);
4470 if (is_array($media['size'])) {
4471 $filesize = intval($media['size'][0]);
4473 $filesize = intval($media['size']);
4475 if (is_array($media['type'])) {
4476 $filetype = $media['type'][0];
4478 $filetype = $media['type'];
4482 if ($filetype == "") {
4483 $filetype=Image::guessType($filename);
4485 $imagedata = @getimagesize($src);
4487 $filetype = $imagedata['mime'];
4490 "File upload src: " . $src . " - filename: " . $filename .
4491 " - size: " . $filesize . " - type: " . $filetype,
4495 // check if there was a php upload error
4496 if ($filesize == 0 && $media['error'] == 1) {
4497 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4499 // check against max upload size within Friendica instance
4500 $maximagesize = Config::get('system', 'maximagesize');
4501 if ($maximagesize && ($filesize > $maximagesize)) {
4502 $formattedBytes = formatBytes($maximagesize);
4503 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4506 // create Photo instance with the data of the image
4507 $imagedata = @file_get_contents($src);
4508 $Image = new Image($imagedata, $filetype);
4509 if (!$Image->isValid()) {
4510 throw new InternalServerErrorException("unable to process image data");
4513 // check orientation of image
4514 $Image->orient($src);
4517 // check max length of images on server
4518 $max_length = Config::get('system', 'max_image_length');
4520 $max_length = MAX_IMAGE_LENGTH;
4522 if ($max_length > 0) {
4523 $Image->scaleDown($max_length);
4524 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4526 $width = $Image->getWidth();
4527 $height = $Image->getHeight();
4529 // create a new resource-id if not already provided
4530 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4532 if ($mediatype == "photo") {
4533 // upload normal image (scales 0, 1, 2)
4534 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4536 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4538 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4540 if ($width > 640 || $height > 640) {
4541 $Image->scaleDown(640);
4542 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4544 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4548 if ($width > 320 || $height > 320) {
4549 $Image->scaleDown(320);
4550 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4552 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4555 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4556 } elseif ($mediatype == "profileimage") {
4557 // upload profile image (scales 4, 5, 6)
4558 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4560 if ($width > 300 || $height > 300) {
4561 $Image->scaleDown(300);
4562 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4564 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4568 if ($width > 80 || $height > 80) {
4569 $Image->scaleDown(80);
4570 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4572 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4576 if ($width > 48 || $height > 48) {
4577 $Image->scaleDown(48);
4578 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4580 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4583 $Image->__destruct();
4584 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4587 if (isset($r) && $r) {
4588 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4589 if ($photo_id == null && $mediatype == "photo") {
4590 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4592 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4593 return prepare_photo_data($type, false, $hash);
4595 throw new InternalServerErrorException("image upload failed");
4601 * @param string $hash
4602 * @param string $allow_cid
4603 * @param string $deny_cid
4604 * @param string $allow_gid
4605 * @param string $deny_gid
4606 * @param string $filetype
4607 * @param boolean $visibility
4609 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4611 // get data about the api authenticated user
4612 $uri = Item::newURI(intval(api_user()));
4613 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4616 $arr['guid'] = System::createUUID();
4617 $arr['uid'] = intval(api_user());
4619 $arr['parent-uri'] = $uri;
4620 $arr['type'] = 'photo';
4622 $arr['resource-id'] = $hash;
4623 $arr['contact-id'] = $owner_record['id'];
4624 $arr['owner-name'] = $owner_record['name'];
4625 $arr['owner-link'] = $owner_record['url'];
4626 $arr['owner-avatar'] = $owner_record['thumb'];
4627 $arr['author-name'] = $owner_record['name'];
4628 $arr['author-link'] = $owner_record['url'];
4629 $arr['author-avatar'] = $owner_record['thumb'];
4631 $arr['allow_cid'] = $allow_cid;
4632 $arr['allow_gid'] = $allow_gid;
4633 $arr['deny_cid'] = $deny_cid;
4634 $arr['deny_gid'] = $deny_gid;
4635 $arr['visible'] = $visibility;
4639 'image/jpeg' => 'jpg',
4640 'image/png' => 'png',
4641 'image/gif' => 'gif'
4644 // adds link to the thumbnail scale photo
4645 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4646 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4649 // do the magic for storing the item in the database and trigger the federation to other contacts
4655 * @param string $type
4657 * @param string $photo_id
4661 function prepare_photo_data($type, $scale, $photo_id)
4664 $user_info = api_get_user($a);
4666 if ($user_info === false) {
4667 throw new ForbiddenException();
4670 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4671 $data_sql = ($scale === false ? "" : "data, ");
4673 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4674 // clients needs to convert this in their way for further processing
4676 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4677 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4678 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4679 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4681 intval(local_user()),
4682 DBA::escape($photo_id),
4687 'image/jpeg' => 'jpg',
4688 'image/png' => 'png',
4689 'image/gif' => 'gif'
4692 // prepare output data for photo
4693 if (DBA::isResult($r)) {
4694 $data = ['photo' => $r[0]];
4695 $data['photo']['id'] = $data['photo']['resource-id'];
4696 if ($scale !== false) {
4697 $data['photo']['data'] = base64_encode($data['photo']['data']);
4699 unset($data['photo']['datasize']); //needed only with scale param
4701 if ($type == "xml") {
4702 $data['photo']['links'] = [];
4703 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4704 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4706 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4709 $data['photo']['link'] = [];
4710 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4712 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4713 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4717 unset($data['photo']['resource-id']);
4718 unset($data['photo']['minscale']);
4719 unset($data['photo']['maxscale']);
4721 throw new NotFoundException();
4724 // retrieve item element for getting activities (like, dislike etc.) related to photo
4725 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4726 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4728 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4730 // retrieve comments on photo
4731 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4732 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4734 $statuses = Item::selectForUser(api_user(), [], $condition);
4736 // prepare output of comments
4737 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
4739 if ($type == "xml") {
4741 foreach ($commentData as $comment) {
4742 $comments[$k++ . ":comment"] = $comment;
4745 foreach ($commentData as $comment) {
4746 $comments[] = $comment;
4749 $data['photo']['friendica_comments'] = $comments;
4751 // include info if rights on photo and rights on item are mismatching
4752 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4753 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4754 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4755 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4756 $data['photo']['rights_mismatch'] = $rights_mismatch;
4763 * Similar as /mod/redir.php
4764 * redirect to 'url' after dfrn auth
4766 * Why this when there is mod/redir.php already?
4767 * This use api_user() and api_login()
4770 * c_url: url of remote contact to auth to
4771 * url: string, url to redirect after auth
4773 function api_friendica_remoteauth()
4775 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4776 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4778 if ($url === '' || $c_url === '') {
4779 throw new BadRequestException("Wrong parameters.");
4782 $c_url = normalise_link($c_url);
4786 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4788 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
4789 throw new BadRequestException("Unknown contact");
4792 $cid = $contact['id'];
4794 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4796 if ($contact['duplex'] && $contact['issued-id']) {
4797 $orig_id = $contact['issued-id'];
4798 $dfrn_id = '1:' . $orig_id;
4800 if ($contact['duplex'] && $contact['dfrn-id']) {
4801 $orig_id = $contact['dfrn-id'];
4802 $dfrn_id = '0:' . $orig_id;
4805 $sec = random_string();
4807 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4808 'sec' => $sec, 'expire' => time() + 45];
4809 DBA::insert('profile_check', $fields);
4811 Logger::log($contact['name'] . ' ' . $sec, Logger::DEBUG);
4812 $dest = ($url ? '&destination_url=' . $url : '');
4814 System::externalRedirect(
4815 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4816 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4817 . '&type=profile&sec=' . $sec . $dest
4820 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4823 * @brief Return the item shared, if the item contains only the [share] tag
4825 * @param array $item Sharer item
4826 * @return array|false Shared item or false if not a reshare
4828 function api_share_as_retweet(&$item)
4830 $body = trim($item["body"]);
4832 if (Diaspora::isReshare($body, false) === false) {
4833 if ($item['author-id'] == $item['owner-id']) {
4836 // Reshares from OStatus, ActivityPub and Twitter
4837 $reshared_item = $item;
4838 $reshared_item['owner-id'] = $reshared_item['author-id'];
4839 $reshared_item['owner-link'] = $reshared_item['author-link'];
4840 $reshared_item['owner-name'] = $reshared_item['author-name'];
4841 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
4842 return $reshared_item;
4846 /// @TODO "$1" should maybe mean '$1' ?
4847 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4849 * Skip if there is no shared message in there
4850 * we already checked this in diaspora::isReshare()
4851 * but better one more than one less...
4853 if (($body == $attributes) || empty($attributes)) {
4857 // build the fake reshared item
4858 $reshared_item = $item;
4861 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4862 if (!empty($matches[1])) {
4863 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4866 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4867 if (!empty($matches[1])) {
4868 $author = $matches[1];
4872 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4873 if (!empty($matches[1])) {
4874 $profile = $matches[1];
4877 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4878 if (!empty($matches[1])) {
4879 $profile = $matches[1];
4883 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4884 if (!empty($matches[1])) {
4885 $avatar = $matches[1];
4888 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4889 if (!empty($matches[1])) {
4890 $avatar = $matches[1];
4894 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4895 if (!empty($matches[1])) {
4896 $link = $matches[1];
4899 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4900 if (!empty($matches[1])) {
4901 $link = $matches[1];
4905 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4906 if (!empty($matches[1])) {
4907 $posted = $matches[1];
4910 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4911 if (!empty($matches[1])) {
4912 $posted = $matches[1];
4915 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4917 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4921 $reshared_item["body"] = $shared_body;
4922 $reshared_item["author-name"] = $author;
4923 $reshared_item["author-link"] = $profile;
4924 $reshared_item["author-avatar"] = $avatar;
4925 $reshared_item["plink"] = $link;
4926 $reshared_item["created"] = $posted;
4927 $reshared_item["edited"] = $posted;
4929 return $reshared_item;
4934 * @param string $profile
4936 * @return string|false
4937 * @todo remove trailing junk from profile url
4938 * @todo pump.io check has to check the website
4940 function api_get_nick($profile)
4945 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4946 DBA::escape(normalise_link($profile))
4949 if (DBA::isResult($r)) {
4950 $nick = $r[0]["nick"];
4955 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4956 DBA::escape(normalise_link($profile))
4959 if (DBA::isResult($r)) {
4960 $nick = $r[0]["nick"];
4965 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4966 if ($friendica != $profile) {
4972 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4973 if ($diaspora != $profile) {
4979 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4980 if ($twitter != $profile) {
4987 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4988 if ($StatusnetHost != $profile) {
4989 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4990 if ($StatusnetUser != $profile) {
4991 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4992 $user = json_decode($UserData);
4994 $nick = $user->screen_name;
5000 // To-Do: look at the page if its really a pumpio site
5001 //if (!$nick == "") {
5002 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5003 // if ($pumpio != $profile)
5005 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5018 * @param array $item
5022 function api_in_reply_to($item)
5026 $in_reply_to['status_id'] = null;
5027 $in_reply_to['user_id'] = null;
5028 $in_reply_to['status_id_str'] = null;
5029 $in_reply_to['user_id_str'] = null;
5030 $in_reply_to['screen_name'] = null;
5032 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5033 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5034 if (DBA::isResult($parent)) {
5035 $in_reply_to['status_id'] = intval($parent['id']);
5037 $in_reply_to['status_id'] = intval($item['parent']);
5040 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5042 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5043 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5045 if (DBA::isResult($parent)) {
5046 if ($parent['author-nick'] == "") {
5047 $parent['author-nick'] = api_get_nick($parent['author-link']);
5050 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5051 $in_reply_to['user_id'] = intval($parent['author-id']);
5052 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5055 // There seems to be situation, where both fields are identical:
5056 // https://github.com/friendica/friendica/issues/1010
5057 // This is a bugfix for that.
5058 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5059 Logger::log('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], Logger::DEBUG);
5060 $in_reply_to['status_id'] = null;
5061 $in_reply_to['user_id'] = null;
5062 $in_reply_to['status_id_str'] = null;
5063 $in_reply_to['user_id_str'] = null;
5064 $in_reply_to['screen_name'] = null;
5068 return $in_reply_to;
5073 * @param string $text
5077 function api_clean_plain_items($text)
5079 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5081 $text = BBCode::cleanPictureLinks($text);
5082 $URLSearchString = "^\[\]";
5084 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5086 if ($include_entities == "true") {
5087 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5090 // Simplify "attachment" element
5091 $text = api_clean_attachments($text);
5097 * @brief Removes most sharing information for API text export
5099 * @param string $body The original body
5101 * @return string Cleaned body
5103 function api_clean_attachments($body)
5105 $data = BBCode::getAttachmentData($body);
5112 if (isset($data["text"])) {
5113 $body = $data["text"];
5115 if (($body == "") && isset($data["title"])) {
5116 $body = $data["title"];
5118 if (isset($data["url"])) {
5119 $body .= "\n".$data["url"];
5121 $body .= $data["after"];
5128 * @param array $contacts
5132 function api_best_nickname(&$contacts)
5136 if (count($contacts) == 0) {
5140 foreach ($contacts as $contact) {
5141 if ($contact["network"] == "") {
5142 $contact["network"] = "dfrn";
5143 $best_contact = [$contact];
5147 if (sizeof($best_contact) == 0) {
5148 foreach ($contacts as $contact) {
5149 if ($contact["network"] == "dfrn") {
5150 $best_contact = [$contact];
5155 if (sizeof($best_contact) == 0) {
5156 foreach ($contacts as $contact) {
5157 if ($contact["network"] == "dspr") {
5158 $best_contact = [$contact];
5163 if (sizeof($best_contact) == 0) {
5164 foreach ($contacts as $contact) {
5165 if ($contact["network"] == "stat") {
5166 $best_contact = [$contact];
5171 if (sizeof($best_contact) == 0) {
5172 foreach ($contacts as $contact) {
5173 if ($contact["network"] == "pump") {
5174 $best_contact = [$contact];
5179 if (sizeof($best_contact) == 0) {
5180 foreach ($contacts as $contact) {
5181 if ($contact["network"] == "twit") {
5182 $best_contact = [$contact];
5187 if (sizeof($best_contact) == 1) {
5188 $contacts = $best_contact;
5190 $contacts = [$contacts[0]];
5195 * Return all or a specified group of the user with the containing contacts.
5197 * @param string $type Return type (atom, rss, xml, json)
5199 * @return array|string
5201 function api_friendica_group_show($type)
5205 if (api_user() === false) {
5206 throw new ForbiddenException();
5210 $user_info = api_get_user($a);
5211 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5212 $uid = $user_info['uid'];
5214 // get data of the specified group id or all groups if not specified
5217 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5221 // error message if specified gid is not in database
5222 if (!DBA::isResult($r)) {
5223 throw new BadRequestException("gid not available");
5227 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5232 // loop through all groups and retrieve all members for adding data in the user array
5234 foreach ($r as $rr) {
5235 $members = Contact::getByGroupId($rr['id']);
5238 if ($type == "xml") {
5239 $user_element = "users";
5241 foreach ($members as $member) {
5242 $user = api_get_user($a, $member['nurl']);
5243 $users[$k++.":user"] = $user;
5246 $user_element = "user";
5247 foreach ($members as $member) {
5248 $user = api_get_user($a, $member['nurl']);
5252 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5254 return api_format_data("groups", $type, ['group' => $grps]);
5256 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5260 * Delete the specified group of the user.
5262 * @param string $type Return type (atom, rss, xml, json)
5264 * @return array|string
5266 function api_friendica_group_delete($type)
5270 if (api_user() === false) {
5271 throw new ForbiddenException();
5275 $user_info = api_get_user($a);
5276 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5277 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5278 $uid = $user_info['uid'];
5280 // error if no gid specified
5281 if ($gid == 0 || $name == "") {
5282 throw new BadRequestException('gid or name not specified');
5285 // get data of the specified group id
5287 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5291 // error message if specified gid is not in database
5292 if (!DBA::isResult($r)) {
5293 throw new BadRequestException('gid not available');
5296 // get data of the specified group id and group name
5298 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5303 // error message if specified gid is not in database
5304 if (!DBA::isResult($rname)) {
5305 throw new BadRequestException('wrong group name');
5309 $ret = Group::removeByName($uid, $name);
5312 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5313 return api_format_data("group_delete", $type, ['result' => $success]);
5315 throw new BadRequestException('other API error');
5318 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5323 * @param string $type Return type (atom, rss, xml, json)
5325 * @return array|string
5326 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5328 function api_lists_destroy($type)
5332 if (api_user() === false) {
5333 throw new ForbiddenException();
5337 $user_info = api_get_user($a);
5338 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5339 $uid = $user_info['uid'];
5341 // error if no gid specified
5343 throw new BadRequestException('gid not specified');
5346 // get data of the specified group id
5347 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5348 // error message if specified gid is not in database
5350 throw new BadRequestException('gid not available');
5353 if (Group::remove($gid)) {
5355 'name' => $group['name'],
5356 'id' => intval($gid),
5357 'id_str' => (string) $gid,
5358 'user' => $user_info
5361 return api_format_data("lists", $type, ['lists' => $list]);
5364 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5367 * Add a new group to the database.
5369 * @param string $name Group name
5370 * @param int $uid User ID
5371 * @param array $users List of users to add to the group
5375 function group_create($name, $uid, $users = [])
5377 // error if no name specified
5379 throw new BadRequestException('group name not specified');
5382 // get data of the specified group name
5384 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5388 // error message if specified group name already exists
5389 if (DBA::isResult($rname)) {
5390 throw new BadRequestException('group name already exists');
5393 // check if specified group name is a deleted group
5395 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5399 // error message if specified group name already exists
5400 if (DBA::isResult($rname)) {
5401 $reactivate_group = true;
5405 $ret = Group::create($uid, $name);
5407 $gid = Group::getIdByName($uid, $name);
5409 throw new BadRequestException('other API error');
5413 $erroraddinguser = false;
5415 foreach ($users as $user) {
5416 $cid = $user['cid'];
5417 // check if user really exists as contact
5419 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5423 if (count($contact)) {
5424 Group::addMember($gid, $cid);
5426 $erroraddinguser = true;
5427 $errorusers[] = $cid;
5431 // return success message incl. missing users in array
5432 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5434 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5438 * Create the specified group with the posted array of contacts.
5440 * @param string $type Return type (atom, rss, xml, json)
5442 * @return array|string
5444 function api_friendica_group_create($type)
5448 if (api_user() === false) {
5449 throw new ForbiddenException();
5453 $user_info = api_get_user($a);
5454 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5455 $uid = $user_info['uid'];
5456 $json = json_decode($_POST['json'], true);
5457 $users = $json['user'];
5459 $success = group_create($name, $uid, $users);
5461 return api_format_data("group_create", $type, ['result' => $success]);
5463 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5466 * Create a new group.
5468 * @param string $type Return type (atom, rss, xml, json)
5470 * @return array|string
5471 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5473 function api_lists_create($type)
5477 if (api_user() === false) {
5478 throw new ForbiddenException();
5482 $user_info = api_get_user($a);
5483 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5484 $uid = $user_info['uid'];
5486 $success = group_create($name, $uid);
5487 if ($success['success']) {
5489 'name' => $success['name'],
5490 'id' => intval($success['gid']),
5491 'id_str' => (string) $success['gid'],
5492 'user' => $user_info
5495 return api_format_data("lists", $type, ['lists'=>$grp]);
5498 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5501 * Update the specified group with the posted array of contacts.
5503 * @param string $type Return type (atom, rss, xml, json)
5505 * @return array|string
5507 function api_friendica_group_update($type)
5511 if (api_user() === false) {
5512 throw new ForbiddenException();
5516 $user_info = api_get_user($a);
5517 $uid = $user_info['uid'];
5518 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5519 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5520 $json = json_decode($_POST['json'], true);
5521 $users = $json['user'];
5523 // error if no name specified
5525 throw new BadRequestException('group name not specified');
5528 // error if no gid specified
5530 throw new BadRequestException('gid not specified');
5534 $members = Contact::getByGroupId($gid);
5535 foreach ($members as $member) {
5536 $cid = $member['id'];
5537 foreach ($users as $user) {
5538 $found = ($user['cid'] == $cid ? true : false);
5540 if (!isset($found) || !$found) {
5541 Group::removeMemberByName($uid, $name, $cid);
5546 $erroraddinguser = false;
5548 foreach ($users as $user) {
5549 $cid = $user['cid'];
5550 // check if user really exists as contact
5552 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5557 if (count($contact)) {
5558 Group::addMember($gid, $cid);
5560 $erroraddinguser = true;
5561 $errorusers[] = $cid;
5565 // return success message incl. missing users in array
5566 $status = ($erroraddinguser ? "missing user" : "ok");
5567 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5568 return api_format_data("group_update", $type, ['result' => $success]);
5571 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5574 * Update information about a group.
5576 * @param string $type Return type (atom, rss, xml, json)
5578 * @return array|string
5579 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5581 function api_lists_update($type)
5585 if (api_user() === false) {
5586 throw new ForbiddenException();
5590 $user_info = api_get_user($a);
5591 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5592 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5593 $uid = $user_info['uid'];
5595 // error if no gid specified
5597 throw new BadRequestException('gid not specified');
5600 // get data of the specified group id
5601 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5602 // error message if specified gid is not in database
5604 throw new BadRequestException('gid not available');
5607 if (Group::update($gid, $name)) {
5610 'id' => intval($gid),
5611 'id_str' => (string) $gid,
5612 'user' => $user_info
5615 return api_format_data("lists", $type, ['lists' => $list]);
5619 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5623 * @param string $type Return type (atom, rss, xml, json)
5625 * @return array|string
5627 function api_friendica_activity($type)
5631 if (api_user() === false) {
5632 throw new ForbiddenException();
5634 $verb = strtolower($a->argv[3]);
5635 $verb = preg_replace("|\..*$|", "", $verb);
5637 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5639 $res = Item::performLike($id, $verb);
5642 if ($type == "xml") {
5647 return api_format_data('ok', $type, ['ok' => $ok]);
5649 throw new BadRequestException('Error adding activity');
5653 /// @TODO move to top of file or somewhere better
5654 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5655 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5656 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5657 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5658 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5659 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5660 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5661 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5662 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5663 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5666 * @brief Returns notifications
5668 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5669 * @return string|array
5671 function api_friendica_notification($type)
5675 if (api_user() === false) {
5676 throw new ForbiddenException();
5679 throw new BadRequestException("Invalid argument count");
5681 $nm = new NotificationsManager();
5683 $notes = $nm->getAll([], "+seen -date", 50);
5685 if ($type == "xml") {
5687 if (!empty($notes)) {
5688 foreach ($notes as $note) {
5689 $xmlnotes[] = ["@attributes" => $note];
5696 return api_format_data("notes", $type, ['note' => $notes]);
5700 * POST request with 'id' param as notification id
5702 * @brief Set notification as seen and returns associated item (if possible)
5704 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5705 * @return string|array
5707 function api_friendica_notification_seen($type)
5710 $user_info = api_get_user($a);
5712 if (api_user() === false || $user_info === false) {
5713 throw new ForbiddenException();
5716 throw new BadRequestException("Invalid argument count");
5719 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5721 $nm = new NotificationsManager();
5722 $note = $nm->getByID($id);
5723 if (is_null($note)) {
5724 throw new BadRequestException("Invalid argument");
5727 $nm->setSeen($note);
5728 if ($note['otype']=='item') {
5729 // would be really better with an ItemsManager and $im->getByID() :-P
5730 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5731 if (DBA::isResult($item)) {
5732 // we found the item, return it to the user
5733 $ret = api_format_items([$item], $user_info, false, $type);
5734 $data = ['status' => $ret];
5735 return api_format_data("status", $type, $data);
5737 // the item can't be found, but we set the note as seen, so we count this as a success
5739 return api_format_data('result', $type, ['result' => "success"]);
5742 /// @TODO move to top of file or somewhere better
5743 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5744 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5747 * @brief update a direct_message to seen state
5749 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5750 * @return string|array (success result=ok, error result=error with error message)
5752 function api_friendica_direct_messages_setseen($type)
5755 if (api_user() === false) {
5756 throw new ForbiddenException();
5760 $user_info = api_get_user($a);
5761 $uid = $user_info['uid'];
5762 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5764 // return error if id is zero
5766 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5767 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5770 // error message if specified id is not in database
5771 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5772 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5773 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5776 // update seen indicator
5777 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5781 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5782 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5784 $answer = ['result' => 'error', 'message' => 'unknown error'];
5785 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5789 /// @TODO move to top of file or somewhere better
5790 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5793 * @brief search for direct_messages containing a searchstring through api
5795 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5796 * @param string $box
5797 * @return string|array (success: success=true if found and search_result contains found messages,
5798 * success=false if nothing was found, search_result='nothing found',
5799 * error: result=error with error message)
5801 function api_friendica_direct_messages_search($type, $box = "")
5805 if (api_user() === false) {
5806 throw new ForbiddenException();
5810 $user_info = api_get_user($a);
5811 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5812 $uid = $user_info['uid'];
5814 // error if no searchstring specified
5815 if ($searchstring == "") {
5816 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5817 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5820 // get data for the specified searchstring
5822 "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",
5824 DBA::escape('%'.$searchstring.'%')
5827 $profile_url = $user_info["url"];
5829 // message if nothing was found
5830 if (!DBA::isResult($r)) {
5831 $success = ['success' => false, 'search_results' => 'problem with query'];
5832 } elseif (count($r) == 0) {
5833 $success = ['success' => false, 'search_results' => 'nothing found'];
5836 foreach ($r as $item) {
5837 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5838 $recipient = $user_info;
5839 $sender = api_get_user($a, normalise_link($item['contact-url']));
5840 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5841 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5842 $sender = $user_info;
5845 if (isset($recipient) && isset($sender)) {
5846 $ret[] = api_format_messages($item, $recipient, $sender);
5849 $success = ['success' => true, 'search_results' => $ret];
5852 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5855 /// @TODO move to top of file or somewhere better
5856 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5859 * @brief return data of all the profiles a user has to the client
5861 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5862 * @return string|array
5864 function api_friendica_profile_show($type)
5868 if (api_user() === false) {
5869 throw new ForbiddenException();
5873 $profile_id = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5875 // retrieve general information about profiles for user
5876 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5877 $directory = Config::get('system', 'directory');
5879 // get data of the specified profile id or all profiles of the user if not specified
5880 if ($profile_id != 0) {
5882 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5887 // error message if specified gid is not in database
5888 if (!DBA::isResult($r)) {
5889 throw new BadRequestException("profile_id not available");
5893 "SELECT * FROM `profile` WHERE `uid` = %d",
5897 // loop through all returned profiles and retrieve data and users
5900 foreach ($r as $rr) {
5901 $profile = api_format_items_profiles($rr);
5903 // select all users from contact table, loop and prepare standard return for user data
5906 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5911 foreach ($nurls as $nurl) {
5912 $user = api_get_user($a, $nurl['nurl']);
5913 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5915 $profile['users'] = $users;
5917 // add prepared profile data to array for final return
5918 if ($type == "xml") {
5919 $profiles[$k++ . ":profile"] = $profile;
5921 $profiles[] = $profile;
5925 // return settings, authenticated user and profiles data
5926 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
5928 $result = ['multi_profiles' => $multi_profiles ? true : false,
5929 'global_dir' => $directory,
5930 'friendica_owner' => api_get_user($a, $self['nurl']),
5931 'profiles' => $profiles];
5932 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5934 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5937 * Returns a list of saved searches.
5939 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5941 * @param string $type Return format: json or xml
5943 * @return string|array
5945 function api_saved_searches_list($type)
5947 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
5950 while ($term = $terms->fetch()) {
5952 'created_at' => api_date(time()),
5953 'id' => intval($term['id']),
5954 'id_str' => $term['id'],
5955 'name' => $term['term'],
5957 'query' => $term['term']
5963 return api_format_data("terms", $type, ['terms' => $result]);
5966 /// @TODO move to top of file or somewhere better
5967 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5970 @TODO Maybe open to implement?
5972 [pagename] => api/1.1/statuses/lookup.json
5973 [id] => 605138389168451584
5974 [include_cards] => true
5975 [cards_platform] => Android-12
5976 [include_entities] => true
5977 [include_my_retweet] => 1
5979 [include_reply_count] => true
5980 [include_descendent_reply_count] => true
5984 Not implemented by now:
5985 statuses/retweets_of_me
5990 account/update_location
5991 account/update_profile_background_image
5994 friendica/profile/update
5995 friendica/profile/create
5996 friendica/profile/delete
5998 Not implemented in status.net:
5999 statuses/retweeted_to_me
6000 statuses/retweeted_by_me
6001 direct_messages/destroy
6003 account/update_delivery_device
6004 notifications/follow