3 * @file include/api.php
4 * Friendica implementation of statusnet/twitter API
6 * @todo Automatically detect if incoming data is HTML or BBCode
9 use Friendica\Content\Feature;
10 use Friendica\Core\System;
11 use Friendica\Core\Config;
12 use Friendica\Core\NotificationsManager;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\Worker;
15 use Friendica\Database\DBM;
16 use Friendica\Model\Contact;
17 use Friendica\Model\Group;
18 use Friendica\Model\Photo;
19 use Friendica\Model\User;
20 use Friendica\Network\FKOAuth1;
21 use Friendica\Network\HTTPException;
22 use Friendica\Network\HTTPException\BadRequestException;
23 use Friendica\Network\HTTPException\ForbiddenException;
24 use Friendica\Network\HTTPException\InternalServerErrorException;
25 use Friendica\Network\HTTPException\MethodNotAllowedException;
26 use Friendica\Network\HTTPException\NotFoundException;
27 use Friendica\Network\HTTPException\NotImplementedException;
28 use Friendica\Network\HTTPException\UnauthorizedException;
29 use Friendica\Network\HTTPException\TooManyRequestsException;
30 use Friendica\Object\Image;
31 use Friendica\Protocol\Diaspora;
32 use Friendica\Util\XML;
34 require_once 'include/bbcode.php';
35 require_once 'include/datetime.php';
36 require_once 'include/conversation.php';
37 require_once 'include/html2plain.php';
38 require_once 'mod/share.php';
39 require_once 'mod/item.php';
40 require_once 'include/security.php';
41 require_once 'include/contact_selectors.php';
42 require_once 'include/html2bbcode.php';
43 require_once 'mod/wall_upload.php';
44 require_once 'mod/proxy.php';
45 require_once 'include/message.php';
46 require_once 'include/like.php';
47 require_once 'include/plaintext.php';
49 define('API_METHOD_ANY', '*');
50 define('API_METHOD_GET', 'GET');
51 define('API_METHOD_POST', 'POST,PUT');
52 define('API_METHOD_DELETE', 'POST,DELETE');
58 * @brief Auth API user
60 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
61 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
62 * into a page, and visitors will post something without noticing it).
66 if (x($_SESSION, 'allow_api')) {
74 * @brief Get source name from API client
76 * Clients can send 'source' parameter to be show in post metadata
77 * as "sent via <source>".
78 * Some clients doesn't send a source param, we support ones we know
82 * Client source name, default to "api" if unset/unknown
86 if (requestdata('source')) {
87 return requestdata('source');
90 // Support for known clients that doesn't send a source name
91 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
95 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
101 * @brief Format date for API
103 * @param string $str Source date, as UTC
104 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
106 function api_date($str)
108 // Wed May 23 06:01:13 +0000 2007
109 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y");
113 * @brief Register API endpoint
115 * Register a function to be the endpont for defined API path.
117 * @param string $path API URL path, relative to System::baseUrl()
118 * @param string $func Function name to call on path request
119 * @param bool $auth API need logged user
120 * @param string $method HTTP method reqiured to call this endpoint.
121 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
122 * Default to API_METHOD_ANY
124 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
134 // Workaround for hotot
135 $path = str_replace("api/", "api/1.1/", $path);
145 * @brief Login API user
147 * Log in user via OAuth1 or Simple HTTP Auth.
148 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
150 * @param object $a App
151 * @hook 'authenticate'
153 * 'username' => username from login form
154 * 'password' => password from login form
155 * 'authenticated' => return status,
156 * 'user_record' => return authenticated user record
158 * array $user logged user record
160 function api_login(App $a)
162 $oauth1 = new FKOAuth1();
165 list($consumer, $token) = $oauth1->verify_request(OAuthRequest::from_request());
166 if (!is_null($token)) {
167 $oauth1->loginUser($token->uid);
168 call_hooks('logged_in', $a->user);
171 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
172 var_dump($consumer, $token);
174 } catch (Exception $e) {
178 // workaround for HTTP-auth in CGI mode
179 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
180 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
181 if (strlen($userpass)) {
182 list($name, $password) = explode(':', $userpass);
183 $_SERVER['PHP_AUTH_USER'] = $name;
184 $_SERVER['PHP_AUTH_PW'] = $password;
188 if (!x($_SERVER, 'PHP_AUTH_USER')) {
189 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
190 header('WWW-Authenticate: Basic realm="Friendica"');
191 throw new UnauthorizedException("This API requires login");
194 $user = $_SERVER['PHP_AUTH_USER'];
195 $password = $_SERVER['PHP_AUTH_PW'];
197 // allow "user@server" login (but ignore 'server' part)
198 $at = strstr($user, "@", true);
203 // next code from mod/auth.php. needs better solution
207 'username' => trim($user),
208 'password' => trim($password),
209 'authenticated' => 0,
210 'user_record' => null,
214 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
215 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
216 * and later plugins should not interfere with an earlier one that succeeded.
218 call_hooks('authenticate', $addon_auth);
220 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
221 $record = $addon_auth['user_record'];
223 $user_id = User::authenticate(trim($user), trim($password));
225 $record = dba::select('user', [], ['uid' => $user_id], ['limit' => 1]);
229 if (!$record || !count($record)) {
230 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
231 header('WWW-Authenticate: Basic realm="Friendica"');
232 //header('HTTP/1.0 401 Unauthorized');
233 //die('This api requires login');
234 throw new UnauthorizedException("This API requires login");
237 authenticate_success($record);
239 $_SESSION["allow_api"] = true;
241 call_hooks('logged_in', $a->user);
245 * @brief Check HTTP method of called API
247 * API endpoints can define which HTTP method to accept when called.
248 * This function check the current HTTP method agains endpoint
251 * @param string $method Required methods, uppercase, separated by comma
254 function api_check_method($method)
256 if ($method == "*") {
259 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
263 * @brief Main API entry point
265 * Authenticate user, call registered API function, set HTTP headers
267 * @param object $a App
268 * @return string API call result
270 function api_call(App $a)
272 global $API, $called_api;
275 if (strpos($a->query_string, ".xml") > 0) {
278 if (strpos($a->query_string, ".json") > 0) {
281 if (strpos($a->query_string, ".rss") > 0) {
284 if (strpos($a->query_string, ".atom") > 0) {
289 foreach ($API as $p => $info) {
290 if (strpos($a->query_string, $p) === 0) {
291 if (!api_check_method($info['method'])) {
292 throw new MethodNotAllowedException();
295 $called_api = explode("/", $p);
296 //unset($_SERVER['PHP_AUTH_USER']);
298 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
299 if ($info['auth'] === true && api_user() === false) {
303 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
304 logger('API parameters: ' . print_r($_REQUEST, true));
306 $stamp = microtime(true);
307 $r = call_user_func($info['func'], $type);
308 $duration = (float) (microtime(true) - $stamp);
309 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
311 if (Config::get("system", "profiler")) {
312 $duration = microtime(true)-$a->performance["start"];
314 /// @TODO round() really everywhere?
316 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
317 "Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
318 round($a->performance["database"] - $a->performance["database_write"], 3),
319 round($a->performance["database_write"], 3),
320 round($a->performance["network"], 2),
321 round($a->performance["file"], 2),
322 round($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
328 if (Config::get("rendertime", "callstack")) {
329 $o = "Database Read:\n";
330 foreach ($a->callstack["database"] as $func => $time) {
331 $time = round($time, 3);
333 $o .= $func . ": " . $time . "\n";
336 $o .= "\nDatabase Write:\n";
337 foreach ($a->callstack["database_write"] as $func => $time) {
338 $time = round($time, 3);
340 $o .= $func . ": " . $time . "\n";
344 $o .= "\nNetwork:\n";
345 foreach ($a->callstack["network"] as $func => $time) {
346 $time = round($time, 3);
348 $o .= $func . ": " . $time . "\n";
351 logger($o, LOGGER_DEBUG);
357 * api function returned false withour throw an
358 * exception. This should not happend, throw a 500
360 throw new InternalServerErrorException();
365 header("Content-Type: text/xml");
369 header("Content-Type: application/json");
371 $json = json_encode($rr);
372 if (x($_GET, 'callback')) {
373 $json = $_GET['callback'] . "(" . $json . ")";
378 header("Content-Type: application/rss+xml");
379 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
382 header("Content-Type: application/atom+xml");
383 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
389 logger('API call not implemented: ' . $a->query_string);
390 throw new NotImplementedException();
391 } catch (HTTPException $e) {
392 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
393 return api_error($type, $e);
398 * @brief Format API error string
400 * @param string $type Return type (xml, json, rss, as)
401 * @param object $e HTTPException Error object
402 * @return strin error message formatted as $type
404 function api_error($type, $e)
408 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
409 /// @TODO: https://dev.twitter.com/overview/api/response-codes
411 $error = array("error" => $error,
412 "code" => $e->httpcode . " " . $e->httpdesc,
413 "request" => $a->query_string);
415 $ret = api_format_data('status', $type, array('status' => $error));
419 header("Content-Type: text/xml");
423 header("Content-Type: application/json");
424 return json_encode($ret);
427 header("Content-Type: application/rss+xml");
431 header("Content-Type: application/atom+xml");
438 * @brief Set values for RSS template
441 * @param array $arr Array to be passed to template
442 * @param array $user_info User info
444 * @todo find proper type-hints
446 function api_rss_extra(App $a, $arr, $user_info)
448 if (is_null($user_info)) {
449 $user_info = api_get_user($a);
452 $arr['$user'] = $user_info;
453 $arr['$rss'] = array(
454 'alternate' => $user_info['url'],
455 'self' => System::baseUrl() . "/" . $a->query_string,
456 'base' => System::baseUrl(),
457 'updated' => api_date(null),
458 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
459 'language' => $user_info['language'],
460 'logo' => System::baseUrl() . "/images/friendica-32.png",
468 * @brief Unique contact to contact url.
470 * @param int $id Contact id
471 * @return bool|string
472 * Contact url or False if contact id is unknown
474 function api_unique_id_to_nurl($id)
476 $r = dba::select('contact', array('nurl'), array('uid' => 0, 'id' => $id), array('limit' => 1));
478 if (DBM::is_result($r)) {
486 * @brief Get user info array.
488 * @param object $a App
489 * @param int|string $contact_id Contact ID or URL
491 function api_get_user(App $a, $contact_id = null)
500 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
502 // Searching for contact URL
503 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
504 $user = dbesc(normalise_link($contact_id));
506 $extra_query = "AND `contact`.`nurl` = '%s' ";
507 if (api_user() !== false) {
508 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
512 // Searching for contact id with uid = 0
513 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
514 $user = dbesc(api_unique_id_to_nurl($contact_id));
517 throw new BadRequestException("User not found.");
521 $extra_query = "AND `contact`.`nurl` = '%s' ";
522 if (api_user() !== false) {
523 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
527 if (is_null($user) && x($_GET, 'user_id')) {
528 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
531 throw new BadRequestException("User not found.");
535 $extra_query = "AND `contact`.`nurl` = '%s' ";
536 if (api_user() !== false) {
537 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
540 if (is_null($user) && x($_GET, 'screen_name')) {
541 $user = dbesc($_GET['screen_name']);
543 $extra_query = "AND `contact`.`nick` = '%s' ";
544 if (api_user() !== false) {
545 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
549 if (is_null($user) && x($_GET, 'profileurl')) {
550 $user = dbesc(normalise_link($_GET['profileurl']));
552 $extra_query = "AND `contact`.`nurl` = '%s' ";
553 if (api_user() !== false) {
554 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
558 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
559 $argid = count($called_api);
560 list($user, $null) = explode(".", $a->argv[$argid]);
561 if (is_numeric($user)) {
562 $user = dbesc(api_unique_id_to_nurl($user));
569 $extra_query = "AND `contact`.`nurl` = '%s' ";
570 if (api_user() !== false) {
571 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
574 $user = dbesc($user);
576 $extra_query = "AND `contact`.`nick` = '%s' ";
577 if (api_user() !== false) {
578 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
583 logger("api_get_user: user ".$user, LOGGER_DEBUG);
586 if (api_user() === false) {
590 $user = $_SESSION['uid'];
591 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
595 logger('api_user: ' . $extra_query . ', user: ' . $user);
599 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
605 // Selecting the id by priority, friendica first
606 api_best_nickname($uinfo);
608 // if the contact wasn't found, fetch it from the contacts with uid = 0
609 if (!DBM::is_result($uinfo)) {
613 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
616 if (DBM::is_result($r)) {
617 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
619 // If no nick where given, extract it from the address
620 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
621 $r[0]['nick'] = api_get_nick($r[0]["url"]);
626 'id_str' => (string) $r[0]["id"],
627 'name' => $r[0]["name"],
628 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
629 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
630 'description' => $r[0]["about"],
631 'profile_image_url' => $r[0]["micro"],
632 'profile_image_url_https' => $r[0]["micro"],
633 'url' => $r[0]["url"],
634 'protected' => false,
635 'followers_count' => 0,
636 'friends_count' => 0,
638 'created_at' => api_date($r[0]["created"]),
639 'favourites_count' => 0,
641 'time_zone' => 'UTC',
642 'geo_enabled' => false,
644 'statuses_count' => 0,
646 'contributors_enabled' => false,
647 'is_translator' => false,
648 'is_translation_enabled' => false,
649 'following' => false,
650 'follow_request_sent' => false,
651 'statusnet_blocking' => false,
652 'notifications' => false,
653 'statusnet_profile_url' => $r[0]["url"],
655 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
657 'network' => $r[0]["network"],
662 throw new BadRequestException("User not found.");
666 if ($uinfo[0]['self']) {
667 if ($uinfo[0]['network'] == "") {
668 $uinfo[0]['network'] = NETWORK_DFRN;
672 "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
676 "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
680 /// @TODO old-lost code? (twice)
681 // Counting is deactivated by now, due to performance issues
682 // count public wall messages
683 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
684 // intval($uinfo[0]['uid'])
686 //$countitms = $r[0]['count'];
689 // Counting is deactivated by now, due to performance issues
690 //$r = q("SELECT count(*) as `count` FROM `item`
691 // WHERE `contact-id` = %d",
692 // intval($uinfo[0]['id'])
694 //$countitms = $r[0]['count'];
698 /// @TODO old-lost code? (twice)
700 // Counting is deactivated by now, due to performance issues
702 $r = q("SELECT count(*) as `count` FROM `contact`
703 WHERE `uid` = %d AND `rel` IN ( %d, %d )
704 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
705 intval($uinfo[0]['uid']),
706 intval(CONTACT_IS_SHARING),
707 intval(CONTACT_IS_FRIEND)
709 $countfriends = $r[0]['count'];
711 $r = q("SELECT count(*) as `count` FROM `contact`
712 WHERE `uid` = %d AND `rel` IN ( %d, %d )
713 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
714 intval($uinfo[0]['uid']),
715 intval(CONTACT_IS_FOLLOWER),
716 intval(CONTACT_IS_FRIEND)
718 $countfollowers = $r[0]['count'];
720 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
721 intval($uinfo[0]['uid'])
723 $starred = $r[0]['count'];
726 if (! $uinfo[0]['self']) {
736 // Add a nick if it isn't present there
737 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
738 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
741 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
743 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
746 'id' => intval($pcontact_id),
747 'id_str' => (string) intval($pcontact_id),
748 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
749 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
750 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
751 'description' => (($profile) ? $profile[0]['pdesc'] : null),
752 'profile_image_url' => $uinfo[0]['micro'],
753 'profile_image_url_https' => $uinfo[0]['micro'],
754 'url' => $uinfo[0]['url'],
755 'protected' => false,
756 'followers_count' => intval($countfollowers),
757 'friends_count' => intval($countfriends),
759 'created_at' => api_date($uinfo[0]['created']),
760 'favourites_count' => intval($starred),
762 'time_zone' => 'UTC',
763 'geo_enabled' => false,
765 'statuses_count' => intval($countitms),
767 'contributors_enabled' => false,
768 'is_translator' => false,
769 'is_translation_enabled' => false,
770 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
771 'follow_request_sent' => false,
772 'statusnet_blocking' => false,
773 'notifications' => false,
775 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
776 'statusnet_profile_url' => $uinfo[0]['url'],
777 'uid' => intval($uinfo[0]['uid']),
778 'cid' => intval($uinfo[0]['cid']),
779 'self' => $uinfo[0]['self'],
780 'network' => $uinfo[0]['network'],
783 // If this is a local user and it uses Frio, we can get its color preferences.
785 $theme_info = dba::select('user', ['theme'], ['uid' => $ret['uid']], ['limit' => 1]);
786 if ($theme_info['theme'] === 'frio') {
787 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
788 if ($schema && ($schema != '---')) {
789 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
790 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
791 require_once $schemefile;
794 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
795 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
796 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
802 $link_color = "#6fdbe8";
805 $bgcolor = "#ededed";
808 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
809 $ret['profile_link_color'] = str_replace('#', '', $link_color);
810 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
818 * @brief return api-formatted array for item's author and owner
820 * @param object $a App
821 * @param array $item item from db
822 * @return array(array:author, array:owner)
824 function api_item_get_user(App $a, $item)
826 $status_user = api_get_user($a, $item["author-link"]);
828 $status_user["protected"] = (($item["allow_cid"] != "") ||
829 ($item["allow_gid"] != "") ||
830 ($item["deny_cid"] != "") ||
831 ($item["deny_gid"] != "") ||
834 if ($item['thr-parent'] == $item['uri']) {
835 $owner_user = api_get_user($a, $item["owner-link"]);
837 $owner_user = $status_user;
840 return (array($status_user, $owner_user));
844 * @brief walks recursively through an array with the possibility to change value and key
846 * @param array $array The array to walk through
847 * @param string $callback The callback function
849 * @return array the transformed array
851 function api_walk_recursive(array &$array, callable $callback)
853 $new_array = array();
855 foreach ($array as $k => $v) {
857 if ($callback($v, $k)) {
858 $new_array[$k] = api_walk_recursive($v, $callback);
861 if ($callback($v, $k)) {
872 * @brief Callback function to transform the array in an array that can be transformed in a XML file
874 * @param mixed $item Array item value
875 * @param string $key Array key
877 * @return boolean Should the array item be deleted?
879 function api_reformat_xml(&$item, &$key)
881 if (is_bool($item)) {
882 $item = ($item ? "true" : "false");
885 if (substr($key, 0, 10) == "statusnet_") {
886 $key = "statusnet:".substr($key, 10);
887 } elseif (substr($key, 0, 10) == "friendica_") {
888 $key = "friendica:".substr($key, 10);
890 /// @TODO old-lost code?
892 // $key = "default:".$key;
898 * @brief Creates the XML from a JSON style array
900 * @param array $data JSON style array
901 * @param string $root_element Name of the root element
903 * @return string The XML data
905 function api_create_xml($data, $root_element)
907 $childname = key($data);
908 $data2 = array_pop($data);
911 $namespaces = array("" => "http://api.twitter.com",
912 "statusnet" => "http://status.net/schema/api/1/",
913 "friendica" => "http://friendi.ca/schema/api/1/",
914 "georss" => "http://www.georss.org/georss");
916 /// @todo Auto detection of needed namespaces
917 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
918 $namespaces = array();
921 if (is_array($data2)) {
922 api_walk_recursive($data2, "api_reformat_xml");
929 foreach ($data2 as $item) {
930 $data4[$i++.":".$childname] = $item;
936 $data3 = array($root_element => $data2);
938 $ret = XML::fromArray($data3, $xml, false, $namespaces);
943 * @brief Formats the data according to the data type
945 * @param string $root_element Name of the root element
946 * @param string $type Return type (atom, rss, xml, json)
947 * @param array $data JSON style array
949 * @return (string|object) XML data or JSON data
951 function api_format_data($root_element, $type, $data)
959 $ret = api_create_xml($data, $root_element);
974 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
975 * returns a 401 status code and an error message if not.
976 * http://developer.twitter.com/doc/get/account/verify_credentials
978 function api_account_verify_credentials($type)
983 if (api_user() === false) {
984 throw new ForbiddenException();
987 unset($_REQUEST["user_id"]);
988 unset($_GET["user_id"]);
990 unset($_REQUEST["screen_name"]);
991 unset($_GET["screen_name"]);
993 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
995 $user_info = api_get_user($a);
997 // "verified" isn't used here in the standard
998 unset($user_info["verified"]);
1000 // - Adding last status
1001 if (!$skip_status) {
1002 $user_info["status"] = api_status_show("raw");
1003 if (!count($user_info["status"])) {
1004 unset($user_info["status"]);
1006 unset($user_info["status"]["user"]);
1010 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1011 unset($user_info["uid"]);
1012 unset($user_info["self"]);
1014 return api_format_data("user", $type, array('user' => $user_info));
1017 /// @TODO move to top of file or somwhere better
1018 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1021 * Get data from $_POST or $_GET
1023 function requestdata($k)
1025 if (x($_POST, $k)) {
1034 /*Waitman Gobble Mod*/
1035 function api_statuses_mediap($type)
1039 if (api_user() === false) {
1040 logger('api_statuses_update: no user');
1041 throw new ForbiddenException();
1043 $user_info = api_get_user($a);
1045 $_REQUEST['type'] = 'wall';
1046 $_REQUEST['profile_uid'] = api_user();
1047 $_REQUEST['api_source'] = true;
1048 $txt = requestdata('status');
1049 /// @TODO old-lost code?
1050 //$txt = urldecode(requestdata('status'));
1052 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1053 $txt = html2bb_video($txt);
1054 $config = HTMLPurifier_Config::createDefault();
1055 $config->set('Cache.DefinitionImpl', null);
1056 $purifier = new HTMLPurifier($config);
1057 $txt = $purifier->purify($txt);
1059 $txt = html2bbcode($txt);
1061 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1063 // tell wall_upload function to return img info instead of echo
1064 $_REQUEST['hush'] = 'yeah';
1065 $bebop = wall_upload_post($a);
1067 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1068 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1071 // this should output the last post (the one we just posted).
1072 return api_status_show($type);
1075 /// @TODO move this to top of file or somewhere better!
1076 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1078 function api_statuses_update($type)
1083 if (api_user() === false) {
1084 logger('api_statuses_update: no user');
1085 throw new ForbiddenException();
1088 $user_info = api_get_user($a);
1090 // convert $_POST array items to the form we use for web posts.
1092 // logger('api_post: ' . print_r($_POST,true));
1094 if (requestdata('htmlstatus')) {
1095 $txt = requestdata('htmlstatus');
1096 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1097 $txt = html2bb_video($txt);
1099 $config = HTMLPurifier_Config::createDefault();
1100 $config->set('Cache.DefinitionImpl', null);
1102 $purifier = new HTMLPurifier($config);
1103 $txt = $purifier->purify($txt);
1105 $_REQUEST['body'] = html2bbcode($txt);
1108 $_REQUEST['body'] = requestdata('status');
1111 $_REQUEST['title'] = requestdata('title');
1113 $parent = requestdata('in_reply_to_status_id');
1115 // Twidere sends "-1" if it is no reply ...
1116 if ($parent == -1) {
1120 if (ctype_digit($parent)) {
1121 $_REQUEST['parent'] = $parent;
1123 $_REQUEST['parent_uri'] = $parent;
1126 if (requestdata('lat') && requestdata('long')) {
1127 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1129 $_REQUEST['profile_uid'] = api_user();
1132 $_REQUEST['type'] = 'net-comment';
1134 // Check for throttling (maximum posts per day, week and month)
1135 $throttle_day = Config::get('system', 'throttle_limit_day');
1136 if ($throttle_day > 0) {
1137 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1140 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1141 AND `created` > '%s' AND `id` = `parent`",
1146 if (DBM::is_result($r)) {
1147 $posts_day = $r[0]["posts_day"];
1152 if ($posts_day > $throttle_day) {
1153 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1154 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1155 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1159 $throttle_week = Config::get('system', 'throttle_limit_week');
1160 if ($throttle_week > 0) {
1161 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1164 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1165 AND `created` > '%s' AND `id` = `parent`",
1170 if (DBM::is_result($r)) {
1171 $posts_week = $r[0]["posts_week"];
1176 if ($posts_week > $throttle_week) {
1177 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1178 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1179 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1183 $throttle_month = Config::get('system', 'throttle_limit_month');
1184 if ($throttle_month > 0) {
1185 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1188 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1189 AND `created` > '%s' AND `id` = `parent`",
1194 if (DBM::is_result($r)) {
1195 $posts_month = $r[0]["posts_month"];
1200 if ($posts_month > $throttle_month) {
1201 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1202 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1203 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1207 $_REQUEST['type'] = 'wall';
1210 if (x($_FILES, 'media')) {
1211 // upload the image if we have one
1212 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1213 $media = wall_upload_post($a);
1214 if (strlen($media) > 0) {
1215 $_REQUEST['body'] .= "\n\n" . $media;
1219 // To-Do: Multiple IDs
1220 if (requestdata('media_ids')) {
1222 "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",
1223 intval(requestdata('media_ids')),
1226 if (DBM::is_result($r)) {
1227 $phototypes = Image::supportedTypes();
1228 $ext = $phototypes[$r[0]['type']];
1229 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1230 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1234 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1236 $_REQUEST['api_source'] = true;
1238 if (!x($_REQUEST, "source")) {
1239 $_REQUEST["source"] = api_source();
1242 // call out normal post function
1245 // this should output the last post (the one we just posted).
1246 return api_status_show($type);
1249 /// @TODO move to top of file or somwhere better
1250 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1251 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1253 function api_media_upload($type)
1257 if (api_user() === false) {
1259 throw new ForbiddenException();
1262 $user_info = api_get_user($a);
1264 if (!x($_FILES, 'media')) {
1266 throw new BadRequestException("No media.");
1269 $media = wall_upload_post($a, false);
1272 throw new InternalServerErrorException();
1275 $returndata = array();
1276 $returndata["media_id"] = $media["id"];
1277 $returndata["media_id_string"] = (string)$media["id"];
1278 $returndata["size"] = $media["size"];
1279 $returndata["image"] = array("w" => $media["width"],
1280 "h" => $media["height"],
1281 "image_type" => $media["type"]);
1283 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1285 return array("media" => $returndata);
1288 /// @TODO move to top of file or somwhere better
1289 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1291 function api_status_show($type)
1295 $user_info = api_get_user($a);
1297 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1299 if ($type == "raw") {
1300 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1305 // get last public wall message
1309 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1310 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1311 AND `item`.`type` != 'activity' $privacy_sql
1312 ORDER BY `item`.`id` DESC
1314 intval($user_info['cid']),
1316 dbesc($user_info['url']),
1317 dbesc(normalise_link($user_info['url'])),
1318 dbesc($user_info['url']),
1319 dbesc(normalise_link($user_info['url']))
1322 if (DBM::is_result($lastwall)) {
1323 $lastwall = $lastwall[0];
1325 $in_reply_to = api_in_reply_to($lastwall);
1327 $converted = api_convert_item($lastwall);
1329 if ($type == "xml") {
1330 $geo = "georss:point";
1335 $status_info = array(
1336 'created_at' => api_date($lastwall['created']),
1337 'id' => intval($lastwall['id']),
1338 'id_str' => (string) $lastwall['id'],
1339 'text' => $converted["text"],
1340 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1341 'truncated' => false,
1342 'in_reply_to_status_id' => $in_reply_to['status_id'],
1343 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1344 'in_reply_to_user_id' => $in_reply_to['user_id'],
1345 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1346 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1347 'user' => $user_info,
1349 'coordinates' => "",
1351 'contributors' => "",
1352 'is_quote_status' => false,
1353 'retweet_count' => 0,
1354 'favorite_count' => 0,
1355 'favorited' => $lastwall['starred'] ? true : false,
1356 'retweeted' => false,
1357 'possibly_sensitive' => false,
1359 'statusnet_html' => $converted["html"],
1360 'statusnet_conversation_id' => $lastwall['parent'],
1361 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1364 if (count($converted["attachments"]) > 0) {
1365 $status_info["attachments"] = $converted["attachments"];
1368 if (count($converted["entities"]) > 0) {
1369 $status_info["entities"] = $converted["entities"];
1372 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1373 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1374 } elseif (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1375 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1378 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1379 unset($status_info["user"]["uid"]);
1380 unset($status_info["user"]["self"]);
1383 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1385 if ($type == "raw") {
1386 return $status_info;
1389 return api_format_data("statuses", $type, array('status' => $status_info));
1393 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1394 * The author's most recent status will be returned inline.
1395 * http://developer.twitter.com/doc/get/users/show
1397 function api_users_show($type)
1401 $user_info = api_get_user($a);
1405 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1406 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1407 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1408 AND `type`!='activity'
1409 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1413 dbesc(ACTIVITY_POST),
1414 intval($user_info['cid']),
1415 dbesc($user_info['url']),
1416 dbesc(normalise_link($user_info['url'])),
1417 dbesc($user_info['url']),
1418 dbesc(normalise_link($user_info['url']))
1421 if (DBM::is_result($lastwall)) {
1422 $lastwall = $lastwall[0];
1424 $in_reply_to = api_in_reply_to($lastwall);
1426 $converted = api_convert_item($lastwall);
1428 if ($type == "xml") {
1429 $geo = "georss:point";
1434 $user_info['status'] = array(
1435 'text' => $converted["text"],
1436 'truncated' => false,
1437 'created_at' => api_date($lastwall['created']),
1438 'in_reply_to_status_id' => $in_reply_to['status_id'],
1439 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1440 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1441 'id' => intval($lastwall['contact-id']),
1442 'id_str' => (string) $lastwall['contact-id'],
1443 'in_reply_to_user_id' => $in_reply_to['user_id'],
1444 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1445 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1447 'favorited' => $lastwall['starred'] ? true : false,
1448 'statusnet_html' => $converted["html"],
1449 'statusnet_conversation_id' => $lastwall['parent'],
1450 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1453 if (count($converted["attachments"]) > 0) {
1454 $user_info["status"]["attachments"] = $converted["attachments"];
1457 if (count($converted["entities"]) > 0) {
1458 $user_info["status"]["entities"] = $converted["entities"];
1461 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1462 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1465 if (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1466 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
1470 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1471 unset($user_info["uid"]);
1472 unset($user_info["self"]);
1474 return api_format_data("user", $type, array('user' => $user_info));
1477 /// @TODO move to top of file or somewhere better
1478 api_register_func('api/users/show', 'api_users_show');
1479 api_register_func('api/externalprofile/show', 'api_users_show');
1481 function api_users_search($type)
1485 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1487 $userlist = array();
1489 if (x($_GET, 'q')) {
1490 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1492 if (!DBM::is_result($r)) {
1493 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1496 if (DBM::is_result($r)) {
1498 foreach ($r as $user) {
1499 $user_info = api_get_user($a, $user["id"], "json");
1501 if ($type == "xml") {
1502 $userlist[$k++.":user"] = $user_info;
1504 $userlist[] = $user_info;
1507 $userlist = array("users" => $userlist);
1509 throw new BadRequestException("User not found.");
1512 throw new BadRequestException("User not found.");
1514 return api_format_data("users", $type, $userlist);
1517 /// @TODO move to top of file or somewhere better
1518 api_register_func('api/users/search', 'api_users_search');
1521 * Return user objects
1523 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1525 * @param string $type Return format: json or xml
1527 * @return array|string
1528 * @throws NotFoundException if the results are empty.
1530 function api_users_lookup($type)
1534 if (x($_REQUEST['user_id'])) {
1535 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1537 $users[] = api_get_user(get_app(), $id);
1542 if (empty($users)) {
1543 throw new NotFoundException;
1546 return api_format_data("users", $type, array('users' => $users));
1549 /// @TODO move to top of file or somewhere better
1550 api_register_func('api/users/lookup', 'api_users_lookup', true);
1553 * Returns statuses that match a specified query.
1555 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1557 * @param string $type Return format: json, xml, atom, rss
1559 * @return array|string
1560 * @throws BadRequestException if the "q" parameter is missing.
1562 function api_search($type)
1566 if (!x($_REQUEST, 'q')) {
1567 throw new BadRequestException("q parameter is required.");
1570 if (x($_REQUEST, 'rpp')) {
1571 $count = $_REQUEST['rpp'];
1572 } elseif (x($_REQUEST, 'count')) {
1573 $count = $_REQUEST['count'];
1578 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1579 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1580 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1582 $start = $page * $count;
1585 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1589 "SELECT ".item_fieldlists()."
1590 FROM `item` ".item_joins()."
1591 WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1592 AND `item`.`body` LIKE CONCAT('%',?,'%')
1595 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
1601 $data['status'] = api_format_items(dba::inArray($r), api_get_user(get_app()));
1603 return api_format_data("statuses", $type, $data);
1606 /// @TODO move to top of file or somewhere better
1607 api_register_func('api/search/tweets', 'api_search', true);
1608 api_register_func('api/search', 'api_search', true);
1612 * http://developer.twitter.com/doc/get/statuses/home_timeline
1614 * TODO: Optional parameters
1615 * TODO: Add reply info
1617 function api_statuses_home_timeline($type)
1621 if (api_user() === false) {
1622 throw new ForbiddenException();
1625 unset($_REQUEST["user_id"]);
1626 unset($_GET["user_id"]);
1628 unset($_REQUEST["screen_name"]);
1629 unset($_GET["screen_name"]);
1631 $user_info = api_get_user($a);
1632 // get last newtork messages
1635 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1636 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1640 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1641 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1642 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1643 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1644 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1646 $start = $page * $count;
1650 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1652 if ($exclude_replies > 0) {
1653 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1655 if ($conversation_id > 0) {
1656 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1660 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1661 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1662 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1663 `contact`.`id` AS `cid`
1665 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1666 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1667 WHERE `item`.`uid` = %d AND `verb` = '%s'
1668 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1671 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1673 dbesc(ACTIVITY_POST),
1679 $ret = api_format_items($r, $user_info, false, $type);
1681 // Set all posts from the query above to seen
1683 foreach ($r as $item) {
1684 $idarray[] = intval($item["id"]);
1687 $idlist = implode(",", $idarray);
1689 if ($idlist != "") {
1690 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1693 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1697 $data = array('status' => $ret);
1701 $data = api_rss_extra($a, $data, $user_info);
1705 return api_format_data("statuses", $type, $data);
1708 /// @TODO move to top of file or somewhere better
1709 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1710 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1712 function api_statuses_public_timeline($type)
1716 if (api_user() === false) {
1717 throw new ForbiddenException();
1720 $user_info = api_get_user($a);
1721 // get last newtork messages
1724 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1725 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1729 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1730 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1731 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1732 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1733 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1735 $start = $page * $count;
1737 if ($exclude_replies && !$conversation_id) {
1739 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1742 $r = dba::p("SELECT " . item_fieldlists() . "
1744 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1745 " . item_joins() . "
1746 STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1747 AND NOT `user`.`hidewall`
1749 AND NOT `thread`.`private`
1751 AND `thread`.`visible`
1752 AND NOT `thread`.`deleted`
1753 AND NOT `thread`.`moderated`
1754 AND `thread`.`iid` > ?
1756 ORDER BY `thread`.`iid` DESC
1757 LIMIT " . intval($start) . ", " . intval($count),
1762 $r = dba::inArray($r);
1765 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1767 if ($conversation_id > 0) {
1768 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1771 $r = dba::p("SELECT " . item_fieldlists() . "
1773 " . item_joins() . "
1774 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1775 AND NOT `user`.`hidewall`
1777 AND NOT `item`.`private`
1779 AND `item`.`visible`
1780 AND NOT `item`.`deleted`
1781 AND NOT `item`.`moderated`
1784 ORDER BY `item`.`id` DESC
1785 LIMIT " . intval($start) . ", " . intval($count),
1790 $r = dba::inArray($r);
1793 $ret = api_format_items($r, $user_info, false, $type);
1795 $data = array('status' => $ret);
1799 $data = api_rss_extra($a, $data, $user_info);
1803 return api_format_data("statuses", $type, $data);
1806 /// @TODO move to top of file or somewhere better
1807 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1810 * @brief Returns the list of public federated posts this node knows about
1812 * @param string $type Return format: json, xml, atom, rss
1813 * @return array|string
1814 * @throws ForbiddenException
1816 function api_statuses_networkpublic_timeline($type)
1820 if (api_user() === false) {
1821 throw new ForbiddenException();
1824 $user_info = api_get_user($a);
1826 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1827 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1830 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1831 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1835 $start = ($page - 1) * $count;
1839 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1842 $r = dba::p("SELECT " . item_fieldlists() . "
1844 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1845 " . item_joins() . "
1846 WHERE `thread`.`uid` = 0
1848 AND NOT `thread`.`private`
1849 AND `thread`.`visible`
1850 AND NOT `thread`.`deleted`
1851 AND NOT `thread`.`moderated`
1852 AND `thread`.`iid` > ?
1854 ORDER BY `thread`.`iid` DESC
1855 LIMIT " . intval($start) . ", " . intval($count),
1860 $r = dba::inArray($r);
1862 $ret = api_format_items($r, $user_info, false, $type);
1864 $data = array('status' => $ret);
1868 $data = api_rss_extra($a, $data, $user_info);
1872 return api_format_data("statuses", $type, $data);
1875 /// @TODO move to top of file or somewhere better
1876 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1879 * @TODO nothing to say?
1881 function api_statuses_show($type)
1885 if (api_user() === false) {
1886 throw new ForbiddenException();
1889 $user_info = api_get_user($a);
1892 $id = intval($a->argv[3]);
1895 $id = intval($_REQUEST["id"]);
1900 $id = intval($a->argv[4]);
1903 logger('API: api_statuses_show: ' . $id);
1905 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1908 if ($conversation) {
1909 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1911 $sql_extra .= " AND `item`.`id` = %d";
1915 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1916 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1917 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1918 `contact`.`id` AS `cid`
1920 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1921 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1922 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1923 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1926 dbesc(ACTIVITY_POST),
1930 /// @TODO How about copying this to above methods which don't check $r ?
1931 if (!DBM::is_result($r)) {
1932 throw new BadRequestException("There is no status with this id.");
1935 $ret = api_format_items($r, $user_info, false, $type);
1937 if ($conversation) {
1938 $data = array('status' => $ret);
1939 return api_format_data("statuses", $type, $data);
1941 $data = array('status' => $ret[0]);
1942 return api_format_data("status", $type, $data);
1946 /// @TODO move to top of file or somewhere better
1947 api_register_func('api/statuses/show', 'api_statuses_show', true);
1950 * @TODO nothing to say?
1952 function api_conversation_show($type)
1956 if (api_user() === false) {
1957 throw new ForbiddenException();
1960 $user_info = api_get_user($a);
1963 $id = intval($a->argv[3]);
1964 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1965 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1969 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1970 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1972 $start = $page*$count;
1975 $id = intval($_REQUEST["id"]);
1980 $id = intval($a->argv[4]);
1983 logger('API: api_conversation_show: '.$id);
1985 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1986 if (DBM::is_result($r)) {
1987 $id = $r[0]["parent"];
1993 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1996 // Not sure why this query was so complicated. We should keep it here for a while,
1997 // just to make sure that we really don't need it.
1998 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1999 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
2002 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2003 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2004 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2005 `contact`.`id` AS `cid`
2007 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2008 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2009 WHERE `item`.`parent` = %d AND `item`.`visible`
2010 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2011 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2012 AND `item`.`id`>%d $sql_extra
2013 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2014 intval($id), intval(api_user()),
2015 dbesc(ACTIVITY_POST),
2017 intval($start), intval($count)
2020 if (!DBM::is_result($r)) {
2021 throw new BadRequestException("There is no status with this id.");
2024 $ret = api_format_items($r, $user_info, false, $type);
2026 $data = array('status' => $ret);
2027 return api_format_data("statuses", $type, $data);
2030 /// @TODO move to top of file or somewhere better
2031 api_register_func('api/conversation/show', 'api_conversation_show', true);
2032 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2035 * @TODO nothing to say?
2037 function api_statuses_repeat($type)
2043 if (api_user() === false) {
2044 throw new ForbiddenException();
2047 $user_info = api_get_user($a);
2050 $id = intval($a->argv[3]);
2053 $id = intval($_REQUEST["id"]);
2058 $id = intval($a->argv[4]);
2061 logger('API: api_statuses_repeat: '.$id);
2064 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2065 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2066 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2067 `contact`.`id` AS `cid`
2069 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2070 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2071 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2072 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2073 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2075 AND `item`.`id`=%d",
2079 /// @TODO other style than above functions!
2080 if (DBM::is_result($r) && $r[0]['body'] != "") {
2081 if (strpos($r[0]['body'], "[/share]") !== false) {
2082 $pos = strpos($r[0]['body'], "[share");
2083 $post = substr($r[0]['body'], $pos);
2085 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2087 $post .= $r[0]['body'];
2088 $post .= "[/share]";
2090 $_REQUEST['body'] = $post;
2091 $_REQUEST['profile_uid'] = api_user();
2092 $_REQUEST['type'] = 'wall';
2093 $_REQUEST['api_source'] = true;
2095 if (!x($_REQUEST, "source")) {
2096 $_REQUEST["source"] = api_source();
2101 throw new ForbiddenException();
2104 // this should output the last post (the one we just posted).
2106 return api_status_show($type);
2109 /// @TODO move to top of file or somewhere better
2110 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2113 * @TODO nothing to say?
2115 function api_statuses_destroy($type)
2119 if (api_user() === false) {
2120 throw new ForbiddenException();
2123 $user_info = api_get_user($a);
2126 $id = intval($a->argv[3]);
2129 $id = intval($_REQUEST["id"]);
2134 $id = intval($a->argv[4]);
2137 logger('API: api_statuses_destroy: '.$id);
2139 $ret = api_statuses_show($type);
2141 drop_item($id, false);
2146 /// @TODO move to top of file or somewhere better
2147 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2150 * @TODO Nothing more than an URL to say?
2151 * http://developer.twitter.com/doc/get/statuses/mentions
2153 function api_statuses_mentions($type)
2157 if (api_user() === false) {
2158 throw new ForbiddenException();
2161 unset($_REQUEST["user_id"]);
2162 unset($_GET["user_id"]);
2164 unset($_REQUEST["screen_name"]);
2165 unset($_GET["screen_name"]);
2167 $user_info = api_get_user($a);
2168 // get last newtork messages
2172 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2173 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2177 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2178 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2179 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2181 $start = $page * $count;
2183 // Ugly code - should be changed
2184 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2185 $myurl = substr($myurl, strpos($myurl, '://') + 3);
2186 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
2187 $myurl = str_replace('www.', '', $myurl);
2188 $diasp_url = str_replace('/profile/', '/u/', $myurl);
2191 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2195 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2196 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2197 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2198 `contact`.`id` AS `cid`
2199 FROM `item` FORCE INDEX (`uid_id`)
2200 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2201 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2202 WHERE `item`.`uid` = %d AND `verb` = '%s'
2203 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2204 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2205 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2208 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2210 dbesc(ACTIVITY_POST),
2211 dbesc(protect_sprintf($myurl)),
2212 dbesc(protect_sprintf($myurl)),
2219 $ret = api_format_items($r, $user_info, false, $type);
2221 $data = array('status' => $ret);
2225 $data = api_rss_extra($a, $data, $user_info);
2229 return api_format_data("statuses", $type, $data);
2232 /// @TODO move to top of file or somewhere better
2233 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2234 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2237 * @brief Returns a user's public timeline
2239 * @param string $type Either "json" or "xml"
2240 * @return string|array
2241 * @throws ForbiddenException
2243 function api_statuses_user_timeline($type)
2247 if (api_user() === false) {
2248 throw new ForbiddenException();
2251 $user_info = api_get_user($a);
2254 "api_statuses_user_timeline: api_user: ". api_user() .
2255 "\nuser_info: ".print_r($user_info, true) .
2256 "\n_REQUEST: ".print_r($_REQUEST, true),
2260 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2261 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2262 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2263 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2266 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2267 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2271 $start = ($page - 1) * $count;
2274 if ($user_info['self'] == 1) {
2275 $sql_extra .= " AND `item`.`wall` = 1 ";
2278 if ($exclude_replies > 0) {
2279 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2282 if ($conversation_id > 0) {
2283 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2287 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2291 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2292 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2293 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2294 `contact`.`id` AS `cid`
2295 FROM `item` FORCE INDEX (`uid_contactid_id`)
2296 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2297 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2298 WHERE `item`.`uid` = %d AND `verb` = '%s'
2299 AND `item`.`contact-id` = %d
2300 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2302 AND `item`.`id` > %d
2303 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2305 dbesc(ACTIVITY_POST),
2306 intval($user_info['cid']),
2312 $ret = api_format_items($r, $user_info, true, $type);
2314 $data = array('status' => $ret);
2318 $data = api_rss_extra($a, $data, $user_info);
2322 return api_format_data("statuses", $type, $data);
2325 /// @TODO move to top of file or somwhere better
2326 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2329 * Star/unstar an item
2330 * param: id : id of the item
2332 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2334 function api_favorites_create_destroy($type)
2338 if (api_user() === false) {
2339 throw new ForbiddenException();
2342 // for versioned api.
2343 /// @TODO We need a better global soluton
2344 $action_argv_id = 2;
2345 if ($a->argv[1] == "1.1") {
2346 $action_argv_id = 3;
2349 if ($a->argc <= $action_argv_id) {
2350 throw new BadRequestException("Invalid request.");
2352 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2353 if ($a->argc == $action_argv_id + 2) {
2354 $itemid = intval($a->argv[$action_argv_id + 1]);
2356 /// @TODO use x() to check if _REQUEST contains 'id'
2357 $itemid = intval($_REQUEST['id']);
2360 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2362 if (!DBM::is_result($item) || count($item) == 0) {
2363 throw new BadRequestException("Invalid item.");
2368 $item[0]['starred'] = 1;
2371 $item[0]['starred'] = 0;
2374 throw new BadRequestException("Invalid action ".$action);
2377 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2379 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2382 throw new InternalServerErrorException("DB error");
2386 $user_info = api_get_user($a);
2387 $rets = api_format_items($item, $user_info, false, $type);
2390 $data = array('status' => $ret);
2394 $data = api_rss_extra($a, $data, $user_info);
2397 return api_format_data("status", $type, $data);
2400 /// @TODO move to top of file or somwhere better
2401 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2402 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2404 function api_favorites($type)
2410 if (api_user() === false) {
2411 throw new ForbiddenException();
2414 $called_api = array();
2416 $user_info = api_get_user($a);
2418 // in friendica starred item are private
2419 // return favorites only for self
2420 logger('api_favorites: self:' . $user_info['self']);
2422 if ($user_info['self'] == 0) {
2428 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2429 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2430 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2431 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2436 $start = $page*$count;
2439 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2443 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2444 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2445 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2446 `contact`.`id` AS `cid`
2447 FROM `item`, `contact`
2448 WHERE `item`.`uid` = %d
2449 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2450 AND `item`.`starred` = 1
2451 AND `contact`.`id` = `item`.`contact-id`
2452 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2455 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2462 $ret = api_format_items($r, $user_info, false, $type);
2465 $data = array('status' => $ret);
2469 $data = api_rss_extra($a, $data, $user_info);
2472 return api_format_data("statuses", $type, $data);
2475 /// @TODO move to top of file or somwhere better
2476 api_register_func('api/favorites', 'api_favorites', true);
2478 function api_format_messages($item, $recipient, $sender)
2480 // standard meta information
2482 'id' => $item['id'],
2483 'sender_id' => $sender['id'] ,
2485 'recipient_id' => $recipient['id'],
2486 'created_at' => api_date($item['created']),
2487 'sender_screen_name' => $sender['screen_name'],
2488 'recipient_screen_name' => $recipient['screen_name'],
2489 'sender' => $sender,
2490 'recipient' => $recipient,
2492 'friendica_seen' => $item['seen'],
2493 'friendica_parent_uri' => $item['parent-uri'],
2496 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2497 unset($ret["sender"]["uid"]);
2498 unset($ret["sender"]["self"]);
2499 unset($ret["recipient"]["uid"]);
2500 unset($ret["recipient"]["self"]);
2502 //don't send title to regular StatusNET requests to avoid confusing these apps
2503 if (x($_GET, 'getText')) {
2504 $ret['title'] = $item['title'];
2505 if ($_GET['getText'] == 'html') {
2506 $ret['text'] = bbcode($item['body'], false, false);
2507 } elseif ($_GET['getText'] == 'plain') {
2508 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2509 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2512 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2514 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2515 unset($ret['sender']);
2516 unset($ret['recipient']);
2522 function api_convert_item($item)
2524 $body = $item['body'];
2525 $attachments = api_get_attachments($body);
2527 // Workaround for ostatus messages where the title is identically to the body
2528 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2529 $statusbody = trim(html2plain($html, 0));
2531 // handle data: images
2532 $statusbody = api_format_items_embeded_images($item, $statusbody);
2534 $statustitle = trim($item['title']);
2536 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2537 $statustext = trim($statusbody);
2539 $statustext = trim($statustitle."\n\n".$statusbody);
2542 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2543 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2546 $statushtml = trim(bbcode($body, false, false));
2548 // Workaround for clients with limited HTML parser functionality
2549 $search = array("<br>", "<blockquote>", "</blockquote>",
2550 "<h1>", "</h1>", "<h2>", "</h2>",
2551 "<h3>", "</h3>", "<h4>", "</h4>",
2552 "<h5>", "</h5>", "<h6>", "</h6>");
2553 $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2554 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2555 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2556 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2557 $statushtml = str_replace($search, $replace, $statushtml);
2559 if ($item['title'] != "") {
2560 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2564 $oldtext = $statushtml;
2565 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2566 } while ($oldtext != $statushtml);
2568 if (substr($statushtml, 0, 4) == '<br>') {
2569 $statushtml = substr($statushtml, 4);
2572 if (substr($statushtml, 0, -4) == '<br>') {
2573 $statushtml = substr($statushtml, -4);
2576 // feeds without body should contain the link
2577 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2578 $statushtml .= bbcode($item['plink']);
2581 $entities = api_get_entitities($statustext, $body);
2584 "text" => $statustext,
2585 "html" => $statushtml,
2586 "attachments" => $attachments,
2587 "entities" => $entities
2591 function api_get_attachments(&$body)
2594 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2596 $URLSearchString = "^\[\]";
2597 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2603 $attachments = array();
2605 foreach ($images[1] as $image) {
2606 $imagedata = Image::getInfoFromURL($image);
2609 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2613 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2614 foreach ($images[0] as $orig) {
2615 $body = str_replace($orig, "", $body);
2619 return $attachments;
2622 function api_get_entitities(&$text, $bbcode)
2626 * Links at the first character of the post
2631 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2633 if ($include_entities != "true") {
2634 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2636 foreach ($images[1] as $image) {
2637 $replace = proxy_url($image);
2638 $text = str_replace($image, $replace, $text);
2643 $bbcode = bb_CleanPictureLinks($bbcode);
2645 // Change pure links in text to bbcode uris
2646 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2648 $entities = array();
2649 $entities["hashtags"] = array();
2650 $entities["symbols"] = array();
2651 $entities["urls"] = array();
2652 $entities["user_mentions"] = array();
2654 $URLSearchString = "^\[\]";
2656 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2658 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2659 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2660 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2662 $bbcode = preg_replace(
2663 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2664 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2667 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2669 $bbcode = preg_replace(
2670 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2671 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2674 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2676 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2678 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2679 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2681 $ordered_urls = array();
2682 foreach ($urls[1] as $id => $url) {
2683 //$start = strpos($text, $url, $offset);
2684 $start = iconv_strpos($text, $url, 0, "UTF-8");
2685 if (!($start === false)) {
2686 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2690 ksort($ordered_urls);
2693 //foreach ($urls[1] AS $id=>$url) {
2694 foreach ($ordered_urls as $url) {
2695 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2696 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2698 $display_url = $url["title"];
2700 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2701 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2703 if (strlen($display_url) > 26) {
2704 $display_url = substr($display_url, 0, 25)."…";
2708 //$start = strpos($text, $url, $offset);
2709 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2710 if (!($start === false)) {
2711 $entities["urls"][] = array("url" => $url["url"],
2712 "expanded_url" => $url["url"],
2713 "display_url" => $display_url,
2714 "indices" => array($start, $start+strlen($url["url"])));
2715 $offset = $start + 1;
2719 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2720 $ordered_images = array();
2721 foreach ($images[1] as $image) {
2722 //$start = strpos($text, $url, $offset);
2723 $start = iconv_strpos($text, $image, 0, "UTF-8");
2724 if (!($start === false))
2725 $ordered_images[$start] = $image;
2727 //$entities["media"] = array();
2730 foreach ($ordered_images as $url) {
2731 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2732 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2734 if (strlen($display_url) > 26)
2735 $display_url = substr($display_url, 0, 25)."…";
2737 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2738 if (!($start === false)) {
2739 $image = Image::getInfoFromURL($url);
2741 // If image cache is activated, then use the following sizes:
2742 // thumb (150), small (340), medium (600) and large (1024)
2743 if (!Config::get("system", "proxy_disabled")) {
2744 $media_url = proxy_url($url);
2747 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2748 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2750 if (($image[0] > 150) || ($image[1] > 150)) {
2751 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2752 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2755 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2756 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2758 if (($image[0] > 600) || ($image[1] > 600)) {
2759 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2760 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2764 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2767 $entities["media"][] = array(
2769 "id_str" => (string)$start+1,
2770 "indices" => array($start, $start+strlen($url)),
2771 "media_url" => normalise_link($media_url),
2772 "media_url_https" => $media_url,
2774 "display_url" => $display_url,
2775 "expanded_url" => $url,
2779 $offset = $start + 1;
2785 function api_format_items_embeded_images(&$item, $text)
2787 $text = preg_replace_callback(
2788 "|data:image/([^;]+)[^=]+=*|m",
2789 function ($match) use ($item) {
2790 return System::baseUrl()."/display/".$item['guid'];
2799 * @brief return <a href='url'>name</a> as array
2801 * @param string $txt text
2806 function api_contactlink_to_array($txt)
2809 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2810 if ($r && count($match)==3) {
2812 'name' => $match[2],
2826 * @brief return likes, dislikes and attend status for item
2828 * @param array $item array
2830 * likes => int count
2831 * dislikes => int count
2833 function api_format_items_activities(&$item, $type = "json")
2837 $activities = array(
2839 'dislike' => array(),
2840 'attendyes' => array(),
2841 'attendno' => array(),
2842 'attendmaybe' => array(),
2847 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2848 intval($item['uid']),
2852 foreach ($items as $i) {
2853 // not used as result should be structured like other user data
2854 //builtin_activity_puller($i, $activities);
2856 // get user data and add it to the array of the activity
2857 $user = api_get_user($a, $i['author-link']);
2858 switch ($i['verb']) {
2860 $activities['like'][] = $user;
2862 case ACTIVITY_DISLIKE:
2863 $activities['dislike'][] = $user;
2865 case ACTIVITY_ATTEND:
2866 $activities['attendyes'][] = $user;
2868 case ACTIVITY_ATTENDNO:
2869 $activities['attendno'][] = $user;
2871 case ACTIVITY_ATTENDMAYBE:
2872 $activities['attendmaybe'][] = $user;
2879 if ($type == "xml") {
2880 $xml_activities = array();
2881 foreach ($activities as $k => $v) {
2882 // change xml element from "like" to "friendica:like"
2883 $xml_activities["friendica:".$k] = $v;
2884 // add user data into xml output
2886 foreach ($v as $user)
2887 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2889 $activities = $xml_activities;
2897 * @brief return data from profiles
2899 * @param array $profile array containing data from db table 'profile'
2900 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2903 function api_format_items_profiles(&$profile = null, $type = "json")
2905 if ($profile != null) {
2906 $profile = array('profile_id' => $profile['id'],
2907 'profile_name' => $profile['profile-name'],
2908 'is_default' => $profile['is-default'] ? true : false,
2909 'hide_friends'=> $profile['hide-friends'] ? true : false,
2910 'profile_photo' => $profile['photo'],
2911 'profile_thumb' => $profile['thumb'],
2912 'publish' => $profile['publish'] ? true : false,
2913 'net_publish' => $profile['net-publish'] ? true : false,
2914 'description' => $profile['pdesc'],
2915 'date_of_birth' => $profile['dob'],
2916 'address' => $profile['address'],
2917 'city' => $profile['locality'],
2918 'region' => $profile['region'],
2919 'postal_code' => $profile['postal-code'],
2920 'country' => $profile['country-name'],
2921 'hometown' => $profile['hometown'],
2922 'gender' => $profile['gender'],
2923 'marital' => $profile['marital'],
2924 'marital_with' => $profile['with'],
2925 'marital_since' => $profile['howlong'],
2926 'sexual' => $profile['sexual'],
2927 'politic' => $profile['politic'],
2928 'religion' => $profile['religion'],
2929 'public_keywords' => $profile['pub_keywords'],
2930 'private_keywords' => $profile['prv_keywords'],
2931 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2932 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2933 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2934 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2935 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2936 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2937 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2938 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2939 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2940 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2941 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2942 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2943 'homepage' => $profile['homepage'],
2950 * @brief format items to be returned by api
2952 * @param array $r array of items
2953 * @param array $user_info
2954 * @param bool $filter_user filter items by $user_info
2956 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2962 foreach ($r as $item) {
2963 localize_item($item);
2964 list($status_user, $owner_user) = api_item_get_user($a, $item);
2966 // Look if the posts are matching if they should be filtered by user id
2967 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2971 $in_reply_to = api_in_reply_to($item);
2973 $converted = api_convert_item($item);
2975 if ($type == "xml") {
2976 $geo = "georss:point";
2982 'text' => $converted["text"],
2983 'truncated' => false,
2984 'created_at'=> api_date($item['created']),
2985 'in_reply_to_status_id' => $in_reply_to['status_id'],
2986 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2987 'source' => (($item['app']) ? $item['app'] : 'web'),
2988 'id' => intval($item['id']),
2989 'id_str' => (string) intval($item['id']),
2990 'in_reply_to_user_id' => $in_reply_to['user_id'],
2991 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2992 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2994 'favorited' => $item['starred'] ? true : false,
2995 'user' => $status_user ,
2996 'friendica_owner' => $owner_user,
2997 //'entities' => NULL,
2998 'statusnet_html' => $converted["html"],
2999 'statusnet_conversation_id' => $item['parent'],
3000 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3001 'friendica_activities' => api_format_items_activities($item, $type),
3004 if (count($converted["attachments"]) > 0) {
3005 $status["attachments"] = $converted["attachments"];
3008 if (count($converted["entities"]) > 0) {
3009 $status["entities"] = $converted["entities"];
3012 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
3013 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
3014 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
3015 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
3019 // Retweets are only valid for top postings
3020 // It doesn't work reliable with the link if its a feed
3021 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
3023 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
3026 if ($item["id"] == $item["parent"]) {
3027 $retweeted_item = api_share_as_retweet($item);
3028 if ($retweeted_item !== false) {
3029 $retweeted_status = $status;
3031 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
3032 } catch (BadRequestException $e) {
3033 // user not found. should be found?
3034 /// @todo check if the user should be always found
3035 $retweeted_status["user"] = array();
3038 $rt_converted = api_convert_item($retweeted_item);
3040 $retweeted_status['text'] = $rt_converted["text"];
3041 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3042 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3043 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3044 $status['retweeted_status'] = $retweeted_status;
3048 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3049 unset($status["user"]["uid"]);
3050 unset($status["user"]["self"]);
3052 if ($item["coord"] != "") {
3053 $coords = explode(' ', $item["coord"]);
3054 if (count($coords) == 2) {
3055 if ($type == "json") {
3056 $status["geo"] = array('type' => 'Point',
3057 'coordinates' => array((float) $coords[0],
3058 (float) $coords[1]));
3059 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3060 $status["georss:point"] = $item["coord"];
3069 function api_account_rate_limit_status($type)
3071 if ($type == "xml") {
3073 'remaining-hits' => '150',
3074 '@attributes' => array("type" => "integer"),
3075 'hourly-limit' => '150',
3076 '@attributes2' => array("type" => "integer"),
3077 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
3078 '@attributes3' => array("type" => "datetime"),
3079 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3080 '@attributes4' => array("type" => "integer"),
3084 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3085 'remaining_hits' => '150',
3086 'hourly_limit' => '150',
3087 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
3091 return api_format_data('hash', $type, array('hash' => $hash));
3094 /// @TODO move to top of file or somwhere better
3095 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3097 function api_help_test($type)
3099 if ($type == 'xml') {
3105 return api_format_data('ok', $type, array("ok" => $ok));
3108 /// @TODO move to top of file or somwhere better
3109 api_register_func('api/help/test', 'api_help_test', false);
3111 function api_lists($type)
3114 /// @TODO $ret is not filled here?
3115 return api_format_data('lists', $type, array("lists_list" => $ret));
3118 /// @TODO move to top of file or somwhere better
3119 api_register_func('api/lists', 'api_lists', true);
3121 function api_lists_list($type)
3124 /// @TODO $ret is not filled here?
3125 return api_format_data('lists', $type, array("lists_list" => $ret));
3128 /// @TODO move to top of file or somwhere better
3129 api_register_func('api/lists/list', 'api_lists_list', true);
3132 * @brief Returns either the friends of the follower list
3134 * Note: Considers friends and followers lists to be private and won't return
3135 * anything if any user_id parameter is passed.
3137 * @param string $qtype Either "friends" or "followers"
3138 * @return boolean|array
3139 * @throws ForbiddenException
3141 function api_statuses_f($qtype)
3145 if (api_user() === false) {
3146 throw new ForbiddenException();
3150 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3151 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3155 $start = ($page - 1) * $count;
3157 $user_info = api_get_user($a);
3159 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3160 /* this is to stop Hotot to load friends multiple times
3161 * I'm not sure if I'm missing return something or
3162 * is a bug in hotot. Workaround, meantime
3166 return array('$users' => $ret);*/
3170 if ($qtype == 'friends') {
3171 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3173 if ($qtype == 'followers') {
3174 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3177 // friends and followers only for self
3178 if ($user_info['self'] == 0) {
3179 $sql_extra = " AND false ";
3182 if ($qtype == 'blocks') {
3183 $sql_filter = 'AND `blocked` AND NOT `pending`';
3184 } elseif ($qtype == 'incoming') {
3185 $sql_filter = 'AND `pending`';
3187 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3205 foreach ($r as $cid) {
3206 $user = api_get_user($a, $cid['nurl']);
3207 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3208 unset($user["uid"]);
3209 unset($user["self"]);
3216 return array('user' => $ret);
3221 * @brief Returns the list of friends of the provided user
3223 * @deprecated By Twitter API in favor of friends/list
3225 * @param string $type Either "json" or "xml"
3226 * @return boolean|string|array
3228 function api_statuses_friends($type)
3230 $data = api_statuses_f("friends");
3231 if ($data === false) {
3234 return api_format_data("users", $type, $data);
3238 * @brief Returns the list of friends of the provided user
3240 * @deprecated By Twitter API in favor of friends/list
3242 * @param string $type Either "json" or "xml"
3243 * @return boolean|string|array
3245 function api_statuses_followers($type)
3247 $data = api_statuses_f("followers");
3248 if ($data === false) {
3251 return api_format_data("users", $type, $data);
3254 /// @TODO move to top of file or somewhere better
3255 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3256 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3259 * Returns the list of blocked users
3261 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3263 * @param string $type Either "json" or "xml"
3265 * @return boolean|string|array
3267 function api_blocks_list($type)
3269 $data = api_statuses_f('blocks');
3270 if ($data === false) {
3273 return api_format_data("users", $type, $data);
3276 /// @TODO move to top of file or somewhere better
3277 api_register_func('api/blocks/list', 'api_blocks_list', true);
3280 * Returns the list of pending users IDs
3282 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3284 * @param string $type Either "json" or "xml"
3286 * @return boolean|string|array
3288 function api_friendships_incoming($type)
3290 $data = api_statuses_f('incoming');
3291 if ($data === false) {
3296 foreach ($data['user'] as $user) {
3297 $ids[] = $user['id'];
3300 return api_format_data("ids", $type, array('id' => $ids));
3303 /// @TODO move to top of file or somewhere better
3304 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3306 function api_statusnet_config($type)
3310 $name = $a->config['sitename'];
3311 $server = $a->get_hostname();
3312 $logo = System::baseUrl() . '/images/friendica-64.png';
3313 $email = $a->config['admin_email'];
3314 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3315 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3316 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3317 if ($a->config['api_import_size']) {
3318 $texlimit = string($a->config['api_import_size']);
3320 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3321 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3324 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3325 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3326 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3327 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3328 'shorturllength' => '30',
3329 'friendica' => array(
3330 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3331 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3332 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3333 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3338 return api_format_data('config', $type, array('config' => $config));
3341 /// @TODO move to top of file or somewhere better
3342 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3343 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3345 function api_statusnet_version($type)
3348 $fake_statusnet_version = "0.9.7";
3350 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
3353 /// @TODO move to top of file or somewhere better
3354 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3355 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3358 * @todo use api_format_data() to return data
3360 function api_ff_ids($type,$qtype)
3365 throw new ForbiddenException();
3368 $user_info = api_get_user($a);
3370 if ($qtype == 'friends') {
3371 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3373 if ($qtype == 'followers') {
3374 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3377 if (!$user_info["self"]) {
3378 $sql_extra = " AND false ";
3381 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3384 "SELECT `pcontact`.`id` FROM `contact`
3385 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3386 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3390 if (!DBM::is_result($r)) {
3395 foreach ($r as $rr) {
3396 if ($stringify_ids) {
3399 $ids[] = intval($rr['id']);
3403 return api_format_data("ids", $type, array('id' => $ids));
3406 function api_friends_ids($type)
3408 return api_ff_ids($type, 'friends');
3411 function api_followers_ids($type)
3413 return api_ff_ids($type, 'followers');
3416 /// @TODO move to top of file or somewhere better
3417 api_register_func('api/friends/ids', 'api_friends_ids', true);
3418 api_register_func('api/followers/ids', 'api_followers_ids', true);
3420 function api_direct_messages_new($type)
3425 if (api_user() === false) throw new ForbiddenException();
3427 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) return;
3429 $sender = api_get_user($a);
3431 if ($_POST['screen_name']) {
3433 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3435 dbesc($_POST['screen_name'])
3438 // Selecting the id by priority, friendica first
3439 api_best_nickname($r);
3441 $recipient = api_get_user($a, $r[0]['nurl']);
3443 $recipient = api_get_user($a, $_POST['user_id']);
3448 if (x($_REQUEST, 'replyto')) {
3450 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3452 intval($_REQUEST['replyto'])
3454 $replyto = $r[0]['parent-uri'];
3455 $sub = $r[0]['title'];
3457 if (x($_REQUEST, 'title')) {
3458 $sub = $_REQUEST['title'];
3460 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3464 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3467 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3468 $ret = api_format_messages($r[0], $recipient, $sender);
3470 $ret = array("error"=>$id);
3473 $data = array('direct_message'=>$ret);
3478 $data = api_rss_extra($a, $data, $user_info);
3481 return api_format_data("direct-messages", $type, $data);
3485 /// @TODO move to top of file or somewhere better
3486 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3489 * @brief delete a direct_message from mail table through api
3491 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3494 function api_direct_messages_destroy($type)
3498 if (api_user() === false) {
3499 throw new ForbiddenException();
3503 $user_info = api_get_user($a);
3505 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3507 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3508 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3509 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3511 $uid = $user_info['uid'];
3512 // error if no id or parenturi specified (for clients posting parent-uri as well)
3513 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3514 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3515 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3518 // BadRequestException if no id specified (for clients using Twitter API)
3520 throw new BadRequestException('Message id not specified');
3523 // add parent-uri to sql command if specified by calling app
3524 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3526 // get data of the specified message id
3528 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3533 // error message if specified id is not in database
3534 if (!DBM::is_result($r)) {
3535 if ($verbose == "true") {
3536 $answer = array('result' => 'error', 'message' => 'message id not in database');
3537 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3539 /// @todo BadRequestException ok for Twitter API clients?
3540 throw new BadRequestException('message id not in database');
3545 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3550 if ($verbose == "true") {
3553 $answer = array('result' => 'ok', 'message' => 'message deleted');
3554 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3556 $answer = array('result' => 'error', 'message' => 'unknown error');
3557 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3560 /// @todo return JSON data like Twitter API not yet implemented
3564 /// @TODO move to top of file or somewhere better
3565 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3567 function api_direct_messages_box($type, $box, $verbose)
3571 if (api_user() === false) {
3572 throw new ForbiddenException();
3576 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3577 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3582 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3583 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3585 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3586 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3589 unset($_REQUEST["user_id"]);
3590 unset($_GET["user_id"]);
3592 unset($_REQUEST["screen_name"]);
3593 unset($_GET["screen_name"]);
3595 $user_info = api_get_user($a);
3596 $profile_url = $user_info["url"];
3599 $start = $page * $count;
3602 if ($box=="sentbox") {
3603 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3604 } elseif ($box == "conversation") {
3605 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3606 } elseif ($box == "all") {
3607 $sql_extra = "true";
3608 } elseif ($box == "inbox") {
3609 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3613 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3616 if ($user_id != "") {
3617 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3618 } elseif ($screen_name !="") {
3619 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3623 "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",
3629 if ($verbose == "true" && !DBM::is_result($r)) {
3630 $answer = array('result' => 'error', 'message' => 'no mails available');
3631 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3635 foreach ($r as $item) {
3636 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3637 $recipient = $user_info;
3638 $sender = api_get_user($a, normalise_link($item['contact-url']));
3639 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3640 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3641 $sender = $user_info;
3644 $ret[] = api_format_messages($item, $recipient, $sender);
3648 $data = array('direct_message' => $ret);
3652 $data = api_rss_extra($a, $data, $user_info);
3655 return api_format_data("direct-messages", $type, $data);
3658 function api_direct_messages_sentbox($type)
3660 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3661 return api_direct_messages_box($type, "sentbox", $verbose);
3664 function api_direct_messages_inbox($type)
3666 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3667 return api_direct_messages_box($type, "inbox", $verbose);
3670 function api_direct_messages_all($type)
3672 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3673 return api_direct_messages_box($type, "all", $verbose);
3676 function api_direct_messages_conversation($type)
3678 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3679 return api_direct_messages_box($type, "conversation", $verbose);
3682 /// @TODO move to top of file or somewhere better
3683 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3684 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3685 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3686 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3688 function api_oauth_request_token($type)
3690 $oauth1 = new FKOAuth1();
3692 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3693 } catch (Exception $e) {
3694 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3701 function api_oauth_access_token($type)
3703 $oauth1 = new FKOAuth1();
3705 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3706 } catch (Exception $e) {
3707 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3714 /// @TODO move to top of file or somewhere better
3715 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3716 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3720 * @brief delete a complete photoalbum with all containing photos from database through api
3722 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3725 function api_fr_photoalbum_delete($type)
3727 if (api_user() === false) {
3728 throw new ForbiddenException();
3731 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3733 // we do not allow calls without album string
3735 throw new BadRequestException("no albumname specified");
3737 // check if album is existing
3739 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3743 if (!DBM::is_result($r))
3744 throw new BadRequestException("album not available");
3746 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3747 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3748 foreach ($r as $rr) {
3750 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3751 intval(local_user()),
3752 dbesc($rr['resource-id'])
3755 if (!DBM::is_result($photo_item)) {
3756 throw new InternalServerErrorException("problem with deleting items occured");
3758 drop_item($photo_item[0]['id'], false);
3761 // now let's delete all photos from the album
3762 $result = dba::delete('photo', array('uid' => api_user(), 'album' => $album));
3764 // return success of deletion or error message
3766 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3767 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3769 throw new InternalServerErrorException("unknown error - deleting from database failed");
3774 * @brief update the name of the album for all photos of an album
3776 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3779 function api_fr_photoalbum_update($type)
3781 if (api_user() === false) {
3782 throw new ForbiddenException();
3785 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3786 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3788 // we do not allow calls without album string
3790 throw new BadRequestException("no albumname specified");
3792 if ($album_new == "") {
3793 throw new BadRequestException("no new albumname specified");
3795 // check if album is existing
3797 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3801 if (!DBM::is_result($r)) {
3802 throw new BadRequestException("album not available");
3804 // now let's update all photos to the albumname
3806 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3812 // return success of updating or error message
3814 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3815 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3817 throw new InternalServerErrorException("unknown error - updating in database failed");
3823 * @brief list all photos of the authenticated user
3825 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3828 function api_fr_photos_list($type)
3830 if (api_user() === false) {
3831 throw new ForbiddenException();
3834 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3835 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3836 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3837 intval(local_user())
3840 'image/jpeg' => 'jpg',
3841 'image/png' => 'png',
3842 'image/gif' => 'gif'
3844 $data = array('photo'=>array());
3845 if (DBM::is_result($r)) {
3846 foreach ($r as $rr) {
3848 $photo['id'] = $rr['resource-id'];
3849 $photo['album'] = $rr['album'];
3850 $photo['filename'] = $rr['filename'];
3851 $photo['type'] = $rr['type'];
3852 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3853 $photo['created'] = $rr['created'];
3854 $photo['edited'] = $rr['edited'];
3855 $photo['desc'] = $rr['desc'];
3857 if ($type == "xml") {
3858 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3860 $photo['thumb'] = $thumb;
3861 $data['photo'][] = $photo;
3865 return api_format_data("photos", $type, $data);
3869 * @brief upload a new photo or change an existing photo
3871 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3874 function api_fr_photo_create_update($type)
3876 if (api_user() === false) {
3877 throw new ForbiddenException();
3880 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3881 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3882 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3883 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3884 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3885 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3886 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3887 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3888 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3890 // do several checks on input parameters
3891 // we do not allow calls without album string
3892 if ($album == null) {
3893 throw new BadRequestException("no albumname specified");
3895 // if photo_id == null --> we are uploading a new photo
3896 if ($photo_id == null) {
3899 // error if no media posted in create-mode
3900 if (!x($_FILES, 'media')) {
3902 throw new BadRequestException("no media data submitted");
3905 // album_new will be ignored in create-mode
3910 // check if photo is existing in database
3912 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3917 if (!DBM::is_result($r)) {
3918 throw new BadRequestException("photo not available");
3922 // checks on acl strings provided by clients
3923 $acl_input_error = false;
3924 $acl_input_error |= check_acl_input($allow_cid);
3925 $acl_input_error |= check_acl_input($deny_cid);
3926 $acl_input_error |= check_acl_input($allow_gid);
3927 $acl_input_error |= check_acl_input($deny_gid);
3928 if ($acl_input_error) {
3929 throw new BadRequestException("acl data invalid");
3931 // now let's upload the new media in create-mode
3932 if ($mode == "create") {
3933 $media = $_FILES['media'];
3934 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3936 // return success of updating or error message
3937 if (!is_null($data)) {
3938 return api_format_data("photo_create", $type, $data);
3940 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3944 // now let's do the changes in update-mode
3945 if ($mode == "update") {
3948 if (!is_null($desc)) {
3949 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3952 if (!is_null($album_new)) {
3953 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3956 if (!is_null($allow_cid)) {
3957 $allow_cid = trim($allow_cid);
3958 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3961 if (!is_null($deny_cid)) {
3962 $deny_cid = trim($deny_cid);
3963 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3966 if (!is_null($allow_gid)) {
3967 $allow_gid = trim($allow_gid);
3968 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3971 if (!is_null($deny_gid)) {
3972 $deny_gid = trim($deny_gid);
3973 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3977 if ($sql_extra != "") {
3978 $nothingtodo = false;
3980 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3982 datetime_convert(), // update edited timestamp
3988 $nothingtodo = true;
3991 if (x($_FILES, 'media')) {
3992 $nothingtodo = false;
3993 $media = $_FILES['media'];
3994 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3995 if (!is_null($data)) {
3996 return api_format_data("photo_update", $type, $data);
4000 // return success of updating or error message
4002 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
4003 return api_format_data("photo_update", $type, array('$result' => $answer));
4006 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
4007 return api_format_data("photo_update", $type, array('$result' => $answer));
4009 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4012 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4017 * @brief delete a single photo from the database through api
4019 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4022 function api_fr_photo_delete($type)
4024 if (api_user() === false) {
4025 throw new ForbiddenException();
4028 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4030 // do several checks on input parameters
4031 // we do not allow calls without photo id
4032 if ($photo_id == null) {
4033 throw new BadRequestException("no photo_id specified");
4035 // check if photo is existing in database
4037 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4041 if (!DBM::is_result($r)) {
4042 throw new BadRequestException("photo not available");
4044 // now we can perform on the deletion of the photo
4045 $result = dba::delete('photo', array('uid' => api_user(), 'resource-id' => $photo_id));
4047 // return success of deletion or error message
4049 // retrieve the id of the parent element (the photo element)
4051 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4052 intval(local_user()),
4056 if (!DBM::is_result($photo_item)) {
4057 throw new InternalServerErrorException("problem with deleting items occured");
4059 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4060 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4061 drop_item($photo_item[0]['id'], false);
4063 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
4064 return api_format_data("photo_delete", $type, array('$result' => $answer));
4066 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4072 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4074 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4077 function api_fr_photo_detail($type)
4079 if (api_user() === false) {
4080 throw new ForbiddenException();
4082 if (!x($_REQUEST, 'photo_id')) {
4083 throw new BadRequestException("No photo id.");
4086 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4087 $photo_id = $_REQUEST['photo_id'];
4089 // prepare json/xml output with data from database for the requested photo
4090 $data = prepare_photo_data($type, $scale, $photo_id);
4092 return api_format_data("photo_detail", $type, $data);
4097 * @brief updates the profile image for the user (either a specified profile or the default profile)
4099 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4102 function api_account_update_profile_image($type)
4104 if (api_user() === false) {
4105 throw new ForbiddenException();
4108 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
4110 // error if image data is missing
4111 if (!x($_FILES, 'image')) {
4112 throw new BadRequestException("no media data submitted");
4115 // check if specified profile id is valid
4116 if ($profileid != 0) {
4118 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4122 // error message if specified profile id is not in database
4123 if (!DBM::is_result($r)) {
4124 throw new BadRequestException("profile_id not available");
4126 $is_default_profile = $r['profile'];
4128 $is_default_profile = 1;
4131 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4133 if (x($_FILES, 'image')) {
4134 $media = $_FILES['image'];
4135 } elseif (x($_FILES, 'media')) {
4136 $media = $_FILES['media'];
4138 // save new profile image
4139 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4142 if (is_array($media['type'])) {
4143 $filetype = $media['type'][0];
4145 $filetype = $media['type'];
4147 if ($filetype == "image/jpeg") {
4149 } elseif ($filetype == "image/png") {
4152 // change specified profile or all profiles to the new resource-id
4153 if ($is_default_profile) {
4155 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4156 dbesc($data['photo']['id']),
4157 intval(local_user())
4161 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
4162 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4163 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4164 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4165 intval(local_user())
4169 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4170 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4171 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4172 intval($_REQUEST['profile']),
4173 intval(local_user())
4177 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4178 // so that browsers will do a cache update unconditionally
4181 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4182 dbesc(datetime_convert()),
4183 intval(local_user())
4186 // Update global directory in background
4187 //$user = api_get_user(get_app());
4188 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4189 if ($url && strlen(Config::get('system', 'directory'))) {
4190 Worker::add(PRIORITY_LOW, "Directory", $url);
4193 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4195 // output for client
4197 return api_account_verify_credentials($type);
4199 // SaveMediaToDatabase failed for some reason
4200 throw new InternalServerErrorException("image upload failed");
4204 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4205 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4206 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4207 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4208 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4209 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4210 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4211 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4212 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4215 function check_acl_input($acl_string)
4217 if ($acl_string == null || $acl_string == " ") {
4220 $contact_not_found = false;
4222 // split <x><y><z> into array of cid's
4223 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4225 // check for each cid if it is available on server
4226 $cid_array = $array[0];
4227 foreach ($cid_array as $cid) {
4228 $cid = str_replace("<", "", $cid);
4229 $cid = str_replace(">", "", $cid);
4231 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4235 $contact_not_found |= !DBM::is_result($contact);
4237 return $contact_not_found;
4240 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)
4248 if (is_array($media)) {
4249 if (is_array($media['tmp_name'])) {
4250 $src = $media['tmp_name'][0];
4252 $src = $media['tmp_name'];
4254 if (is_array($media['name'])) {
4255 $filename = basename($media['name'][0]);
4257 $filename = basename($media['name']);
4259 if (is_array($media['size'])) {
4260 $filesize = intval($media['size'][0]);
4262 $filesize = intval($media['size']);
4264 if (is_array($media['type'])) {
4265 $filetype = $media['type'][0];
4267 $filetype = $media['type'];
4271 if ($filetype == "") {
4272 $filetype=Image::guessType($filename);
4274 $imagedata = getimagesize($src);
4276 $filetype = $imagedata['mime'];
4279 "File upload src: " . $src . " - filename: " . $filename .
4280 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG
4283 // check if there was a php upload error
4284 if ($filesize == 0 && $media['error'] == 1) {
4285 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4287 // check against max upload size within Friendica instance
4288 $maximagesize = Config::get('system', 'maximagesize');
4289 if ($maximagesize && ($filesize > $maximagesize)) {
4290 $formattedBytes = formatBytes($maximagesize);
4291 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4294 // create Photo instance with the data of the image
4295 $imagedata = @file_get_contents($src);
4296 $Image = new Image($imagedata, $filetype);
4297 if (! $Image->isValid()) {
4298 throw new InternalServerErrorException("unable to process image data");
4301 // check orientation of image
4302 $Image->orient($src);
4305 // check max length of images on server
4306 $max_length = Config::get('system', 'max_image_length');
4307 if (! $max_length) {
4308 $max_length = MAX_IMAGE_LENGTH;
4310 if ($max_length > 0) {
4311 $Image->scaleDown($max_length);
4312 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4314 $width = $Image->getWidth();
4315 $height = $Image->getHeight();
4317 // create a new resource-id if not already provided
4318 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
4320 if ($mediatype == "photo") {
4321 // upload normal image (scales 0, 1, 2)
4322 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4324 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4326 logger("photo upload: image upload with scale 0 (original size) failed");
4328 if ($width > 640 || $height > 640) {
4329 $Image->scaleDown(640);
4330 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4332 logger("photo upload: image upload with scale 1 (640x640) failed");
4336 if ($width > 320 || $height > 320) {
4337 $Image->scaleDown(320);
4338 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4340 logger("photo upload: image upload with scale 2 (320x320) failed");
4343 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4344 } elseif ($mediatype == "profileimage") {
4345 // upload profile image (scales 4, 5, 6)
4346 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4348 if ($width > 175 || $height > 175) {
4349 $Image->scaleDown(175);
4350 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4352 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4356 if ($width > 80 || $height > 80) {
4357 $Image->scaleDown(80);
4358 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4360 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4364 if ($width > 48 || $height > 48) {
4365 $Image->scaleDown(48);
4366 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4368 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4371 $Image->__destruct();
4372 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4376 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4377 if ($photo_id == null && $mediatype == "photo") {
4378 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4380 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4381 return prepare_photo_data($type, false, $hash);
4383 throw new InternalServerErrorException("image upload failed");
4387 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4389 // get data about the api authenticated user
4390 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4391 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4394 $arr['guid'] = get_guid(32);
4395 $arr['uid'] = intval(api_user());
4397 $arr['parent-uri'] = $uri;
4398 $arr['type'] = 'photo';
4400 $arr['resource-id'] = $hash;
4401 $arr['contact-id'] = $owner_record[0]['id'];
4402 $arr['owner-name'] = $owner_record[0]['name'];
4403 $arr['owner-link'] = $owner_record[0]['url'];
4404 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4405 $arr['author-name'] = $owner_record[0]['name'];
4406 $arr['author-link'] = $owner_record[0]['url'];
4407 $arr['author-avatar'] = $owner_record[0]['thumb'];
4409 $arr['allow_cid'] = $allow_cid;
4410 $arr['allow_gid'] = $allow_gid;
4411 $arr['deny_cid'] = $deny_cid;
4412 $arr['deny_gid'] = $deny_gid;
4413 $arr['last-child'] = 1;
4414 $arr['visible'] = $visibility;
4418 'image/jpeg' => 'jpg',
4419 'image/png' => 'png',
4420 'image/gif' => 'gif'
4423 // adds link to the thumbnail scale photo
4424 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4425 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4428 // do the magic for storing the item in the database and trigger the federation to other contacts
4432 function prepare_photo_data($type, $scale, $photo_id)
4434 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4435 $data_sql = ($scale === false ? "" : "data, ");
4437 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4438 // clients needs to convert this in their way for further processing
4440 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4441 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4442 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4443 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4445 intval(local_user()),
4451 'image/jpeg' => 'jpg',
4452 'image/png' => 'png',
4453 'image/gif' => 'gif'
4456 // prepare output data for photo
4457 if (DBM::is_result($r)) {
4458 $data = array('photo' => $r[0]);
4459 $data['photo']['id'] = $data['photo']['resource-id'];
4460 if ($scale !== false) {
4461 $data['photo']['data'] = base64_encode($data['photo']['data']);
4463 unset($data['photo']['datasize']); //needed only with scale param
4465 if ($type == "xml") {
4466 $data['photo']['links'] = array();
4467 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4468 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4470 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4473 $data['photo']['link'] = array();
4474 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4476 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4477 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4481 unset($data['photo']['resource-id']);
4482 unset($data['photo']['minscale']);
4483 unset($data['photo']['maxscale']);
4485 throw new NotFoundException();
4488 // retrieve item element for getting activities (like, dislike etc.) related to photo
4490 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4491 intval(local_user()),
4494 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4496 // retrieve comments on photo
4498 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4499 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4500 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4501 `contact`.`id` AS `cid`
4503 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4504 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4505 WHERE `item`.`parent` = %d AND `item`.`visible`
4506 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4507 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4508 intval($item[0]['parent']),
4510 dbesc(ACTIVITY_POST)
4513 // prepare output of comments
4514 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4515 $comments = array();
4516 if ($type == "xml") {
4518 foreach ($commentData as $comment) {
4519 $comments[$k++ . ":comment"] = $comment;
4522 foreach ($commentData as $comment) {
4523 $comments[] = $comment;
4526 $data['photo']['friendica_comments'] = $comments;
4528 // include info if rights on photo and rights on item are mismatching
4529 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4530 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4531 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4532 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4533 $data['photo']['rights_mismatch'] = $rights_mismatch;
4540 * Similar as /mod/redir.php
4541 * redirect to 'url' after dfrn auth
4543 * Why this when there is mod/redir.php already?
4544 * This use api_user() and api_login()
4547 * c_url: url of remote contact to auth to
4548 * url: string, url to redirect after auth
4550 function api_friendica_remoteauth()
4552 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4553 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4555 if ($url === '' || $c_url === '') {
4556 throw new BadRequestException("Wrong parameters.");
4559 $c_url = normalise_link($c_url);
4563 $r = dba::select('contact', [], ['uid' => api_user(), 'nurl' => $c_url], ['limit' => 1]);
4565 if (!DBM::is_result($r) || ($r['network'] !== NETWORK_DFRN)) {
4566 throw new BadRequestException("Unknown contact");
4571 $dfrn_id = $orig_id = (($r['issued-id']) ? $r['issued-id'] : $r['dfrn-id']);
4573 if ($r['duplex'] && $r['issued-id']) {
4574 $orig_id = $r['issued-id'];
4575 $dfrn_id = '1:' . $orig_id;
4577 if ($r['duplex'] && $r['dfrn-id']) {
4578 $orig_id = $r['dfrn-id'];
4579 $dfrn_id = '0:' . $orig_id;
4582 $sec = random_string();
4585 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4586 VALUES( %d, %s, '%s', '%s', %d )",
4594 logger($r['name'] . ' ' . $sec, LOGGER_DEBUG);
4595 $dest = ($url ? '&destination_url=' . $url : '');
4597 $r['poll'] . '?dfrn_id=' . $dfrn_id
4598 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4599 . '&type=profile&sec=' . $sec . $dest . $quiet
4602 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4605 * @brief Return the item shared, if the item contains only the [share] tag
4607 * @param array $item Sharer item
4608 * @return array Shared item or false if not a reshare
4610 function api_share_as_retweet(&$item)
4612 $body = trim($item["body"]);
4614 if (Diaspora::isReshare($body, false)===false) {
4618 /// @TODO "$1" should maybe mean '$1' ?
4619 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4621 * Skip if there is no shared message in there
4622 * we already checked this in diaspora::isReshare()
4623 * but better one more than one less...
4625 if ($body == $attributes) {
4630 // build the fake reshared item
4631 $reshared_item = $item;
4634 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4635 if ($matches[1] != "") {
4636 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4639 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4640 if ($matches[1] != "") {
4641 $author = $matches[1];
4645 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4646 if ($matches[1] != "") {
4647 $profile = $matches[1];
4650 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4651 if ($matches[1] != "") {
4652 $profile = $matches[1];
4656 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4657 if ($matches[1] != "") {
4658 $avatar = $matches[1];
4661 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4662 if ($matches[1] != "") {
4663 $avatar = $matches[1];
4667 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4668 if ($matches[1] != "") {
4669 $link = $matches[1];
4672 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4673 if ($matches[1] != "") {
4674 $link = $matches[1];
4678 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4679 if ($matches[1] != "")
4680 $posted = $matches[1];
4682 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4683 if ($matches[1] != "") {
4684 $posted = $matches[1];
4687 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4689 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4693 $reshared_item["body"] = $shared_body;
4694 $reshared_item["author-name"] = $author;
4695 $reshared_item["author-link"] = $profile;
4696 $reshared_item["author-avatar"] = $avatar;
4697 $reshared_item["plink"] = $link;
4698 $reshared_item["created"] = $posted;
4699 $reshared_item["edited"] = $posted;
4701 return $reshared_item;
4705 function api_get_nick($profile)
4708 - remove trailing junk from profile url
4709 - pump.io check has to check the website
4715 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4716 dbesc(normalise_link($profile))
4719 if (DBM::is_result($r)) {
4720 $nick = $r[0]["nick"];
4725 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4726 dbesc(normalise_link($profile))
4729 if (DBM::is_result($r)) {
4730 $nick = $r[0]["nick"];
4735 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4736 if ($friendica != $profile) {
4742 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4743 if ($diaspora != $profile) {
4749 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4750 if ($twitter != $profile) {
4757 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4758 if ($StatusnetHost != $profile) {
4759 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4760 if ($StatusnetUser != $profile) {
4761 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4762 $user = json_decode($UserData);
4764 $nick = $user->screen_name;
4770 // To-Do: look at the page if its really a pumpio site
4771 //if (!$nick == "") {
4772 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4773 // if ($pumpio != $profile)
4775 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4786 function api_in_reply_to($item)
4788 $in_reply_to = array();
4790 $in_reply_to['status_id'] = null;
4791 $in_reply_to['user_id'] = null;
4792 $in_reply_to['status_id_str'] = null;
4793 $in_reply_to['user_id_str'] = null;
4794 $in_reply_to['screen_name'] = null;
4796 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4797 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4798 intval($item['uid']),
4799 dbesc($item['thr-parent']));
4801 if (DBM::is_result($r)) {
4802 $in_reply_to['status_id'] = intval($r[0]['id']);
4804 $in_reply_to['status_id'] = intval($item['parent']);
4807 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4809 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4810 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4811 WHERE `item`.`id` = %d LIMIT 1",
4812 intval($in_reply_to['status_id'])
4815 if (DBM::is_result($r)) {
4816 if ($r[0]['nick'] == "") {
4817 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4820 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4821 $in_reply_to['user_id'] = intval($r[0]['id']);
4822 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4825 // There seems to be situation, where both fields are identical:
4826 // https://github.com/friendica/friendica/issues/1010
4827 // This is a bugfix for that.
4828 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4829 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4830 $in_reply_to['status_id'] = null;
4831 $in_reply_to['user_id'] = null;
4832 $in_reply_to['status_id_str'] = null;
4833 $in_reply_to['user_id_str'] = null;
4834 $in_reply_to['screen_name'] = null;
4838 return $in_reply_to;
4841 function api_clean_plain_items($Text)
4843 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4845 $Text = bb_CleanPictureLinks($Text);
4846 $URLSearchString = "^\[\]";
4848 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
4850 if ($include_entities == "true") {
4851 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
4854 // Simplify "attachment" element
4855 $Text = api_clean_attachments($Text);
4861 * @brief Removes most sharing information for API text export
4863 * @param string $body The original body
4865 * @return string Cleaned body
4867 function api_clean_attachments($body)
4869 $data = get_attachment_data($body);
4876 if (isset($data["text"])) {
4877 $body = $data["text"];
4879 if (($body == "") && isset($data["title"])) {
4880 $body = $data["title"];
4882 if (isset($data["url"])) {
4883 $body .= "\n".$data["url"];
4885 $body .= $data["after"];
4890 function api_best_nickname(&$contacts)
4892 $best_contact = array();
4894 if (count($contact) == 0)
4897 foreach ($contacts as $contact)
4898 if ($contact["network"] == "") {
4899 $contact["network"] = "dfrn";
4900 $best_contact = array($contact);
4903 if (sizeof($best_contact) == 0)
4904 foreach ($contacts as $contact)
4905 if ($contact["network"] == "dfrn")
4906 $best_contact = array($contact);
4908 if (sizeof($best_contact) == 0)
4909 foreach ($contacts as $contact)
4910 if ($contact["network"] == "dspr")
4911 $best_contact = array($contact);
4913 if (sizeof($best_contact) == 0)
4914 foreach ($contacts as $contact)
4915 if ($contact["network"] == "stat")
4916 $best_contact = array($contact);
4918 if (sizeof($best_contact) == 0)
4919 foreach ($contacts as $contact)
4920 if ($contact["network"] == "pump")
4921 $best_contact = array($contact);
4923 if (sizeof($best_contact) == 0)
4924 foreach ($contacts as $contact)
4925 if ($contact["network"] == "twit")
4926 $best_contact = array($contact);
4928 if (sizeof($best_contact) == 1) {
4929 $contacts = $best_contact;
4931 $contacts = array($contacts[0]);
4935 // return all or a specified group of the user with the containing contacts
4936 function api_friendica_group_show($type)
4940 if (api_user() === false) throw new ForbiddenException();
4943 $user_info = api_get_user($a);
4944 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4945 $uid = $user_info['uid'];
4947 // get data of the specified group id or all groups if not specified
4950 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4954 // error message if specified gid is not in database
4955 if (!DBM::is_result($r))
4956 throw new BadRequestException("gid not available");
4959 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4964 // loop through all groups and retrieve all members for adding data in the user array
4965 foreach ($r as $rr) {
4966 $members = Contact::getByGroupId($rr['id']);
4969 if ($type == "xml") {
4970 $user_element = "users";
4972 foreach ($members as $member) {
4973 $user = api_get_user($a, $member['nurl']);
4974 $users[$k++.":user"] = $user;
4977 $user_element = "user";
4978 foreach ($members as $member) {
4979 $user = api_get_user($a, $member['nurl']);
4983 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4985 return api_format_data("groups", $type, array('group' => $grps));
4987 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4990 // delete the specified group of the user
4991 function api_friendica_group_delete($type)
4995 if (api_user() === false) {
4996 throw new ForbiddenException();
5000 $user_info = api_get_user($a);
5001 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5002 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5003 $uid = $user_info['uid'];
5005 // error if no gid specified
5006 if ($gid == 0 || $name == "") {
5007 throw new BadRequestException('gid or name not specified');
5010 // get data of the specified group id
5012 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5016 // error message if specified gid is not in database
5017 if (!DBM::is_result($r)) {
5018 throw new BadRequestException('gid not available');
5021 // get data of the specified group id and group name
5023 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5028 // error message if specified gid is not in database
5029 if (!DBM::is_result($rname)) {
5030 throw new BadRequestException('wrong group name');
5034 $ret = Group::removeByName($uid, $name);
5037 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
5038 return api_format_data("group_delete", $type, array('result' => $success));
5040 throw new BadRequestException('other API error');
5043 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5046 // create the specified group with the posted array of contacts
5047 function api_friendica_group_create($type)
5051 if (api_user() === false) throw new ForbiddenException();
5054 $user_info = api_get_user($a);
5055 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5056 $uid = $user_info['uid'];
5057 $json = json_decode($_POST['json'], true);
5058 $users = $json['user'];
5060 // error if no name specified
5062 throw new BadRequestException('group name not specified');
5064 // get data of the specified group name
5066 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5070 // error message if specified group name already exists
5071 if (DBM::is_result($rname))
5072 throw new BadRequestException('group name already exists');
5074 // check if specified group name is a deleted group
5076 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5080 // error message if specified group name already exists
5081 if (DBM::is_result($rname))
5082 $reactivate_group = true;
5085 $ret = Group::create($uid, $name);
5087 $gid = Group::getIdByName($uid, $name);
5089 throw new BadRequestException('other API error');
5093 $erroraddinguser = false;
5094 $errorusers = array();
5095 foreach ($users as $user) {
5096 $cid = $user['cid'];
5097 // check if user really exists as contact
5099 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5103 if (count($contact)) {
5104 $result = Group::addMember($gid, $cid);
5106 $erroraddinguser = true;
5107 $errorusers[] = $cid;
5111 // return success message incl. missing users in array
5112 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
5113 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
5114 return api_format_data("group_create", $type, array('result' => $success));
5116 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5119 // update the specified group with the posted array of contacts
5120 function api_friendica_group_update($type)
5124 if (api_user() === false) throw new ForbiddenException();
5127 $user_info = api_get_user($a);
5128 $uid = $user_info['uid'];
5129 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5130 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5131 $json = json_decode($_POST['json'], true);
5132 $users = $json['user'];
5134 // error if no name specified
5136 throw new BadRequestException('group name not specified');
5138 // error if no gid specified
5140 throw new BadRequestException('gid not specified');
5143 $members = Contact::getByGroupId($gid);
5144 foreach ($members as $member) {
5145 $cid = $member['id'];
5146 foreach ($users as $user) {
5147 $found = ($user['cid'] == $cid ? true : false);
5150 $ret = Group::removeMemberByName($uid, $name, $cid);
5155 $erroraddinguser = false;
5156 $errorusers = array();
5157 foreach ($users as $user) {
5158 $cid = $user['cid'];
5159 // check if user really exists as contact
5161 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5166 if (count($contact)) {
5167 $result = Group::addMember($gid, $cid);
5169 $erroraddinguser = true;
5170 $errorusers[] = $cid;
5174 // return success message incl. missing users in array
5175 $status = ($erroraddinguser ? "missing user" : "ok");
5176 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
5177 return api_format_data("group_update", $type, array('result' => $success));
5180 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5182 function api_friendica_activity($type)
5186 if (api_user() === false) throw new ForbiddenException();
5187 $verb = strtolower($a->argv[3]);
5188 $verb = preg_replace("|\..*$|", "", $verb);
5190 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5192 $res = do_like($id, $verb);
5195 if ($type == "xml") {
5200 return api_format_data('ok', $type, array('ok' => $ok));
5202 throw new BadRequestException('Error adding activity');
5206 /// @TODO move to top of file or somwhere better
5207 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5208 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5209 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5210 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5211 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5212 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5213 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5214 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5215 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5216 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5219 * @brief Returns notifications
5221 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5224 function api_friendica_notification($type)
5228 if (api_user() === false) throw new ForbiddenException();
5229 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
5230 $nm = new NotificationsManager();
5232 $notes = $nm->getAll(array(), "+seen -date", 50);
5234 if ($type == "xml") {
5235 $xmlnotes = array();
5236 foreach ($notes as $note)
5237 $xmlnotes[] = array("@attributes" => $note);
5242 return api_format_data("notes", $type, array('note' => $notes));
5246 * @brief Set notification as seen and returns associated item (if possible)
5248 * POST request with 'id' param as notification id
5250 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5253 function api_friendica_notification_seen($type)
5257 if (api_user() === false) throw new ForbiddenException();
5258 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
5260 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5262 $nm = new NotificationsManager();
5263 $note = $nm->getByID($id);
5264 if (is_null($note)) throw new BadRequestException("Invalid argument");
5266 $nm->setSeen($note);
5267 if ($note['otype']=='item') {
5268 // would be really better with an ItemsManager and $im->getByID() :-P
5270 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5271 intval($note['iid']),
5272 intval(local_user())
5275 // we found the item, return it to the user
5276 $user_info = api_get_user($a);
5277 $ret = api_format_items($r, $user_info, false, $type);
5278 $data = array('status' => $ret);
5279 return api_format_data("status", $type, $data);
5281 // the item can't be found, but we set the note as seen, so we count this as a success
5283 return api_format_data('result', $type, array('result' => "success"));
5286 /// @TODO move to top of file or somwhere better
5287 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5288 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5291 * @brief update a direct_message to seen state
5293 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5294 * @return string (success result=ok, error result=error with error message)
5296 function api_friendica_direct_messages_setseen($type)
5299 if (api_user() === false) {
5300 throw new ForbiddenException();
5304 $user_info = api_get_user($a);
5305 $uid = $user_info['uid'];
5306 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5308 // return error if id is zero
5310 $answer = array('result' => 'error', 'message' => 'message id not specified');
5311 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5314 // get data of the specified message id
5316 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5321 // error message if specified id is not in database
5322 if (!DBM::is_result($r)) {
5323 $answer = array('result' => 'error', 'message' => 'message id not in database');
5324 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5327 // update seen indicator
5329 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5336 $answer = array('result' => 'ok', 'message' => 'message set to seen');
5337 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
5339 $answer = array('result' => 'error', 'message' => 'unknown error');
5340 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5344 /// @TODO move to top of file or somwhere better
5345 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5348 * @brief search for direct_messages containing a searchstring through api
5350 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5351 * @return string (success: success=true if found and search_result contains found messages
5352 * success=false if nothing was found, search_result='nothing found',
5353 * error: result=error with error message)
5355 function api_friendica_direct_messages_search($type)
5359 if (api_user() === false) {
5360 throw new ForbiddenException();
5364 $user_info = api_get_user($a);
5365 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5366 $uid = $user_info['uid'];
5368 // error if no searchstring specified
5369 if ($searchstring == "") {
5370 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
5371 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
5374 // get data for the specified searchstring
5376 "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",
5378 dbesc('%'.$searchstring.'%')
5381 $profile_url = $user_info["url"];
5383 // message if nothing was found
5384 if (!DBM::is_result($r)) {
5385 $success = array('success' => false, 'search_results' => 'problem with query');
5386 } elseif (count($r) == 0) {
5387 $success = array('success' => false, 'search_results' => 'nothing found');
5390 foreach ($r as $item) {
5391 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5392 $recipient = $user_info;
5393 $sender = api_get_user($a, normalise_link($item['contact-url']));
5394 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5395 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5396 $sender = $user_info;
5399 $ret[] = api_format_messages($item, $recipient, $sender);
5401 $success = array('success' => true, 'search_results' => $ret);
5404 return api_format_data("direct_message_search", $type, array('$result' => $success));
5407 /// @TODO move to top of file or somwhere better
5408 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5411 * @brief return data of all the profiles a user has to the client
5413 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5416 function api_friendica_profile_show($type)
5420 if (api_user() === false) {
5421 throw new ForbiddenException();
5425 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5427 // retrieve general information about profiles for user
5428 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5429 $directory = Config::get('system', 'directory');
5431 // get data of the specified profile id or all profiles of the user if not specified
5432 if ($profileid != 0) {
5434 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5439 // error message if specified gid is not in database
5440 if (!DBM::is_result($r)) {
5441 throw new BadRequestException("profile_id not available");
5445 "SELECT * FROM `profile` WHERE `uid` = %d",
5449 // loop through all returned profiles and retrieve data and users
5451 foreach ($r as $rr) {
5452 $profile = api_format_items_profiles($rr, $type);
5454 // select all users from contact table, loop and prepare standard return for user data
5457 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5459 intval($rr['profile_id'])
5462 foreach ($r as $rr) {
5463 $user = api_get_user($a, $rr['nurl']);
5464 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5466 $profile['users'] = $users;
5468 // add prepared profile data to array for final return
5469 if ($type == "xml") {
5470 $profiles[$k++ . ":profile"] = $profile;
5472 $profiles[] = $profile;
5476 // return settings, authenticated user and profiles data
5477 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5479 $result = array('multi_profiles' => $multi_profiles ? true : false,
5480 'global_dir' => $directory,
5481 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5482 'profiles' => $profiles);
5483 return api_format_data("friendica_profiles", $type, array('$result' => $result));
5485 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5488 * Returns a list of saved searches.
5490 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5492 * @param string $type Return format: json or xml
5494 * @return string|array
5496 function api_saved_searches_list($type)
5498 $terms = dba::select('search', array('id', 'term'), array('uid' => local_user()));
5501 while ($term = $terms->fetch()) {
5503 'name' => $term['term'],
5504 'query' => $term['term'],
5505 'id_str' => $term['id'],
5506 'id' => intval($term['id'])
5512 return api_format_data("terms", $type, array('terms' => $result));
5515 /// @TODO move to top of file or somwhere better
5516 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5519 @TODO Maybe open to implement?
5521 [pagename] => api/1.1/statuses/lookup.json
5522 [id] => 605138389168451584
5523 [include_cards] => true
5524 [cards_platform] => Android-12
5525 [include_entities] => true
5526 [include_my_retweet] => 1
5528 [include_reply_count] => true
5529 [include_descendent_reply_count] => true
5533 Not implemented by now:
5534 statuses/retweets_of_me
5539 account/update_location
5540 account/update_profile_background_image
5543 friendica/profile/update
5544 friendica/profile/create
5545 friendica/profile/delete
5547 Not implemented in status.net:
5548 statuses/retweeted_to_me
5549 statuses/retweeted_by_me
5550 direct_messages/destroy
5552 account/update_delivery_device
5553 notifications/follow