3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
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 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
59 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
60 * into a page, and visitors will post something without noticing it).
62 * @brief Auth API user
66 if (x($_SESSION, 'allow_api')) {
74 * Clients can send 'source' parameter to be show in post metadata
75 * as "sent via <source>".
76 * Some clients doesn't send a source param, we support ones we know
79 * @brief Get source name from API client
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 * Register a function to be the endpoint for defined API path.
115 * @brief Register API endpoint
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 * Log in user via OAuth1 or Simple HTTP Auth.
146 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
148 * @brief Login API user
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 * API endpoints can define which HTTP method to accept when called.
246 * This function check the current HTTP method agains endpoint
249 * @brief Check HTTP method of called API
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 * Authenticate user, call registered API function, set HTTP headers
265 * @brief Main API entry point
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");
370 foreach ($r as $rr) {
371 $json = json_encode($rr);
373 if (x($_GET, 'callback')) {
374 $json = $_GET['callback'] . "(" . $json . ")";
379 header("Content-Type: application/rss+xml");
380 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
383 header("Content-Type: application/atom+xml");
384 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
390 logger('API call not implemented: ' . $a->query_string);
391 throw new NotImplementedException();
392 } catch (HTTPException $e) {
393 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
394 return api_error($type, $e);
399 * @brief Format API error string
401 * @param string $type Return type (xml, json, rss, as)
402 * @param object $e HTTPException Error object
403 * @return string error message formatted as $type
405 function api_error($type, $e)
409 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
410 /// @TODO: https://dev.twitter.com/overview/api/response-codes
412 $error = array("error" => $error,
413 "code" => $e->httpcode . " " . $e->httpdesc,
414 "request" => $a->query_string);
416 $ret = api_format_data('status', $type, array('status' => $error));
420 header("Content-Type: text/xml");
424 header("Content-Type: application/json");
425 return json_encode($ret);
428 header("Content-Type: application/rss+xml");
432 header("Content-Type: application/atom+xml");
439 * @brief Set values for RSS template
442 * @param array $arr Array to be passed to template
443 * @param array $user_info User info
445 * @todo find proper type-hints
447 function api_rss_extra(App $a, $arr, $user_info)
449 if (is_null($user_info)) {
450 $user_info = api_get_user($a);
453 $arr['$user'] = $user_info;
454 $arr['$rss'] = array(
455 'alternate' => $user_info['url'],
456 'self' => System::baseUrl() . "/" . $a->query_string,
457 'base' => System::baseUrl(),
458 'updated' => api_date(null),
459 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
460 'language' => $user_info['language'],
461 'logo' => System::baseUrl() . "/images/friendica-32.png",
469 * @brief Unique contact to contact url.
471 * @param int $id Contact id
472 * @return bool|string
473 * Contact url or False if contact id is unknown
475 function api_unique_id_to_nurl($id)
477 $r = dba::select('contact', array('nurl'), array('uid' => 0, 'id' => $id), array('limit' => 1));
479 if (DBM::is_result($r)) {
487 * @brief Get user info array.
489 * @param object $a App
490 * @param int|string $contact_id Contact ID or URL
492 function api_get_user(App $a, $contact_id = null)
501 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
503 // Searching for contact URL
504 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
505 $user = dbesc(normalise_link($contact_id));
507 $extra_query = "AND `contact`.`nurl` = '%s' ";
508 if (api_user() !== false) {
509 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
513 // Searching for contact id with uid = 0
514 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
515 $user = dbesc(api_unique_id_to_nurl($contact_id));
518 throw new BadRequestException("User not found.");
522 $extra_query = "AND `contact`.`nurl` = '%s' ";
523 if (api_user() !== false) {
524 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
528 if (is_null($user) && x($_GET, 'user_id')) {
529 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
532 throw new BadRequestException("User not found.");
536 $extra_query = "AND `contact`.`nurl` = '%s' ";
537 if (api_user() !== false) {
538 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
541 if (is_null($user) && x($_GET, 'screen_name')) {
542 $user = dbesc($_GET['screen_name']);
544 $extra_query = "AND `contact`.`nick` = '%s' ";
545 if (api_user() !== false) {
546 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
550 if (is_null($user) && x($_GET, 'profileurl')) {
551 $user = dbesc(normalise_link($_GET['profileurl']));
553 $extra_query = "AND `contact`.`nurl` = '%s' ";
554 if (api_user() !== false) {
555 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
559 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
560 $argid = count($called_api);
561 list($user, $null) = explode(".", $a->argv[$argid]);
562 if (is_numeric($user)) {
563 $user = dbesc(api_unique_id_to_nurl($user));
570 $extra_query = "AND `contact`.`nurl` = '%s' ";
571 if (api_user() !== false) {
572 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
575 $user = dbesc($user);
577 $extra_query = "AND `contact`.`nick` = '%s' ";
578 if (api_user() !== false) {
579 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
584 logger("api_get_user: user ".$user, LOGGER_DEBUG);
587 if (api_user() === false) {
591 $user = $_SESSION['uid'];
592 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
596 logger('api_user: ' . $extra_query . ', user: ' . $user);
600 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
606 // Selecting the id by priority, friendica first
607 api_best_nickname($uinfo);
609 // if the contact wasn't found, fetch it from the contacts with uid = 0
610 if (!DBM::is_result($uinfo)) {
614 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
617 if (DBM::is_result($r)) {
618 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
620 // If no nick where given, extract it from the address
621 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
622 $r[0]['nick'] = api_get_nick($r[0]["url"]);
627 'id_str' => (string) $r[0]["id"],
628 'name' => $r[0]["name"],
629 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
630 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
631 'description' => $r[0]["about"],
632 'profile_image_url' => $r[0]["micro"],
633 'profile_image_url_https' => $r[0]["micro"],
634 'url' => $r[0]["url"],
635 'protected' => false,
636 'followers_count' => 0,
637 'friends_count' => 0,
639 'created_at' => api_date($r[0]["created"]),
640 'favourites_count' => 0,
642 'time_zone' => 'UTC',
643 'geo_enabled' => false,
645 'statuses_count' => 0,
647 'contributors_enabled' => false,
648 'is_translator' => false,
649 'is_translation_enabled' => false,
650 'following' => false,
651 'follow_request_sent' => false,
652 'statusnet_blocking' => false,
653 'notifications' => false,
654 'statusnet_profile_url' => $r[0]["url"],
656 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
658 'network' => $r[0]["network"],
663 throw new BadRequestException("User not found.");
667 if ($uinfo[0]['self']) {
668 if ($uinfo[0]['network'] == "") {
669 $uinfo[0]['network'] = NETWORK_DFRN;
673 "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
677 "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
681 /// @TODO old-lost code? (twice)
682 // Counting is deactivated by now, due to performance issues
683 // count public wall messages
684 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
685 // intval($uinfo[0]['uid'])
687 //$countitms = $r[0]['count'];
690 // Counting is deactivated by now, due to performance issues
691 //$r = q("SELECT count(*) as `count` FROM `item`
692 // WHERE `contact-id` = %d",
693 // intval($uinfo[0]['id'])
695 //$countitms = $r[0]['count'];
699 /// @TODO old-lost code? (twice)
701 // Counting is deactivated by now, due to performance issues
703 $r = q("SELECT count(*) as `count` FROM `contact`
704 WHERE `uid` = %d AND `rel` IN ( %d, %d )
705 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
706 intval($uinfo[0]['uid']),
707 intval(CONTACT_IS_SHARING),
708 intval(CONTACT_IS_FRIEND)
710 $countfriends = $r[0]['count'];
712 $r = q("SELECT count(*) as `count` FROM `contact`
713 WHERE `uid` = %d AND `rel` IN ( %d, %d )
714 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
715 intval($uinfo[0]['uid']),
716 intval(CONTACT_IS_FOLLOWER),
717 intval(CONTACT_IS_FRIEND)
719 $countfollowers = $r[0]['count'];
721 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
722 intval($uinfo[0]['uid'])
724 $starred = $r[0]['count'];
727 if (! $uinfo[0]['self']) {
737 // Add a nick if it isn't present there
738 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
739 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
742 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
744 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
746 if (!empty($profile[0]['about'])) {
747 $description = $profile[0]['about'];
749 $description = $uinfo[0]["about"];
752 if (!empty($usr[0]['default-location'])) {
753 $location = $usr[0]['default-location'];
754 } elseif (!empty($uinfo[0]["location"])) {
755 $location = $uinfo[0]["location"];
757 $location = $network_name;
761 'id' => intval($pcontact_id),
762 'id_str' => (string) intval($pcontact_id),
763 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
764 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
765 'location' => $location,
766 'description' => $description,
767 'profile_image_url' => $uinfo[0]['micro'],
768 'profile_image_url_https' => $uinfo[0]['micro'],
769 'url' => $uinfo[0]['url'],
770 'protected' => false,
771 'followers_count' => intval($countfollowers),
772 'friends_count' => intval($countfriends),
774 'created_at' => api_date($uinfo[0]['created']),
775 'favourites_count' => intval($starred),
777 'time_zone' => 'UTC',
778 'geo_enabled' => false,
780 'statuses_count' => intval($countitms),
782 'contributors_enabled' => false,
783 'is_translator' => false,
784 'is_translation_enabled' => false,
785 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
786 'follow_request_sent' => false,
787 'statusnet_blocking' => false,
788 'notifications' => false,
790 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
791 'statusnet_profile_url' => $uinfo[0]['url'],
792 'uid' => intval($uinfo[0]['uid']),
793 'cid' => intval($uinfo[0]['cid']),
794 'self' => $uinfo[0]['self'],
795 'network' => $uinfo[0]['network'],
798 // If this is a local user and it uses Frio, we can get its color preferences.
800 $theme_info = dba::select('user', ['theme'], ['uid' => $ret['uid']], ['limit' => 1]);
801 if ($theme_info['theme'] === 'frio') {
802 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
803 if ($schema && ($schema != '---')) {
804 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
805 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
806 require_once $schemefile;
809 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
810 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
811 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
817 $link_color = "#6fdbe8";
820 $bgcolor = "#ededed";
823 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
824 $ret['profile_link_color'] = str_replace('#', '', $link_color);
825 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
833 * @brief return api-formatted array for item's author and owner
835 * @param object $a App
836 * @param array $item item from db
837 * @return array(array:author, array:owner)
839 function api_item_get_user(App $a, $item)
841 $status_user = api_get_user($a, $item["author-link"]);
843 $status_user["protected"] = (($item["allow_cid"] != "") ||
844 ($item["allow_gid"] != "") ||
845 ($item["deny_cid"] != "") ||
846 ($item["deny_gid"] != "") ||
849 if ($item['thr-parent'] == $item['uri']) {
850 $owner_user = api_get_user($a, $item["owner-link"]);
852 $owner_user = $status_user;
855 return (array($status_user, $owner_user));
859 * @brief walks recursively through an array with the possibility to change value and key
861 * @param array $array The array to walk through
862 * @param string $callback The callback function
864 * @return array the transformed array
866 function api_walk_recursive(array &$array, callable $callback)
868 $new_array = array();
870 foreach ($array as $k => $v) {
872 if ($callback($v, $k)) {
873 $new_array[$k] = api_walk_recursive($v, $callback);
876 if ($callback($v, $k)) {
887 * @brief Callback function to transform the array in an array that can be transformed in a XML file
889 * @param mixed $item Array item value
890 * @param string $key Array key
892 * @return boolean Should the array item be deleted?
894 function api_reformat_xml(&$item, &$key)
896 if (is_bool($item)) {
897 $item = ($item ? "true" : "false");
900 if (substr($key, 0, 10) == "statusnet_") {
901 $key = "statusnet:".substr($key, 10);
902 } elseif (substr($key, 0, 10) == "friendica_") {
903 $key = "friendica:".substr($key, 10);
905 /// @TODO old-lost code?
907 // $key = "default:".$key;
913 * @brief Creates the XML from a JSON style array
915 * @param array $data JSON style array
916 * @param string $root_element Name of the root element
918 * @return string The XML data
920 function api_create_xml($data, $root_element)
922 $childname = key($data);
923 $data2 = array_pop($data);
926 $namespaces = array("" => "http://api.twitter.com",
927 "statusnet" => "http://status.net/schema/api/1/",
928 "friendica" => "http://friendi.ca/schema/api/1/",
929 "georss" => "http://www.georss.org/georss");
931 /// @todo Auto detection of needed namespaces
932 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
933 $namespaces = array();
936 if (is_array($data2)) {
937 api_walk_recursive($data2, "api_reformat_xml");
944 foreach ($data2 as $item) {
945 $data4[$i++.":".$childname] = $item;
951 $data3 = array($root_element => $data2);
953 $ret = XML::fromArray($data3, $xml, false, $namespaces);
958 * @brief Formats the data according to the data type
960 * @param string $root_element Name of the root element
961 * @param string $type Return type (atom, rss, xml, json)
962 * @param array $data JSON style array
964 * @return (string|object|array) XML data or JSON data
966 function api_format_data($root_element, $type, $data)
972 $ret = api_create_xml($data, $root_element);
987 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
988 * returns a 401 status code and an error message if not.
989 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
991 * @param string $type Return type (atom, rss, xml, json)
993 function api_account_verify_credentials($type)
998 if (api_user() === false) {
999 throw new ForbiddenException();
1002 unset($_REQUEST["user_id"]);
1003 unset($_GET["user_id"]);
1005 unset($_REQUEST["screen_name"]);
1006 unset($_GET["screen_name"]);
1008 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
1010 $user_info = api_get_user($a);
1012 // "verified" isn't used here in the standard
1013 unset($user_info["verified"]);
1015 // - Adding last status
1016 if (!$skip_status) {
1017 $user_info["status"] = api_status_show("raw");
1018 if (!count($user_info["status"])) {
1019 unset($user_info["status"]);
1021 unset($user_info["status"]["user"]);
1025 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1026 unset($user_info["uid"]);
1027 unset($user_info["self"]);
1029 return api_format_data("user", $type, array('user' => $user_info));
1032 /// @TODO move to top of file or somewhere better
1033 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1036 * Get data from $_POST or $_GET
1040 function requestdata($k)
1042 if (x($_POST, $k)) {
1052 * Waitman Gobble Mod
1054 * @param string $type Return type (atom, rss, xml, json)
1056 * @return array|string
1058 function api_statuses_mediap($type)
1062 if (api_user() === false) {
1063 logger('api_statuses_update: no user');
1064 throw new ForbiddenException();
1066 $user_info = api_get_user($a);
1068 $_REQUEST['type'] = 'wall';
1069 $_REQUEST['profile_uid'] = api_user();
1070 $_REQUEST['api_source'] = true;
1071 $txt = requestdata('status');
1072 /// @TODO old-lost code?
1073 //$txt = urldecode(requestdata('status'));
1075 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1076 $txt = html2bb_video($txt);
1077 $config = HTMLPurifier_Config::createDefault();
1078 $config->set('Cache.DefinitionImpl', null);
1079 $purifier = new HTMLPurifier($config);
1080 $txt = $purifier->purify($txt);
1082 $txt = html2bbcode($txt);
1084 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1086 // tell wall_upload function to return img info instead of echo
1087 $_REQUEST['hush'] = 'yeah';
1088 $bebop = wall_upload_post($a);
1090 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1091 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1094 // this should output the last post (the one we just posted).
1095 return api_status_show($type);
1098 /// @TODO move this to top of file or somewhere better!
1099 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1102 * Updates the user’s current status.
1104 * @param string $type Return type (atom, rss, xml, json)
1106 * @return array|string
1107 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1109 function api_statuses_update($type)
1114 if (api_user() === false) {
1115 logger('api_statuses_update: no user');
1116 throw new ForbiddenException();
1119 $user_info = api_get_user($a);
1121 // convert $_POST array items to the form we use for web posts.
1123 // logger('api_post: ' . print_r($_POST,true));
1125 if (requestdata('htmlstatus')) {
1126 $txt = requestdata('htmlstatus');
1127 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1128 $txt = html2bb_video($txt);
1130 $config = HTMLPurifier_Config::createDefault();
1131 $config->set('Cache.DefinitionImpl', null);
1133 $purifier = new HTMLPurifier($config);
1134 $txt = $purifier->purify($txt);
1136 $_REQUEST['body'] = html2bbcode($txt);
1139 $_REQUEST['body'] = requestdata('status');
1142 $_REQUEST['title'] = requestdata('title');
1144 $parent = requestdata('in_reply_to_status_id');
1146 // Twidere sends "-1" if it is no reply ...
1147 if ($parent == -1) {
1151 if (ctype_digit($parent)) {
1152 $_REQUEST['parent'] = $parent;
1154 $_REQUEST['parent_uri'] = $parent;
1157 if (requestdata('lat') && requestdata('long')) {
1158 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1160 $_REQUEST['profile_uid'] = api_user();
1163 $_REQUEST['type'] = 'net-comment';
1165 // Check for throttling (maximum posts per day, week and month)
1166 $throttle_day = Config::get('system', 'throttle_limit_day');
1167 if ($throttle_day > 0) {
1168 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1171 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1172 AND `created` > '%s' AND `id` = `parent`",
1177 if (DBM::is_result($r)) {
1178 $posts_day = $r[0]["posts_day"];
1183 if ($posts_day > $throttle_day) {
1184 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1185 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1186 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1190 $throttle_week = Config::get('system', 'throttle_limit_week');
1191 if ($throttle_week > 0) {
1192 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1195 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1196 AND `created` > '%s' AND `id` = `parent`",
1201 if (DBM::is_result($r)) {
1202 $posts_week = $r[0]["posts_week"];
1207 if ($posts_week > $throttle_week) {
1208 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1209 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1210 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1214 $throttle_month = Config::get('system', 'throttle_limit_month');
1215 if ($throttle_month > 0) {
1216 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1219 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1220 AND `created` > '%s' AND `id` = `parent`",
1225 if (DBM::is_result($r)) {
1226 $posts_month = $r[0]["posts_month"];
1231 if ($posts_month > $throttle_month) {
1232 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1233 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1234 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1238 $_REQUEST['type'] = 'wall';
1241 if (x($_FILES, 'media')) {
1242 // upload the image if we have one
1243 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1244 $media = wall_upload_post($a);
1245 if (strlen($media) > 0) {
1246 $_REQUEST['body'] .= "\n\n" . $media;
1250 // To-Do: Multiple IDs
1251 if (requestdata('media_ids')) {
1253 "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",
1254 intval(requestdata('media_ids')),
1257 if (DBM::is_result($r)) {
1258 $phototypes = Image::supportedTypes();
1259 $ext = $phototypes[$r[0]['type']];
1260 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1261 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1265 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1267 $_REQUEST['api_source'] = true;
1269 if (!x($_REQUEST, "source")) {
1270 $_REQUEST["source"] = api_source();
1273 // call out normal post function
1276 // this should output the last post (the one we just posted).
1277 return api_status_show($type);
1280 /// @TODO move to top of file or somewhere better
1281 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1282 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1285 * Uploads an image to Friendica.
1287 * @param string $type Return type (atom, rss, xml, json)
1290 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1292 function api_media_upload($type)
1296 if (api_user() === false) {
1298 throw new ForbiddenException();
1301 $user_info = api_get_user($a);
1303 if (!x($_FILES, 'media')) {
1305 throw new BadRequestException("No media.");
1308 $media = wall_upload_post($a, false);
1311 throw new InternalServerErrorException();
1314 $returndata = array();
1315 $returndata["media_id"] = $media["id"];
1316 $returndata["media_id_string"] = (string)$media["id"];
1317 $returndata["size"] = $media["size"];
1318 $returndata["image"] = array("w" => $media["width"],
1319 "h" => $media["height"],
1320 "image_type" => $media["type"]);
1322 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1324 return array("media" => $returndata);
1327 /// @TODO move to top of file or somewhere better
1328 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1332 * @param string $type Return type (atom, rss, xml, json)
1334 * @return array|string
1336 function api_status_show($type)
1340 $user_info = api_get_user($a);
1342 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1344 if ($type == "raw") {
1345 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1350 // get last public wall message
1354 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1355 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1356 AND `item`.`type` != 'activity' $privacy_sql
1357 ORDER BY `item`.`id` DESC
1359 intval($user_info['cid']),
1361 dbesc($user_info['url']),
1362 dbesc(normalise_link($user_info['url'])),
1363 dbesc($user_info['url']),
1364 dbesc(normalise_link($user_info['url']))
1367 if (DBM::is_result($lastwall)) {
1368 $lastwall = $lastwall[0];
1370 $in_reply_to = api_in_reply_to($lastwall);
1372 $converted = api_convert_item($lastwall);
1374 if ($type == "xml") {
1375 $geo = "georss:point";
1380 $status_info = array(
1381 'created_at' => api_date($lastwall['created']),
1382 'id' => intval($lastwall['id']),
1383 'id_str' => (string) $lastwall['id'],
1384 'text' => $converted["text"],
1385 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1386 'truncated' => false,
1387 'in_reply_to_status_id' => $in_reply_to['status_id'],
1388 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1389 'in_reply_to_user_id' => $in_reply_to['user_id'],
1390 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1391 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1392 'user' => $user_info,
1394 'coordinates' => "",
1396 'contributors' => "",
1397 'is_quote_status' => false,
1398 'retweet_count' => 0,
1399 'favorite_count' => 0,
1400 'favorited' => $lastwall['starred'] ? true : false,
1401 'retweeted' => false,
1402 'possibly_sensitive' => false,
1404 'statusnet_html' => $converted["html"],
1405 'statusnet_conversation_id' => $lastwall['parent'],
1406 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1409 if (count($converted["attachments"]) > 0) {
1410 $status_info["attachments"] = $converted["attachments"];
1413 if (count($converted["entities"]) > 0) {
1414 $status_info["entities"] = $converted["entities"];
1417 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1418 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1419 } elseif (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1420 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1423 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1424 unset($status_info["user"]["uid"]);
1425 unset($status_info["user"]["self"]);
1428 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1430 if ($type == "raw") {
1431 return $status_info;
1434 return api_format_data("statuses", $type, array('status' => $status_info));
1438 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1439 * The author's most recent status will be returned inline.
1441 * @param string $type Return type (atom, rss, xml, json)
1442 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1444 function api_users_show($type)
1448 $user_info = api_get_user($a);
1452 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1453 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1454 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1455 AND `type`!='activity'
1456 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1460 dbesc(ACTIVITY_POST),
1461 intval($user_info['cid']),
1462 dbesc($user_info['url']),
1463 dbesc(normalise_link($user_info['url'])),
1464 dbesc($user_info['url']),
1465 dbesc(normalise_link($user_info['url']))
1468 if (DBM::is_result($lastwall)) {
1469 $lastwall = $lastwall[0];
1471 $in_reply_to = api_in_reply_to($lastwall);
1473 $converted = api_convert_item($lastwall);
1475 if ($type == "xml") {
1476 $geo = "georss:point";
1481 $user_info['status'] = array(
1482 'text' => $converted["text"],
1483 'truncated' => false,
1484 'created_at' => api_date($lastwall['created']),
1485 'in_reply_to_status_id' => $in_reply_to['status_id'],
1486 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1487 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1488 'id' => intval($lastwall['contact-id']),
1489 'id_str' => (string) $lastwall['contact-id'],
1490 'in_reply_to_user_id' => $in_reply_to['user_id'],
1491 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1492 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1494 'favorited' => $lastwall['starred'] ? true : false,
1495 'statusnet_html' => $converted["html"],
1496 'statusnet_conversation_id' => $lastwall['parent'],
1497 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1500 if (count($converted["attachments"]) > 0) {
1501 $user_info["status"]["attachments"] = $converted["attachments"];
1504 if (count($converted["entities"]) > 0) {
1505 $user_info["status"]["entities"] = $converted["entities"];
1508 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1509 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1512 if (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1513 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
1517 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1518 unset($user_info["uid"]);
1519 unset($user_info["self"]);
1521 return api_format_data("user", $type, array('user' => $user_info));
1524 /// @TODO move to top of file or somewhere better
1525 api_register_func('api/users/show', 'api_users_show');
1526 api_register_func('api/externalprofile/show', 'api_users_show');
1529 * Search a public user account.
1531 * @param string $type Return type (atom, rss, xml, json)
1533 * @return array|string
1534 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1536 function api_users_search($type)
1540 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1542 $userlist = array();
1544 if (x($_GET, 'q')) {
1545 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1547 if (!DBM::is_result($r)) {
1548 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1551 if (DBM::is_result($r)) {
1553 foreach ($r as $user) {
1554 $user_info = api_get_user($a, $user["id"]);
1556 if ($type == "xml") {
1557 $userlist[$k++.":user"] = $user_info;
1559 $userlist[] = $user_info;
1562 $userlist = array("users" => $userlist);
1564 throw new BadRequestException("User not found.");
1567 throw new BadRequestException("User not found.");
1569 return api_format_data("users", $type, $userlist);
1572 /// @TODO move to top of file or somewhere better
1573 api_register_func('api/users/search', 'api_users_search');
1576 * Return user objects
1578 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1580 * @param string $type Return format: json or xml
1582 * @return array|string
1583 * @throws NotFoundException if the results are empty.
1585 function api_users_lookup($type)
1589 if (x($_REQUEST['user_id'])) {
1590 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1592 $users[] = api_get_user(get_app(), $id);
1597 if (empty($users)) {
1598 throw new NotFoundException;
1601 return api_format_data("users", $type, array('users' => $users));
1604 /// @TODO move to top of file or somewhere better
1605 api_register_func('api/users/lookup', 'api_users_lookup', true);
1608 * Returns statuses that match a specified query.
1610 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1612 * @param string $type Return format: json, xml, atom, rss
1614 * @return array|string
1615 * @throws BadRequestException if the "q" parameter is missing.
1617 function api_search($type)
1621 if (!x($_REQUEST, 'q')) {
1622 throw new BadRequestException("q parameter is required.");
1625 if (x($_REQUEST, 'rpp')) {
1626 $count = $_REQUEST['rpp'];
1627 } elseif (x($_REQUEST, 'count')) {
1628 $count = $_REQUEST['count'];
1633 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1634 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1635 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1637 $start = $page * $count;
1640 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1644 "SELECT ".item_fieldlists()."
1645 FROM `item` ".item_joins()."
1646 WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1647 AND `item`.`body` LIKE CONCAT('%',?,'%')
1650 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
1656 $data['status'] = api_format_items(dba::inArray($r), api_get_user(get_app()));
1658 return api_format_data("statuses", $type, $data);
1661 /// @TODO move to top of file or somewhere better
1662 api_register_func('api/search/tweets', 'api_search', true);
1663 api_register_func('api/search', 'api_search', true);
1666 * Returns the most recent statuses posted by the user and the users they follow.
1668 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1670 * @param string $type Return type (atom, rss, xml, json)
1672 * @todo Optional parameters
1673 * @todo Add reply info
1675 function api_statuses_home_timeline($type)
1679 if (api_user() === false) {
1680 throw new ForbiddenException();
1683 unset($_REQUEST["user_id"]);
1684 unset($_GET["user_id"]);
1686 unset($_REQUEST["screen_name"]);
1687 unset($_GET["screen_name"]);
1689 $user_info = api_get_user($a);
1690 // get last newtork messages
1693 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1694 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1698 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1699 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1700 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1701 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1702 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1704 $start = $page * $count;
1708 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1710 if ($exclude_replies > 0) {
1711 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1713 if ($conversation_id > 0) {
1714 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1718 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1719 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1720 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1721 `contact`.`id` AS `cid`
1723 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1724 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1725 WHERE `item`.`uid` = %d AND `verb` = '%s'
1726 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1729 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1731 dbesc(ACTIVITY_POST),
1737 $ret = api_format_items($r, $user_info, false, $type);
1739 // Set all posts from the query above to seen
1741 foreach ($r as $item) {
1742 $idarray[] = intval($item["id"]);
1745 $idlist = implode(",", $idarray);
1747 if ($idlist != "") {
1748 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1751 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1755 $data = array('status' => $ret);
1759 $data = api_rss_extra($a, $data, $user_info);
1763 return api_format_data("statuses", $type, $data);
1766 /// @TODO move to top of file or somewhere better
1767 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1768 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1771 * Returns the most recent statuses from public users.
1773 * @param string $type Return type (atom, rss, xml, json)
1775 * @return array|string
1777 function api_statuses_public_timeline($type)
1781 if (api_user() === false) {
1782 throw new ForbiddenException();
1785 $user_info = api_get_user($a);
1786 // get last newtork messages
1789 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1790 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1794 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1795 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1796 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1797 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1798 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1800 $start = $page * $count;
1802 if ($exclude_replies && !$conversation_id) {
1804 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1808 "SELECT " . item_fieldlists() . "
1810 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1811 " . item_joins() . "
1812 STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1813 AND NOT `user`.`hidewall`
1815 AND NOT `thread`.`private`
1817 AND `thread`.`visible`
1818 AND NOT `thread`.`deleted`
1819 AND NOT `thread`.`moderated`
1820 AND `thread`.`iid` > ?
1822 ORDER BY `thread`.`iid` DESC
1823 LIMIT " . intval($start) . ", " . intval($count),
1828 $r = dba::inArray($r);
1831 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1833 if ($conversation_id > 0) {
1834 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1838 "SELECT " . item_fieldlists() . "
1840 " . item_joins() . "
1841 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1842 AND NOT `user`.`hidewall`
1844 AND NOT `item`.`private`
1846 AND `item`.`visible`
1847 AND NOT `item`.`deleted`
1848 AND NOT `item`.`moderated`
1851 ORDER BY `item`.`id` DESC
1852 LIMIT " . intval($start) . ", " . intval($count),
1857 $r = dba::inArray($r);
1860 $ret = api_format_items($r, $user_info, false, $type);
1862 $data = array('status' => $ret);
1866 $data = api_rss_extra($a, $data, $user_info);
1870 return api_format_data("statuses", $type, $data);
1873 /// @TODO move to top of file or somewhere better
1874 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1877 * Returns the most recent statuses posted by users this node knows about.
1879 * @brief Returns the list of public federated posts this node knows about
1881 * @param string $type Return format: json, xml, atom, rss
1882 * @return array|string
1883 * @throws ForbiddenException
1885 function api_statuses_networkpublic_timeline($type)
1889 if (api_user() === false) {
1890 throw new ForbiddenException();
1893 $user_info = api_get_user($a);
1895 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1896 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1899 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1900 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1904 $start = ($page - 1) * $count;
1908 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1912 "SELECT " . item_fieldlists() . "
1914 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1915 " . item_joins() . "
1916 WHERE `thread`.`uid` = 0
1918 AND NOT `thread`.`private`
1919 AND `thread`.`visible`
1920 AND NOT `thread`.`deleted`
1921 AND NOT `thread`.`moderated`
1922 AND `thread`.`iid` > ?
1924 ORDER BY `thread`.`iid` DESC
1925 LIMIT " . intval($start) . ", " . intval($count),
1930 $r = dba::inArray($r);
1932 $ret = api_format_items($r, $user_info, false, $type);
1934 $data = array('status' => $ret);
1938 $data = api_rss_extra($a, $data, $user_info);
1942 return api_format_data("statuses", $type, $data);
1945 /// @TODO move to top of file or somewhere better
1946 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1949 * Returns a single status.
1951 * @param string $type Return type (atom, rss, xml, json)
1953 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1955 function api_statuses_show($type)
1959 if (api_user() === false) {
1960 throw new ForbiddenException();
1963 $user_info = api_get_user($a);
1966 $id = intval($a->argv[3]);
1969 $id = intval($_REQUEST["id"]);
1974 $id = intval($a->argv[4]);
1977 logger('API: api_statuses_show: ' . $id);
1979 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1982 if ($conversation) {
1983 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1985 $sql_extra .= " AND `item`.`id` = %d";
1989 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1990 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1991 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1992 `contact`.`id` AS `cid`
1994 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1995 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1996 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1997 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2000 dbesc(ACTIVITY_POST),
2004 /// @TODO How about copying this to above methods which don't check $r ?
2005 if (!DBM::is_result($r)) {
2006 throw new BadRequestException("There is no status with this id.");
2009 $ret = api_format_items($r, $user_info, false, $type);
2011 if ($conversation) {
2012 $data = array('status' => $ret);
2013 return api_format_data("statuses", $type, $data);
2015 $data = array('status' => $ret[0]);
2016 return api_format_data("status", $type, $data);
2020 /// @TODO move to top of file or somewhere better
2021 api_register_func('api/statuses/show', 'api_statuses_show', true);
2025 * @param string $type Return type (atom, rss, xml, json)
2027 * @todo nothing to say?
2029 function api_conversation_show($type)
2033 if (api_user() === false) {
2034 throw new ForbiddenException();
2037 $user_info = api_get_user($a);
2040 $id = intval($a->argv[3]);
2041 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2042 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
2046 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2047 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2049 $start = $page*$count;
2052 $id = intval($_REQUEST["id"]);
2057 $id = intval($a->argv[4]);
2060 logger('API: api_conversation_show: '.$id);
2062 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
2063 if (DBM::is_result($r)) {
2064 $id = $r[0]["parent"];
2070 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2073 // Not sure why this query was so complicated. We should keep it here for a while,
2074 // just to make sure that we really don't need it.
2075 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
2076 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
2079 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2080 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2081 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2082 `contact`.`id` AS `cid`
2084 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2085 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2086 WHERE `item`.`parent` = %d AND `item`.`visible`
2087 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2088 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2089 AND `item`.`id`>%d $sql_extra
2090 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2093 dbesc(ACTIVITY_POST),
2099 if (!DBM::is_result($r)) {
2100 throw new BadRequestException("There is no status with this id.");
2103 $ret = api_format_items($r, $user_info, false, $type);
2105 $data = array('status' => $ret);
2106 return api_format_data("statuses", $type, $data);
2109 /// @TODO move to top of file or somewhere better
2110 api_register_func('api/conversation/show', 'api_conversation_show', true);
2111 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2116 * @param string $type Return type (atom, rss, xml, json)
2118 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2120 function api_statuses_repeat($type)
2126 if (api_user() === false) {
2127 throw new ForbiddenException();
2130 $user_info = api_get_user($a);
2133 $id = intval($a->argv[3]);
2136 $id = intval($_REQUEST["id"]);
2141 $id = intval($a->argv[4]);
2144 logger('API: api_statuses_repeat: '.$id);
2147 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2148 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2149 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2150 `contact`.`id` AS `cid`
2152 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2153 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2154 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2155 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2156 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2158 AND `item`.`id`=%d",
2162 /// @TODO other style than above functions!
2163 if (DBM::is_result($r) && $r[0]['body'] != "") {
2164 if (strpos($r[0]['body'], "[/share]") !== false) {
2165 $pos = strpos($r[0]['body'], "[share");
2166 $post = substr($r[0]['body'], $pos);
2168 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2170 $post .= $r[0]['body'];
2171 $post .= "[/share]";
2173 $_REQUEST['body'] = $post;
2174 $_REQUEST['profile_uid'] = api_user();
2175 $_REQUEST['type'] = 'wall';
2176 $_REQUEST['api_source'] = true;
2178 if (!x($_REQUEST, "source")) {
2179 $_REQUEST["source"] = api_source();
2184 throw new ForbiddenException();
2187 // this should output the last post (the one we just posted).
2189 return api_status_show($type);
2192 /// @TODO move to top of file or somewhere better
2193 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2196 * Destroys a specific status.
2198 * @param string $type Return type (atom, rss, xml, json)
2200 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2202 function api_statuses_destroy($type)
2206 if (api_user() === false) {
2207 throw new ForbiddenException();
2210 $user_info = api_get_user($a);
2213 $id = intval($a->argv[3]);
2216 $id = intval($_REQUEST["id"]);
2221 $id = intval($a->argv[4]);
2224 logger('API: api_statuses_destroy: '.$id);
2226 $ret = api_statuses_show($type);
2228 drop_item($id, false);
2233 /// @TODO move to top of file or somewhere better
2234 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2237 * Returns the most recent mentions.
2239 * @param string $type Return type (atom, rss, xml, json)
2241 * @see http://developer.twitter.com/doc/get/statuses/mentions
2243 function api_statuses_mentions($type)
2247 if (api_user() === false) {
2248 throw new ForbiddenException();
2251 unset($_REQUEST["user_id"]);
2252 unset($_GET["user_id"]);
2254 unset($_REQUEST["screen_name"]);
2255 unset($_GET["screen_name"]);
2257 $user_info = api_get_user($a);
2258 // get last newtork messages
2262 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2263 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2267 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2268 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2269 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2271 $start = $page * $count;
2273 // Ugly code - should be changed
2274 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2275 $myurl = substr($myurl, strpos($myurl, '://') + 3);
2276 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
2277 $myurl = str_replace('www.', '', $myurl);
2278 $diasp_url = str_replace('/profile/', '/u/', $myurl);
2281 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2285 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2286 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2287 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2288 `contact`.`id` AS `cid`
2289 FROM `item` FORCE INDEX (`uid_id`)
2290 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2291 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2292 WHERE `item`.`uid` = %d AND `verb` = '%s'
2293 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2294 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2295 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2298 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2300 dbesc(ACTIVITY_POST),
2301 dbesc(protect_sprintf($myurl)),
2302 dbesc(protect_sprintf($myurl)),
2309 $ret = api_format_items($r, $user_info, false, $type);
2311 $data = array('status' => $ret);
2315 $data = api_rss_extra($a, $data, $user_info);
2319 return api_format_data("statuses", $type, $data);
2322 /// @TODO move to top of file or somewhere better
2323 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2324 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2327 * Returns the most recent statuses posted by the user.
2329 * @brief Returns a user's public timeline
2331 * @param string $type Either "json" or "xml"
2332 * @return string|array
2333 * @throws ForbiddenException
2334 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2336 function api_statuses_user_timeline($type)
2340 if (api_user() === false) {
2341 throw new ForbiddenException();
2344 $user_info = api_get_user($a);
2347 "api_statuses_user_timeline: api_user: ". api_user() .
2348 "\nuser_info: ".print_r($user_info, true) .
2349 "\n_REQUEST: ".print_r($_REQUEST, true),
2353 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2354 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2355 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2356 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2359 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2360 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2364 $start = ($page - 1) * $count;
2367 if ($user_info['self'] == 1) {
2368 $sql_extra .= " AND `item`.`wall` = 1 ";
2371 if ($exclude_replies > 0) {
2372 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2375 if ($conversation_id > 0) {
2376 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2380 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2384 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2385 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2386 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2387 `contact`.`id` AS `cid`
2388 FROM `item` FORCE INDEX (`uid_contactid_id`)
2389 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2390 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2391 WHERE `item`.`uid` = %d AND `verb` = '%s'
2392 AND `item`.`contact-id` = %d
2393 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2395 AND `item`.`id` > %d
2396 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2398 dbesc(ACTIVITY_POST),
2399 intval($user_info['cid']),
2405 $ret = api_format_items($r, $user_info, true, $type);
2407 $data = array('status' => $ret);
2411 $data = api_rss_extra($a, $data, $user_info);
2415 return api_format_data("statuses", $type, $data);
2418 /// @TODO move to top of file or somewhere better
2419 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2422 * Star/unstar an item.
2423 * param: id : id of the item
2425 * @param string $type Return type (atom, rss, xml, json)
2427 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2429 function api_favorites_create_destroy($type)
2433 if (api_user() === false) {
2434 throw new ForbiddenException();
2437 // for versioned api.
2438 /// @TODO We need a better global soluton
2439 $action_argv_id = 2;
2440 if ($a->argv[1] == "1.1") {
2441 $action_argv_id = 3;
2444 if ($a->argc <= $action_argv_id) {
2445 throw new BadRequestException("Invalid request.");
2447 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2448 if ($a->argc == $action_argv_id + 2) {
2449 $itemid = intval($a->argv[$action_argv_id + 1]);
2451 /// @TODO use x() to check if _REQUEST contains 'id'
2452 $itemid = intval($_REQUEST['id']);
2455 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2457 if (!DBM::is_result($item) || count($item) == 0) {
2458 throw new BadRequestException("Invalid item.");
2463 $item[0]['starred'] = 1;
2466 $item[0]['starred'] = 0;
2469 throw new BadRequestException("Invalid action ".$action);
2472 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2474 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2477 throw new InternalServerErrorException("DB error");
2481 $user_info = api_get_user($a);
2482 $rets = api_format_items($item, $user_info, false, $type);
2485 $data = array('status' => $ret);
2489 $data = api_rss_extra($a, $data, $user_info);
2492 return api_format_data("status", $type, $data);
2495 /// @TODO move to top of file or somewhere better
2496 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2497 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2500 * Returns the most recent favorite statuses.
2502 * @param string $type Return type (atom, rss, xml, json)
2504 * @return string|array
2506 function api_favorites($type)
2512 if (api_user() === false) {
2513 throw new ForbiddenException();
2516 $called_api = array();
2518 $user_info = api_get_user($a);
2520 // in friendica starred item are private
2521 // return favorites only for self
2522 logger('api_favorites: self:' . $user_info['self']);
2524 if ($user_info['self'] == 0) {
2530 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2531 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2532 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2533 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2538 $start = $page*$count;
2541 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2545 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2546 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2547 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2548 `contact`.`id` AS `cid`
2549 FROM `item`, `contact`
2550 WHERE `item`.`uid` = %d
2551 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2552 AND `item`.`starred` = 1
2553 AND `contact`.`id` = `item`.`contact-id`
2554 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2557 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2564 $ret = api_format_items($r, $user_info, false, $type);
2567 $data = array('status' => $ret);
2571 $data = api_rss_extra($a, $data, $user_info);
2574 return api_format_data("statuses", $type, $data);
2577 /// @TODO move to top of file or somewhere better
2578 api_register_func('api/favorites', 'api_favorites', true);
2582 * @param array $item
2583 * @param array $recipient
2584 * @param array $sender
2588 function api_format_messages($item, $recipient, $sender)
2590 // standard meta information
2592 'id' => $item['id'],
2593 'sender_id' => $sender['id'] ,
2595 'recipient_id' => $recipient['id'],
2596 'created_at' => api_date($item['created']),
2597 'sender_screen_name' => $sender['screen_name'],
2598 'recipient_screen_name' => $recipient['screen_name'],
2599 'sender' => $sender,
2600 'recipient' => $recipient,
2602 'friendica_seen' => $item['seen'],
2603 'friendica_parent_uri' => $item['parent-uri'],
2606 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2607 unset($ret["sender"]["uid"]);
2608 unset($ret["sender"]["self"]);
2609 unset($ret["recipient"]["uid"]);
2610 unset($ret["recipient"]["self"]);
2612 //don't send title to regular StatusNET requests to avoid confusing these apps
2613 if (x($_GET, 'getText')) {
2614 $ret['title'] = $item['title'];
2615 if ($_GET['getText'] == 'html') {
2616 $ret['text'] = bbcode($item['body'], false, false);
2617 } elseif ($_GET['getText'] == 'plain') {
2618 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2619 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2622 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2624 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2625 unset($ret['sender']);
2626 unset($ret['recipient']);
2634 * @param array $item
2638 function api_convert_item($item)
2640 $body = $item['body'];
2641 $attachments = api_get_attachments($body);
2643 // Workaround for ostatus messages where the title is identically to the body
2644 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2645 $statusbody = trim(html2plain($html, 0));
2647 // handle data: images
2648 $statusbody = api_format_items_embeded_images($item, $statusbody);
2650 $statustitle = trim($item['title']);
2652 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2653 $statustext = trim($statusbody);
2655 $statustext = trim($statustitle."\n\n".$statusbody);
2658 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2659 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2662 $statushtml = trim(bbcode($body, false, false));
2664 // Workaround for clients with limited HTML parser functionality
2665 $search = array("<br>", "<blockquote>", "</blockquote>",
2666 "<h1>", "</h1>", "<h2>", "</h2>",
2667 "<h3>", "</h3>", "<h4>", "</h4>",
2668 "<h5>", "</h5>", "<h6>", "</h6>");
2669 $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2670 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2671 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2672 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2673 $statushtml = str_replace($search, $replace, $statushtml);
2675 if ($item['title'] != "") {
2676 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2680 $oldtext = $statushtml;
2681 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2682 } while ($oldtext != $statushtml);
2684 if (substr($statushtml, 0, 4) == '<br>') {
2685 $statushtml = substr($statushtml, 4);
2688 if (substr($statushtml, 0, -4) == '<br>') {
2689 $statushtml = substr($statushtml, -4);
2692 // feeds without body should contain the link
2693 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2694 $statushtml .= bbcode($item['plink']);
2697 $entities = api_get_entitities($statustext, $body);
2700 "text" => $statustext,
2701 "html" => $statushtml,
2702 "attachments" => $attachments,
2703 "entities" => $entities
2709 * @param string $body
2711 * @return array|false
2713 function api_get_attachments(&$body)
2716 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2718 $URLSearchString = "^\[\]";
2719 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2725 $attachments = array();
2727 foreach ($images[1] as $image) {
2728 $imagedata = Image::getInfoFromURL($image);
2731 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2735 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2736 foreach ($images[0] as $orig) {
2737 $body = str_replace($orig, "", $body);
2741 return $attachments;
2746 * @param string $text
2747 * @param string $bbcode
2750 * @todo Links at the first character of the post
2752 function api_get_entitities(&$text, $bbcode)
2756 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2758 if ($include_entities != "true") {
2759 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2761 foreach ($images[1] as $image) {
2762 $replace = proxy_url($image);
2763 $text = str_replace($image, $replace, $text);
2768 $bbcode = bb_CleanPictureLinks($bbcode);
2770 // Change pure links in text to bbcode uris
2771 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2773 $entities = array();
2774 $entities["hashtags"] = array();
2775 $entities["symbols"] = array();
2776 $entities["urls"] = array();
2777 $entities["user_mentions"] = array();
2779 $URLSearchString = "^\[\]";
2781 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2783 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2784 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2785 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2787 $bbcode = preg_replace(
2788 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2789 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2792 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2794 $bbcode = preg_replace(
2795 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2796 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2799 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2801 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2803 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2804 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2806 $ordered_urls = array();
2807 foreach ($urls[1] as $id => $url) {
2808 //$start = strpos($text, $url, $offset);
2809 $start = iconv_strpos($text, $url, 0, "UTF-8");
2810 if (!($start === false)) {
2811 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2815 ksort($ordered_urls);
2818 //foreach ($urls[1] AS $id=>$url) {
2819 foreach ($ordered_urls as $url) {
2820 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2821 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2823 $display_url = $url["title"];
2825 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2826 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2828 if (strlen($display_url) > 26) {
2829 $display_url = substr($display_url, 0, 25)."…";
2833 //$start = strpos($text, $url, $offset);
2834 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2835 if (!($start === false)) {
2836 $entities["urls"][] = array("url" => $url["url"],
2837 "expanded_url" => $url["url"],
2838 "display_url" => $display_url,
2839 "indices" => array($start, $start+strlen($url["url"])));
2840 $offset = $start + 1;
2844 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2845 $ordered_images = array();
2846 foreach ($images[1] as $image) {
2847 //$start = strpos($text, $url, $offset);
2848 $start = iconv_strpos($text, $image, 0, "UTF-8");
2849 if (!($start === false)) {
2850 $ordered_images[$start] = $image;
2853 //$entities["media"] = array();
2856 foreach ($ordered_images as $url) {
2857 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2858 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2860 if (strlen($display_url) > 26) {
2861 $display_url = substr($display_url, 0, 25)."…";
2864 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2865 if (!($start === false)) {
2866 $image = Image::getInfoFromURL($url);
2868 // If image cache is activated, then use the following sizes:
2869 // thumb (150), small (340), medium (600) and large (1024)
2870 if (!Config::get("system", "proxy_disabled")) {
2871 $media_url = proxy_url($url);
2874 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2875 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2877 if (($image[0] > 150) || ($image[1] > 150)) {
2878 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2879 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2882 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2883 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2885 if (($image[0] > 600) || ($image[1] > 600)) {
2886 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2887 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2891 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2894 $entities["media"][] = array(
2896 "id_str" => (string)$start+1,
2897 "indices" => array($start, $start+strlen($url)),
2898 "media_url" => normalise_link($media_url),
2899 "media_url_https" => $media_url,
2901 "display_url" => $display_url,
2902 "expanded_url" => $url,
2906 $offset = $start + 1;
2915 * @param array $item
2916 * @param string $text
2920 function api_format_items_embeded_images(&$item, $text)
2922 $text = preg_replace_callback(
2923 "|data:image/([^;]+)[^=]+=*|m",
2924 function ($match) use ($item) {
2925 return System::baseUrl()."/display/".$item['guid'];
2934 * @brief return <a href='url'>name</a> as array
2936 * @param string $txt text
2941 function api_contactlink_to_array($txt)
2944 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2945 if ($r && count($match)==3) {
2947 'name' => $match[2],
2961 * @brief return likes, dislikes and attend status for item
2963 * @param array $item array
2964 * @param string $type Return type (atom, rss, xml, json)
2967 * likes => int count,
2968 * dislikes => int count
2970 function api_format_items_activities(&$item, $type = "json")
2974 $activities = array(
2976 'dislike' => array(),
2977 'attendyes' => array(),
2978 'attendno' => array(),
2979 'attendmaybe' => array(),
2984 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2985 intval($item['uid']),
2989 foreach ($items as $i) {
2990 // not used as result should be structured like other user data
2991 //builtin_activity_puller($i, $activities);
2993 // get user data and add it to the array of the activity
2994 $user = api_get_user($a, $i['author-link']);
2995 switch ($i['verb']) {
2997 $activities['like'][] = $user;
2999 case ACTIVITY_DISLIKE:
3000 $activities['dislike'][] = $user;
3002 case ACTIVITY_ATTEND:
3003 $activities['attendyes'][] = $user;
3005 case ACTIVITY_ATTENDNO:
3006 $activities['attendno'][] = $user;
3008 case ACTIVITY_ATTENDMAYBE:
3009 $activities['attendmaybe'][] = $user;
3016 if ($type == "xml") {
3017 $xml_activities = array();
3018 foreach ($activities as $k => $v) {
3019 // change xml element from "like" to "friendica:like"
3020 $xml_activities["friendica:".$k] = $v;
3021 // add user data into xml output
3023 foreach ($v as $user) {
3024 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
3027 $activities = $xml_activities;
3035 * @brief return data from profiles
3037 * @param array $profile array containing data from db table 'profile'
3038 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3041 function api_format_items_profiles(&$profile = null, $type = "json")
3043 if ($profile != null) {
3044 $profile = array('profile_id' => $profile['id'],
3045 'profile_name' => $profile['profile-name'],
3046 'is_default' => $profile['is-default'] ? true : false,
3047 'hide_friends'=> $profile['hide-friends'] ? true : false,
3048 'profile_photo' => $profile['photo'],
3049 'profile_thumb' => $profile['thumb'],
3050 'publish' => $profile['publish'] ? true : false,
3051 'net_publish' => $profile['net-publish'] ? true : false,
3052 'description' => $profile['pdesc'],
3053 'date_of_birth' => $profile['dob'],
3054 'address' => $profile['address'],
3055 'city' => $profile['locality'],
3056 'region' => $profile['region'],
3057 'postal_code' => $profile['postal-code'],
3058 'country' => $profile['country-name'],
3059 'hometown' => $profile['hometown'],
3060 'gender' => $profile['gender'],
3061 'marital' => $profile['marital'],
3062 'marital_with' => $profile['with'],
3063 'marital_since' => $profile['howlong'],
3064 'sexual' => $profile['sexual'],
3065 'politic' => $profile['politic'],
3066 'religion' => $profile['religion'],
3067 'public_keywords' => $profile['pub_keywords'],
3068 'private_keywords' => $profile['prv_keywords'],
3069 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
3070 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
3071 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
3072 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
3073 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
3074 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
3075 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
3076 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
3077 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
3078 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
3079 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
3080 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
3081 'homepage' => $profile['homepage'],
3088 * @brief format items to be returned by api
3090 * @param array $r array of items
3091 * @param array $user_info
3092 * @param bool $filter_user filter items by $user_info
3093 * @param string $type Return type (atom, rss, xml, json)
3095 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
3101 foreach ($r as $item) {
3102 localize_item($item);
3103 list($status_user, $owner_user) = api_item_get_user($a, $item);
3105 // Look if the posts are matching if they should be filtered by user id
3106 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3110 $in_reply_to = api_in_reply_to($item);
3112 $converted = api_convert_item($item);
3114 if ($type == "xml") {
3115 $geo = "georss:point";
3121 'text' => $converted["text"],
3122 'truncated' => false,
3123 'created_at'=> api_date($item['created']),
3124 'in_reply_to_status_id' => $in_reply_to['status_id'],
3125 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3126 'source' => (($item['app']) ? $item['app'] : 'web'),
3127 'id' => intval($item['id']),
3128 'id_str' => (string) intval($item['id']),
3129 'in_reply_to_user_id' => $in_reply_to['user_id'],
3130 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3131 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3133 'favorited' => $item['starred'] ? true : false,
3134 'user' => $status_user ,
3135 'friendica_owner' => $owner_user,
3136 //'entities' => NULL,
3137 'statusnet_html' => $converted["html"],
3138 'statusnet_conversation_id' => $item['parent'],
3139 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3140 'friendica_activities' => api_format_items_activities($item, $type),
3143 if (count($converted["attachments"]) > 0) {
3144 $status["attachments"] = $converted["attachments"];
3147 if (count($converted["entities"]) > 0) {
3148 $status["entities"] = $converted["entities"];
3151 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
3152 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
3153 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
3154 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
3158 // Retweets are only valid for top postings
3159 // It doesn't work reliable with the link if its a feed
3160 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
3162 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
3165 if ($item["id"] == $item["parent"]) {
3166 $retweeted_item = api_share_as_retweet($item);
3167 if ($retweeted_item !== false) {
3168 $retweeted_status = $status;
3170 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
3171 } catch (BadRequestException $e) {
3172 // user not found. should be found?
3173 /// @todo check if the user should be always found
3174 $retweeted_status["user"] = array();
3177 $rt_converted = api_convert_item($retweeted_item);
3179 $retweeted_status['text'] = $rt_converted["text"];
3180 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3181 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3182 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3183 $status['retweeted_status'] = $retweeted_status;
3187 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3188 unset($status["user"]["uid"]);
3189 unset($status["user"]["self"]);
3191 if ($item["coord"] != "") {
3192 $coords = explode(' ', $item["coord"]);
3193 if (count($coords) == 2) {
3194 if ($type == "json") {
3195 $status["geo"] = array('type' => 'Point',
3196 'coordinates' => array((float) $coords[0],
3197 (float) $coords[1]));
3198 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3199 $status["georss:point"] = $item["coord"];
3209 * Returns the remaining number of API requests available to the user before the API limit is reached.
3211 * @param string $type Return type (atom, rss, xml, json)
3213 * @return array|string
3215 function api_account_rate_limit_status($type)
3217 if ($type == "xml") {
3219 'remaining-hits' => '150',
3220 '@attributes' => array("type" => "integer"),
3221 'hourly-limit' => '150',
3222 '@attributes2' => array("type" => "integer"),
3223 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
3224 '@attributes3' => array("type" => "datetime"),
3225 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3226 '@attributes4' => array("type" => "integer"),
3230 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3231 'remaining_hits' => '150',
3232 'hourly_limit' => '150',
3233 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
3237 return api_format_data('hash', $type, array('hash' => $hash));
3240 /// @TODO move to top of file or somewhere better
3241 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3244 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3246 * @param string $type Return type (atom, rss, xml, json)
3248 * @return array|string
3250 function api_help_test($type)
3252 if ($type == 'xml') {
3258 return api_format_data('ok', $type, array("ok" => $ok));
3261 /// @TODO move to top of file or somewhere better
3262 api_register_func('api/help/test', 'api_help_test', false);
3266 * @param string $type Return type (atom, rss, xml, json)
3268 * @return array|string
3270 function api_lists($type)
3273 /// @TODO $ret is not filled here?
3274 return api_format_data('lists', $type, array("lists_list" => $ret));
3277 /// @TODO move to top of file or somewhere better
3278 api_register_func('api/lists', 'api_lists', true);
3281 * Returns all lists the user subscribes to.
3283 * @param string $type Return type (atom, rss, xml, json)
3285 * @return array|string
3286 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3288 function api_lists_list($type)
3291 /// @TODO $ret is not filled here?
3292 return api_format_data('lists', $type, array("lists_list" => $ret));
3295 /// @TODO move to top of file or somewhere better
3296 api_register_func('api/lists/list', 'api_lists_list', true);
3299 * Considers friends and followers lists to be private and won't return
3300 * anything if any user_id parameter is passed.
3302 * @brief Returns either the friends of the follower list
3304 * @param string $qtype Either "friends" or "followers"
3305 * @return boolean|array
3306 * @throws ForbiddenException
3308 function api_statuses_f($qtype)
3312 if (api_user() === false) {
3313 throw new ForbiddenException();
3317 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3318 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3322 $start = ($page - 1) * $count;
3324 $user_info = api_get_user($a);
3326 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3327 /* this is to stop Hotot to load friends multiple times
3328 * I'm not sure if I'm missing return something or
3329 * is a bug in hotot. Workaround, meantime
3333 return array('$users' => $ret);*/
3338 if ($qtype == 'friends') {
3339 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3340 } elseif ($qtype == 'followers') {
3341 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3344 // friends and followers only for self
3345 if ($user_info['self'] == 0) {
3346 $sql_extra = " AND false ";
3349 if ($qtype == 'blocks') {
3350 $sql_filter = 'AND `blocked` AND NOT `pending`';
3351 } elseif ($qtype == 'incoming') {
3352 $sql_filter = 'AND `pending`';
3354 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3372 foreach ($r as $cid) {
3373 $user = api_get_user($a, $cid['nurl']);
3374 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3375 unset($user["uid"]);
3376 unset($user["self"]);
3383 return array('user' => $ret);
3388 * Returns the user's friends.
3390 * @brief Returns the list of friends of the provided user
3392 * @deprecated By Twitter API in favor of friends/list
3394 * @param string $type Either "json" or "xml"
3395 * @return boolean|string|array
3397 function api_statuses_friends($type)
3399 $data = api_statuses_f("friends");
3400 if ($data === false) {
3403 return api_format_data("users", $type, $data);
3407 * Returns the user's followers.
3409 * @brief Returns the list of followers of the provided user
3411 * @deprecated By Twitter API in favor of friends/list
3413 * @param string $type Either "json" or "xml"
3414 * @return boolean|string|array
3416 function api_statuses_followers($type)
3418 $data = api_statuses_f("followers");
3419 if ($data === false) {
3422 return api_format_data("users", $type, $data);
3425 /// @TODO move to top of file or somewhere better
3426 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3427 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3430 * Returns the list of blocked users
3432 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3434 * @param string $type Either "json" or "xml"
3436 * @return boolean|string|array
3438 function api_blocks_list($type)
3440 $data = api_statuses_f('blocks');
3441 if ($data === false) {
3444 return api_format_data("users", $type, $data);
3447 /// @TODO move to top of file or somewhere better
3448 api_register_func('api/blocks/list', 'api_blocks_list', true);
3451 * Returns the list of pending users IDs
3453 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3455 * @param string $type Either "json" or "xml"
3457 * @return boolean|string|array
3459 function api_friendships_incoming($type)
3461 $data = api_statuses_f('incoming');
3462 if ($data === false) {
3467 foreach ($data['user'] as $user) {
3468 $ids[] = $user['id'];
3471 return api_format_data("ids", $type, array('id' => $ids));
3474 /// @TODO move to top of file or somewhere better
3475 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3478 * Returns the instance's configuration information.
3480 * @param string $type Return type (atom, rss, xml, json)
3482 * @return array|string
3484 function api_statusnet_config($type)
3488 $name = $a->config['sitename'];
3489 $server = $a->get_hostname();
3490 $logo = System::baseUrl() . '/images/friendica-64.png';
3491 $email = $a->config['admin_email'];
3492 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3493 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3494 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3495 if ($a->config['api_import_size']) {
3496 $textlimit = (string) $a->config['api_import_size'];
3498 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3499 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3502 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3503 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3504 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3505 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3506 'shorturllength' => '30',
3507 'friendica' => array(
3508 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3509 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3510 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3511 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3516 return api_format_data('config', $type, array('config' => $config));
3519 /// @TODO move to top of file or somewhere better
3520 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3521 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3525 * @param string $type Return type (atom, rss, xml, json)
3527 * @return array|string
3529 function api_statusnet_version($type)
3532 $fake_statusnet_version = "0.9.7";
3534 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
3537 /// @TODO move to top of file or somewhere better
3538 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3539 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3543 * @param string $type Return type (atom, rss, xml, json)
3544 * @param string $qtype
3546 * @todo use api_format_data() to return data
3548 function api_ff_ids($type, $qtype)
3553 throw new ForbiddenException();
3556 $user_info = api_get_user($a);
3558 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3561 "SELECT `pcontact`.`id` FROM `contact`
3562 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3563 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3567 if (!DBM::is_result($r)) {
3572 foreach ($r as $rr) {
3573 if ($stringify_ids) {
3576 $ids[] = intval($rr['id']);
3580 return api_format_data("ids", $type, array('id' => $ids));
3584 * Returns the ID of every user the user is following.
3586 * @param string $type Return type (atom, rss, xml, json)
3588 * @return array|string
3589 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3591 function api_friends_ids($type)
3593 return api_ff_ids($type, 'friends');
3597 * Returns the ID of every user following the user.
3599 * @param string $type Return type (atom, rss, xml, json)
3601 * @return array|string
3602 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3604 function api_followers_ids($type)
3606 return api_ff_ids($type, 'followers');
3609 /// @TODO move to top of file or somewhere better
3610 api_register_func('api/friends/ids', 'api_friends_ids', true);
3611 api_register_func('api/followers/ids', 'api_followers_ids', true);
3614 * Sends a new direct message.
3616 * @param string $type Return type (atom, rss, xml, json)
3618 * @return array|string
3619 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3621 function api_direct_messages_new($type)
3626 if (api_user() === false) {
3627 throw new ForbiddenException();
3630 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3634 $sender = api_get_user($a);
3636 if ($_POST['screen_name']) {
3638 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3640 dbesc($_POST['screen_name'])
3643 // Selecting the id by priority, friendica first
3644 api_best_nickname($r);
3646 $recipient = api_get_user($a, $r[0]['nurl']);
3648 $recipient = api_get_user($a, $_POST['user_id']);
3653 if (x($_REQUEST, 'replyto')) {
3655 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3657 intval($_REQUEST['replyto'])
3659 $replyto = $r[0]['parent-uri'];
3660 $sub = $r[0]['title'];
3662 if (x($_REQUEST, 'title')) {
3663 $sub = $_REQUEST['title'];
3665 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3669 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3672 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3673 $ret = api_format_messages($r[0], $recipient, $sender);
3675 $ret = array("error"=>$id);
3678 $data = array('direct_message'=>$ret);
3683 $data = api_rss_extra($a, $data, $user_info);
3686 return api_format_data("direct-messages", $type, $data);
3689 /// @TODO move to top of file or somewhere better
3690 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3693 * Destroys a direct message.
3695 * @brief delete a direct_message from mail table through api
3697 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3699 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3701 function api_direct_messages_destroy($type)
3705 if (api_user() === false) {
3706 throw new ForbiddenException();
3710 $user_info = api_get_user($a);
3712 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3714 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3715 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3716 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3718 $uid = $user_info['uid'];
3719 // error if no id or parenturi specified (for clients posting parent-uri as well)
3720 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3721 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3722 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3725 // BadRequestException if no id specified (for clients using Twitter API)
3727 throw new BadRequestException('Message id not specified');
3730 // add parent-uri to sql command if specified by calling app
3731 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3733 // get data of the specified message id
3735 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3740 // error message if specified id is not in database
3741 if (!DBM::is_result($r)) {
3742 if ($verbose == "true") {
3743 $answer = array('result' => 'error', 'message' => 'message id not in database');
3744 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3746 /// @todo BadRequestException ok for Twitter API clients?
3747 throw new BadRequestException('message id not in database');
3752 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3757 if ($verbose == "true") {
3760 $answer = array('result' => 'ok', 'message' => 'message deleted');
3761 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3763 $answer = array('result' => 'error', 'message' => 'unknown error');
3764 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3767 /// @todo return JSON data like Twitter API not yet implemented
3770 /// @TODO move to top of file or somewhere better
3771 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3775 * @param string $type Return type (atom, rss, xml, json)
3776 * @param string $box
3777 * @param string $verbose
3779 * @return array|string
3781 function api_direct_messages_box($type, $box, $verbose)
3785 if (api_user() === false) {
3786 throw new ForbiddenException();
3790 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3791 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3796 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3797 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3799 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3800 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3803 unset($_REQUEST["user_id"]);
3804 unset($_GET["user_id"]);
3806 unset($_REQUEST["screen_name"]);
3807 unset($_GET["screen_name"]);
3809 $user_info = api_get_user($a);
3810 $profile_url = $user_info["url"];
3813 $start = $page * $count;
3816 if ($box=="sentbox") {
3817 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3818 } elseif ($box == "conversation") {
3819 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3820 } elseif ($box == "all") {
3821 $sql_extra = "true";
3822 } elseif ($box == "inbox") {
3823 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3827 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3830 if ($user_id != "") {
3831 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3832 } elseif ($screen_name !="") {
3833 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3837 "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",
3843 if ($verbose == "true" && !DBM::is_result($r)) {
3844 $answer = array('result' => 'error', 'message' => 'no mails available');
3845 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3849 foreach ($r as $item) {
3850 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3851 $recipient = $user_info;
3852 $sender = api_get_user($a, normalise_link($item['contact-url']));
3853 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3854 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3855 $sender = $user_info;
3858 $ret[] = api_format_messages($item, $recipient, $sender);
3862 $data = array('direct_message' => $ret);
3866 $data = api_rss_extra($a, $data, $user_info);
3869 return api_format_data("direct-messages", $type, $data);
3873 * Returns the most recent direct messages sent by the user.
3875 * @param string $type Return type (atom, rss, xml, json)
3877 * @return array|string
3878 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3880 function api_direct_messages_sentbox($type)
3882 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3883 return api_direct_messages_box($type, "sentbox", $verbose);
3887 * Returns the most recent direct messages sent to the user.
3889 * @param string $type Return type (atom, rss, xml, json)
3891 * @return array|string
3892 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3894 function api_direct_messages_inbox($type)
3896 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3897 return api_direct_messages_box($type, "inbox", $verbose);
3902 * @param string $type Return type (atom, rss, xml, json)
3904 * @return array|string
3906 function api_direct_messages_all($type)
3908 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3909 return api_direct_messages_box($type, "all", $verbose);
3914 * @param string $type Return type (atom, rss, xml, json)
3916 * @return array|string
3918 function api_direct_messages_conversation($type)
3920 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3921 return api_direct_messages_box($type, "conversation", $verbose);
3924 /// @TODO move to top of file or somewhere better
3925 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3926 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3927 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3928 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3931 * Returns an OAuth Request Token.
3933 * @param string $type Return type (atom, rss, xml, json)
3934 * @see https://oauth.net/core/1.0/#auth_step1
3936 function api_oauth_request_token($type)
3938 $oauth1 = new FKOAuth1();
3940 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3941 } catch (Exception $e) {
3942 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3950 * Returns an OAuth Access Token.
3952 * @param string $type Return type (atom, rss, xml, json)
3954 * @return array|string
3955 * @see https://oauth.net/core/1.0/#auth_step3
3957 function api_oauth_access_token($type)
3959 $oauth1 = new FKOAuth1();
3961 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3962 } catch (Exception $e) {
3963 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3970 /// @TODO move to top of file or somewhere better
3971 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3972 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3976 * @brief delete a complete photoalbum with all containing photos from database through api
3978 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3981 function api_fr_photoalbum_delete($type)
3983 if (api_user() === false) {
3984 throw new ForbiddenException();
3987 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3989 // we do not allow calls without album string
3991 throw new BadRequestException("no albumname specified");
3993 // check if album is existing
3995 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3999 if (!DBM::is_result($r)) {
4000 throw new BadRequestException("album not available");
4003 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4004 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4005 foreach ($r as $rr) {
4007 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4008 intval(local_user()),
4009 dbesc($rr['resource-id'])
4012 if (!DBM::is_result($photo_item)) {
4013 throw new InternalServerErrorException("problem with deleting items occured");
4015 drop_item($photo_item[0]['id'], false);
4018 // now let's delete all photos from the album
4019 $result = dba::delete('photo', array('uid' => api_user(), 'album' => $album));
4021 // return success of deletion or error message
4023 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
4024 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
4026 throw new InternalServerErrorException("unknown error - deleting from database failed");
4031 * @brief update the name of the album for all photos of an album
4033 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4036 function api_fr_photoalbum_update($type)
4038 if (api_user() === false) {
4039 throw new ForbiddenException();
4042 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
4043 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
4045 // we do not allow calls without album string
4047 throw new BadRequestException("no albumname specified");
4049 if ($album_new == "") {
4050 throw new BadRequestException("no new albumname specified");
4052 // check if album is existing
4054 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4058 if (!DBM::is_result($r)) {
4059 throw new BadRequestException("album not available");
4061 // now let's update all photos to the albumname
4063 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
4069 // return success of updating or error message
4071 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
4072 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
4074 throw new InternalServerErrorException("unknown error - updating in database failed");
4080 * @brief list all photos of the authenticated user
4082 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4085 function api_fr_photos_list($type)
4087 if (api_user() === false) {
4088 throw new ForbiddenException();
4091 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4092 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4093 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4094 intval(local_user())
4097 'image/jpeg' => 'jpg',
4098 'image/png' => 'png',
4099 'image/gif' => 'gif'
4101 $data = array('photo'=>array());
4102 if (DBM::is_result($r)) {
4103 foreach ($r as $rr) {
4105 $photo['id'] = $rr['resource-id'];
4106 $photo['album'] = $rr['album'];
4107 $photo['filename'] = $rr['filename'];
4108 $photo['type'] = $rr['type'];
4109 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4110 $photo['created'] = $rr['created'];
4111 $photo['edited'] = $rr['edited'];
4112 $photo['desc'] = $rr['desc'];
4114 if ($type == "xml") {
4115 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
4117 $photo['thumb'] = $thumb;
4118 $data['photo'][] = $photo;
4122 return api_format_data("photos", $type, $data);
4126 * @brief upload a new photo or change an existing photo
4128 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4131 function api_fr_photo_create_update($type)
4133 if (api_user() === false) {
4134 throw new ForbiddenException();
4137 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4138 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4139 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4140 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4141 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4142 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4143 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4144 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4145 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4147 // do several checks on input parameters
4148 // we do not allow calls without album string
4149 if ($album == null) {
4150 throw new BadRequestException("no albumname specified");
4152 // if photo_id == null --> we are uploading a new photo
4153 if ($photo_id == null) {
4156 // error if no media posted in create-mode
4157 if (!x($_FILES, 'media')) {
4159 throw new BadRequestException("no media data submitted");
4162 // album_new will be ignored in create-mode
4167 // check if photo is existing in database
4169 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4174 if (!DBM::is_result($r)) {
4175 throw new BadRequestException("photo not available");
4179 // checks on acl strings provided by clients
4180 $acl_input_error = false;
4181 $acl_input_error |= check_acl_input($allow_cid);
4182 $acl_input_error |= check_acl_input($deny_cid);
4183 $acl_input_error |= check_acl_input($allow_gid);
4184 $acl_input_error |= check_acl_input($deny_gid);
4185 if ($acl_input_error) {
4186 throw new BadRequestException("acl data invalid");
4188 // now let's upload the new media in create-mode
4189 if ($mode == "create") {
4190 $media = $_FILES['media'];
4191 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4193 // return success of updating or error message
4194 if (!is_null($data)) {
4195 return api_format_data("photo_create", $type, $data);
4197 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4201 // now let's do the changes in update-mode
4202 if ($mode == "update") {
4205 if (!is_null($desc)) {
4206 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4209 if (!is_null($album_new)) {
4210 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4213 if (!is_null($allow_cid)) {
4214 $allow_cid = trim($allow_cid);
4215 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4218 if (!is_null($deny_cid)) {
4219 $deny_cid = trim($deny_cid);
4220 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4223 if (!is_null($allow_gid)) {
4224 $allow_gid = trim($allow_gid);
4225 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4228 if (!is_null($deny_gid)) {
4229 $deny_gid = trim($deny_gid);
4230 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4234 if ($sql_extra != "") {
4235 $nothingtodo = false;
4237 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4239 datetime_convert(), // update edited timestamp
4245 $nothingtodo = true;
4248 if (x($_FILES, 'media')) {
4249 $nothingtodo = false;
4250 $media = $_FILES['media'];
4251 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4252 if (!is_null($data)) {
4253 return api_format_data("photo_update", $type, $data);
4257 // return success of updating or error message
4259 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
4260 return api_format_data("photo_update", $type, array('$result' => $answer));
4263 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
4264 return api_format_data("photo_update", $type, array('$result' => $answer));
4266 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4269 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4274 * @brief delete a single photo from the database through api
4276 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4279 function api_fr_photo_delete($type)
4281 if (api_user() === false) {
4282 throw new ForbiddenException();
4285 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4287 // do several checks on input parameters
4288 // we do not allow calls without photo id
4289 if ($photo_id == null) {
4290 throw new BadRequestException("no photo_id specified");
4292 // check if photo is existing in database
4294 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4298 if (!DBM::is_result($r)) {
4299 throw new BadRequestException("photo not available");
4301 // now we can perform on the deletion of the photo
4302 $result = dba::delete('photo', array('uid' => api_user(), 'resource-id' => $photo_id));
4304 // return success of deletion or error message
4306 // retrieve the id of the parent element (the photo element)
4308 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4309 intval(local_user()),
4313 if (!DBM::is_result($photo_item)) {
4314 throw new InternalServerErrorException("problem with deleting items occured");
4316 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4317 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4318 drop_item($photo_item[0]['id'], false);
4320 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
4321 return api_format_data("photo_delete", $type, array('$result' => $answer));
4323 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4329 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4331 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4332 * @return string|array
4334 function api_fr_photo_detail($type)
4336 if (api_user() === false) {
4337 throw new ForbiddenException();
4339 if (!x($_REQUEST, 'photo_id')) {
4340 throw new BadRequestException("No photo id.");
4343 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4344 $photo_id = $_REQUEST['photo_id'];
4346 // prepare json/xml output with data from database for the requested photo
4347 $data = prepare_photo_data($type, $scale, $photo_id);
4349 return api_format_data("photo_detail", $type, $data);
4354 * Updates the user’s profile image.
4356 * @brief updates the profile image for the user (either a specified profile or the default profile)
4358 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4361 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4363 function api_account_update_profile_image($type)
4365 if (api_user() === false) {
4366 throw new ForbiddenException();
4369 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
4371 // error if image data is missing
4372 if (!x($_FILES, 'image')) {
4373 throw new BadRequestException("no media data submitted");
4376 // check if specified profile id is valid
4377 if ($profileid != 0) {
4379 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4383 // error message if specified profile id is not in database
4384 if (!DBM::is_result($r)) {
4385 throw new BadRequestException("profile_id not available");
4387 $is_default_profile = $r['profile'];
4389 $is_default_profile = 1;
4392 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4394 if (x($_FILES, 'image')) {
4395 $media = $_FILES['image'];
4396 } elseif (x($_FILES, 'media')) {
4397 $media = $_FILES['media'];
4399 // save new profile image
4400 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4403 if (is_array($media['type'])) {
4404 $filetype = $media['type'][0];
4406 $filetype = $media['type'];
4408 if ($filetype == "image/jpeg") {
4410 } elseif ($filetype == "image/png") {
4413 // change specified profile or all profiles to the new resource-id
4414 if ($is_default_profile) {
4416 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4417 dbesc($data['photo']['id']),
4418 intval(local_user())
4422 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
4423 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4424 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4425 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4426 intval(local_user())
4430 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4431 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4432 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4433 intval($_REQUEST['profile']),
4434 intval(local_user())
4438 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4439 // so that browsers will do a cache update unconditionally
4442 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4443 dbesc(datetime_convert()),
4444 intval(local_user())
4447 // Update global directory in background
4448 //$user = api_get_user(get_app());
4449 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4450 if ($url && strlen(Config::get('system', 'directory'))) {
4451 Worker::add(PRIORITY_LOW, "Directory", $url);
4454 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4456 // output for client
4458 return api_account_verify_credentials($type);
4460 // SaveMediaToDatabase failed for some reason
4461 throw new InternalServerErrorException("image upload failed");
4465 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4466 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4467 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4468 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4469 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4470 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4471 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4472 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4473 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4476 * Update user profile
4478 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4480 * @return array|string
4482 function api_account_update_profile($type)
4484 $local_user = api_user();
4485 $api_user = api_get_user(get_app());
4487 if (!empty($_POST['name'])) {
4488 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4489 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4490 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4491 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4494 if (isset($_POST['description'])) {
4495 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4496 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4497 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4500 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4501 // Update global directory in background
4502 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4503 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4506 return api_account_verify_credentials($type);
4509 /// @TODO move to top of file or somewhere better
4510 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4514 * @param string $acl_string
4516 function check_acl_input($acl_string)
4518 if ($acl_string == null || $acl_string == " ") {
4521 $contact_not_found = false;
4523 // split <x><y><z> into array of cid's
4524 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4526 // check for each cid if it is available on server
4527 $cid_array = $array[0];
4528 foreach ($cid_array as $cid) {
4529 $cid = str_replace("<", "", $cid);
4530 $cid = str_replace(">", "", $cid);
4532 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4536 $contact_not_found |= !DBM::is_result($contact);
4538 return $contact_not_found;
4543 * @param string $mediatype
4544 * @param array $media
4545 * @param string $type
4546 * @param string $album
4547 * @param string $allow_cid
4548 * @param string $deny_cid
4549 * @param string $allow_gid
4550 * @param string $deny_gid
4551 * @param string $desc
4552 * @param integer $profile
4553 * @param boolean $visibility
4554 * @param string $photo_id
4556 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)
4564 if (is_array($media)) {
4565 if (is_array($media['tmp_name'])) {
4566 $src = $media['tmp_name'][0];
4568 $src = $media['tmp_name'];
4570 if (is_array($media['name'])) {
4571 $filename = basename($media['name'][0]);
4573 $filename = basename($media['name']);
4575 if (is_array($media['size'])) {
4576 $filesize = intval($media['size'][0]);
4578 $filesize = intval($media['size']);
4580 if (is_array($media['type'])) {
4581 $filetype = $media['type'][0];
4583 $filetype = $media['type'];
4587 if ($filetype == "") {
4588 $filetype=Image::guessType($filename);
4590 $imagedata = getimagesize($src);
4592 $filetype = $imagedata['mime'];
4595 "File upload src: " . $src . " - filename: " . $filename .
4596 " - size: " . $filesize . " - type: " . $filetype,
4600 // check if there was a php upload error
4601 if ($filesize == 0 && $media['error'] == 1) {
4602 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4604 // check against max upload size within Friendica instance
4605 $maximagesize = Config::get('system', 'maximagesize');
4606 if ($maximagesize && ($filesize > $maximagesize)) {
4607 $formattedBytes = formatBytes($maximagesize);
4608 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4611 // create Photo instance with the data of the image
4612 $imagedata = @file_get_contents($src);
4613 $Image = new Image($imagedata, $filetype);
4614 if (! $Image->isValid()) {
4615 throw new InternalServerErrorException("unable to process image data");
4618 // check orientation of image
4619 $Image->orient($src);
4622 // check max length of images on server
4623 $max_length = Config::get('system', 'max_image_length');
4624 if (! $max_length) {
4625 $max_length = MAX_IMAGE_LENGTH;
4627 if ($max_length > 0) {
4628 $Image->scaleDown($max_length);
4629 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4631 $width = $Image->getWidth();
4632 $height = $Image->getHeight();
4634 // create a new resource-id if not already provided
4635 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
4637 if ($mediatype == "photo") {
4638 // upload normal image (scales 0, 1, 2)
4639 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4641 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4643 logger("photo upload: image upload with scale 0 (original size) failed");
4645 if ($width > 640 || $height > 640) {
4646 $Image->scaleDown(640);
4647 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4649 logger("photo upload: image upload with scale 1 (640x640) failed");
4653 if ($width > 320 || $height > 320) {
4654 $Image->scaleDown(320);
4655 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4657 logger("photo upload: image upload with scale 2 (320x320) failed");
4660 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4661 } elseif ($mediatype == "profileimage") {
4662 // upload profile image (scales 4, 5, 6)
4663 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4665 if ($width > 175 || $height > 175) {
4666 $Image->scaleDown(175);
4667 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4669 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4673 if ($width > 80 || $height > 80) {
4674 $Image->scaleDown(80);
4675 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4677 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4681 if ($width > 48 || $height > 48) {
4682 $Image->scaleDown(48);
4683 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4685 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4688 $Image->__destruct();
4689 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4693 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4694 if ($photo_id == null && $mediatype == "photo") {
4695 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4697 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4698 return prepare_photo_data($type, false, $hash);
4700 throw new InternalServerErrorException("image upload failed");
4706 * @param string $hash
4707 * @param string $allow_cid
4708 * @param string $deny_cid
4709 * @param string $allow_gid
4710 * @param string $deny_gid
4711 * @param string $filetype
4712 * @param boolean $visibility
4714 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4716 // get data about the api authenticated user
4717 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4718 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4721 $arr['guid'] = get_guid(32);
4722 $arr['uid'] = intval(api_user());
4724 $arr['parent-uri'] = $uri;
4725 $arr['type'] = 'photo';
4727 $arr['resource-id'] = $hash;
4728 $arr['contact-id'] = $owner_record[0]['id'];
4729 $arr['owner-name'] = $owner_record[0]['name'];
4730 $arr['owner-link'] = $owner_record[0]['url'];
4731 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4732 $arr['author-name'] = $owner_record[0]['name'];
4733 $arr['author-link'] = $owner_record[0]['url'];
4734 $arr['author-avatar'] = $owner_record[0]['thumb'];
4736 $arr['allow_cid'] = $allow_cid;
4737 $arr['allow_gid'] = $allow_gid;
4738 $arr['deny_cid'] = $deny_cid;
4739 $arr['deny_gid'] = $deny_gid;
4740 $arr['last-child'] = 1;
4741 $arr['visible'] = $visibility;
4745 'image/jpeg' => 'jpg',
4746 'image/png' => 'png',
4747 'image/gif' => 'gif'
4750 // adds link to the thumbnail scale photo
4751 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4752 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4755 // do the magic for storing the item in the database and trigger the federation to other contacts
4761 * @param string $type
4763 * @param string $photo_id
4767 function prepare_photo_data($type, $scale, $photo_id)
4769 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4770 $data_sql = ($scale === false ? "" : "data, ");
4772 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4773 // clients needs to convert this in their way for further processing
4775 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4776 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4777 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4778 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4780 intval(local_user()),
4786 'image/jpeg' => 'jpg',
4787 'image/png' => 'png',
4788 'image/gif' => 'gif'
4791 // prepare output data for photo
4792 if (DBM::is_result($r)) {
4793 $data = array('photo' => $r[0]);
4794 $data['photo']['id'] = $data['photo']['resource-id'];
4795 if ($scale !== false) {
4796 $data['photo']['data'] = base64_encode($data['photo']['data']);
4798 unset($data['photo']['datasize']); //needed only with scale param
4800 if ($type == "xml") {
4801 $data['photo']['links'] = array();
4802 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4803 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4805 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4808 $data['photo']['link'] = array();
4809 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4811 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4812 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4816 unset($data['photo']['resource-id']);
4817 unset($data['photo']['minscale']);
4818 unset($data['photo']['maxscale']);
4820 throw new NotFoundException();
4823 // retrieve item element for getting activities (like, dislike etc.) related to photo
4825 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4826 intval(local_user()),
4829 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4831 // retrieve comments on photo
4833 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4834 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4835 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4836 `contact`.`id` AS `cid`
4838 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4839 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4840 WHERE `item`.`parent` = %d AND `item`.`visible`
4841 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4842 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4843 intval($item[0]['parent']),
4845 dbesc(ACTIVITY_POST)
4848 // prepare output of comments
4849 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4850 $comments = array();
4851 if ($type == "xml") {
4853 foreach ($commentData as $comment) {
4854 $comments[$k++ . ":comment"] = $comment;
4857 foreach ($commentData as $comment) {
4858 $comments[] = $comment;
4861 $data['photo']['friendica_comments'] = $comments;
4863 // include info if rights on photo and rights on item are mismatching
4864 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4865 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4866 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4867 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4868 $data['photo']['rights_mismatch'] = $rights_mismatch;
4875 * Similar as /mod/redir.php
4876 * redirect to 'url' after dfrn auth
4878 * Why this when there is mod/redir.php already?
4879 * This use api_user() and api_login()
4882 * c_url: url of remote contact to auth to
4883 * url: string, url to redirect after auth
4885 function api_friendica_remoteauth()
4887 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4888 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4890 if ($url === '' || $c_url === '') {
4891 throw new BadRequestException("Wrong parameters.");
4894 $c_url = normalise_link($c_url);
4898 $r = dba::select('contact', [], ['uid' => api_user(), 'nurl' => $c_url], ['limit' => 1]);
4900 if (!DBM::is_result($r) || ($r['network'] !== NETWORK_DFRN)) {
4901 throw new BadRequestException("Unknown contact");
4906 $dfrn_id = $orig_id = (($r['issued-id']) ? $r['issued-id'] : $r['dfrn-id']);
4908 if ($r['duplex'] && $r['issued-id']) {
4909 $orig_id = $r['issued-id'];
4910 $dfrn_id = '1:' . $orig_id;
4912 if ($r['duplex'] && $r['dfrn-id']) {
4913 $orig_id = $r['dfrn-id'];
4914 $dfrn_id = '0:' . $orig_id;
4917 $sec = random_string();
4920 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4921 VALUES( %d, %s, '%s', '%s', %d )",
4929 logger($r['name'] . ' ' . $sec, LOGGER_DEBUG);
4930 $dest = ($url ? '&destination_url=' . $url : '');
4932 $r['poll'] . '?dfrn_id=' . $dfrn_id
4933 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4934 . '&type=profile&sec=' . $sec . $dest . $quiet
4937 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4940 * @brief Return the item shared, if the item contains only the [share] tag
4942 * @param array $item Sharer item
4943 * @return array|false Shared item or false if not a reshare
4945 function api_share_as_retweet(&$item)
4947 $body = trim($item["body"]);
4949 if (Diaspora::isReshare($body, false)===false) {
4953 /// @TODO "$1" should maybe mean '$1' ?
4954 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4956 * Skip if there is no shared message in there
4957 * we already checked this in diaspora::isReshare()
4958 * but better one more than one less...
4960 if ($body == $attributes) {
4965 // build the fake reshared item
4966 $reshared_item = $item;
4969 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4970 if ($matches[1] != "") {
4971 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4974 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4975 if ($matches[1] != "") {
4976 $author = $matches[1];
4980 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4981 if ($matches[1] != "") {
4982 $profile = $matches[1];
4985 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4986 if ($matches[1] != "") {
4987 $profile = $matches[1];
4991 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4992 if ($matches[1] != "") {
4993 $avatar = $matches[1];
4996 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4997 if ($matches[1] != "") {
4998 $avatar = $matches[1];
5002 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5003 if ($matches[1] != "") {
5004 $link = $matches[1];
5007 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5008 if ($matches[1] != "") {
5009 $link = $matches[1];
5013 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5014 if ($matches[1] != "") {
5015 $posted = $matches[1];
5018 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5019 if ($matches[1] != "") {
5020 $posted = $matches[1];
5023 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5025 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5029 $reshared_item["body"] = $shared_body;
5030 $reshared_item["author-name"] = $author;
5031 $reshared_item["author-link"] = $profile;
5032 $reshared_item["author-avatar"] = $avatar;
5033 $reshared_item["plink"] = $link;
5034 $reshared_item["created"] = $posted;
5035 $reshared_item["edited"] = $posted;
5037 return $reshared_item;
5042 * @param string $profile
5044 * @return string|false
5045 * @todo remove trailing junk from profile url
5046 * @todo pump.io check has to check the website
5048 function api_get_nick($profile)
5053 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5054 dbesc(normalise_link($profile))
5057 if (DBM::is_result($r)) {
5058 $nick = $r[0]["nick"];
5063 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5064 dbesc(normalise_link($profile))
5067 if (DBM::is_result($r)) {
5068 $nick = $r[0]["nick"];
5073 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5074 if ($friendica != $profile) {
5080 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5081 if ($diaspora != $profile) {
5087 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5088 if ($twitter != $profile) {
5095 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5096 if ($StatusnetHost != $profile) {
5097 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5098 if ($StatusnetUser != $profile) {
5099 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5100 $user = json_decode($UserData);
5102 $nick = $user->screen_name;
5108 // To-Do: look at the page if its really a pumpio site
5109 //if (!$nick == "") {
5110 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5111 // if ($pumpio != $profile)
5113 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5126 * @param array $item
5130 function api_in_reply_to($item)
5132 $in_reply_to = array();
5134 $in_reply_to['status_id'] = null;
5135 $in_reply_to['user_id'] = null;
5136 $in_reply_to['status_id_str'] = null;
5137 $in_reply_to['user_id_str'] = null;
5138 $in_reply_to['screen_name'] = null;
5140 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5142 "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
5143 intval($item['uid']),
5144 dbesc($item['thr-parent'])
5147 if (DBM::is_result($r)) {
5148 $in_reply_to['status_id'] = intval($r[0]['id']);
5150 $in_reply_to['status_id'] = intval($item['parent']);
5153 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5156 "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
5157 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
5158 WHERE `item`.`id` = %d LIMIT 1",
5159 intval($in_reply_to['status_id'])
5162 if (DBM::is_result($r)) {
5163 if ($r[0]['nick'] == "") {
5164 $r[0]['nick'] = api_get_nick($r[0]["url"]);
5167 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
5168 $in_reply_to['user_id'] = intval($r[0]['id']);
5169 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
5172 // There seems to be situation, where both fields are identical:
5173 // https://github.com/friendica/friendica/issues/1010
5174 // This is a bugfix for that.
5175 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5176 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
5177 $in_reply_to['status_id'] = null;
5178 $in_reply_to['user_id'] = null;
5179 $in_reply_to['status_id_str'] = null;
5180 $in_reply_to['user_id_str'] = null;
5181 $in_reply_to['screen_name'] = null;
5185 return $in_reply_to;
5190 * @param string $Text
5194 function api_clean_plain_items($Text)
5196 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5198 $Text = bb_CleanPictureLinks($Text);
5199 $URLSearchString = "^\[\]";
5201 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
5203 if ($include_entities == "true") {
5204 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
5207 // Simplify "attachment" element
5208 $Text = api_clean_attachments($Text);
5214 * @brief Removes most sharing information for API text export
5216 * @param string $body The original body
5218 * @return string Cleaned body
5220 function api_clean_attachments($body)
5222 $data = get_attachment_data($body);
5229 if (isset($data["text"])) {
5230 $body = $data["text"];
5232 if (($body == "") && isset($data["title"])) {
5233 $body = $data["title"];
5235 if (isset($data["url"])) {
5236 $body .= "\n".$data["url"];
5238 $body .= $data["after"];
5245 * @param array $contacts
5249 function api_best_nickname(&$contacts)
5251 $best_contact = array();
5253 if (count($contact) == 0) {
5257 foreach ($contacts as $contact) {
5258 if ($contact["network"] == "") {
5259 $contact["network"] = "dfrn";
5260 $best_contact = array($contact);
5264 if (sizeof($best_contact) == 0) {
5265 foreach ($contacts as $contact) {
5266 if ($contact["network"] == "dfrn") {
5267 $best_contact = array($contact);
5272 if (sizeof($best_contact) == 0) {
5273 foreach ($contacts as $contact) {
5274 if ($contact["network"] == "dspr") {
5275 $best_contact = array($contact);
5280 if (sizeof($best_contact) == 0) {
5281 foreach ($contacts as $contact) {
5282 if ($contact["network"] == "stat") {
5283 $best_contact = array($contact);
5288 if (sizeof($best_contact) == 0) {
5289 foreach ($contacts as $contact) {
5290 if ($contact["network"] == "pump") {
5291 $best_contact = array($contact);
5296 if (sizeof($best_contact) == 0) {
5297 foreach ($contacts as $contact) {
5298 if ($contact["network"] == "twit") {
5299 $best_contact = array($contact);
5304 if (sizeof($best_contact) == 1) {
5305 $contacts = $best_contact;
5307 $contacts = array($contacts[0]);
5312 * Return all or a specified group of the user with the containing contacts.
5314 * @param string $type Return type (atom, rss, xml, json)
5316 * @return array|string
5318 function api_friendica_group_show($type)
5322 if (api_user() === false) {
5323 throw new ForbiddenException();
5327 $user_info = api_get_user($a);
5328 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5329 $uid = $user_info['uid'];
5331 // get data of the specified group id or all groups if not specified
5334 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5338 // error message if specified gid is not in database
5339 if (!DBM::is_result($r)) {
5340 throw new BadRequestException("gid not available");
5344 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5349 // loop through all groups and retrieve all members for adding data in the user array
5350 foreach ($r as $rr) {
5351 $members = Contact::getByGroupId($rr['id']);
5354 if ($type == "xml") {
5355 $user_element = "users";
5357 foreach ($members as $member) {
5358 $user = api_get_user($a, $member['nurl']);
5359 $users[$k++.":user"] = $user;
5362 $user_element = "user";
5363 foreach ($members as $member) {
5364 $user = api_get_user($a, $member['nurl']);
5368 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
5370 return api_format_data("groups", $type, array('group' => $grps));
5372 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5376 * Delete the specified group of the user.
5378 * @param string $type Return type (atom, rss, xml, json)
5380 * @return array|string
5382 function api_friendica_group_delete($type)
5386 if (api_user() === false) {
5387 throw new ForbiddenException();
5391 $user_info = api_get_user($a);
5392 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5393 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5394 $uid = $user_info['uid'];
5396 // error if no gid specified
5397 if ($gid == 0 || $name == "") {
5398 throw new BadRequestException('gid or name not specified');
5401 // get data of the specified group id
5403 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5407 // error message if specified gid is not in database
5408 if (!DBM::is_result($r)) {
5409 throw new BadRequestException('gid not available');
5412 // get data of the specified group id and group name
5414 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5419 // error message if specified gid is not in database
5420 if (!DBM::is_result($rname)) {
5421 throw new BadRequestException('wrong group name');
5425 $ret = Group::removeByName($uid, $name);
5428 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
5429 return api_format_data("group_delete", $type, array('result' => $success));
5431 throw new BadRequestException('other API error');
5434 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5438 * Create the specified group with the posted array of contacts.
5440 * @param string $type Return type (atom, rss, xml, json)
5442 * @return array|string
5444 function api_friendica_group_create($type)
5448 if (api_user() === false) {
5449 throw new ForbiddenException();
5453 $user_info = api_get_user($a);
5454 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5455 $uid = $user_info['uid'];
5456 $json = json_decode($_POST['json'], true);
5457 $users = $json['user'];
5459 // error if no name specified
5461 throw new BadRequestException('group name not specified');
5464 // get data of the specified group name
5466 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5470 // error message if specified group name already exists
5471 if (DBM::is_result($rname)) {
5472 throw new BadRequestException('group name already exists');
5475 // check if specified group name is a deleted group
5477 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5481 // error message if specified group name already exists
5482 if (DBM::is_result($rname)) {
5483 $reactivate_group = true;
5487 $ret = Group::create($uid, $name);
5489 $gid = Group::getIdByName($uid, $name);
5491 throw new BadRequestException('other API error');
5495 $erroraddinguser = false;
5496 $errorusers = array();
5497 foreach ($users as $user) {
5498 $cid = $user['cid'];
5499 // check if user really exists as contact
5501 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5505 if (count($contact)) {
5506 $result = Group::addMember($gid, $cid);
5508 $erroraddinguser = true;
5509 $errorusers[] = $cid;
5513 // return success message incl. missing users in array
5514 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
5515 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
5516 return api_format_data("group_create", $type, array('result' => $success));
5518 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5522 * Update the specified group with the posted array of contacts.
5524 * @param string $type Return type (atom, rss, xml, json)
5526 * @return array|string
5528 function api_friendica_group_update($type)
5532 if (api_user() === false) {
5533 throw new ForbiddenException();
5537 $user_info = api_get_user($a);
5538 $uid = $user_info['uid'];
5539 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5540 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5541 $json = json_decode($_POST['json'], true);
5542 $users = $json['user'];
5544 // error if no name specified
5546 throw new BadRequestException('group name not specified');
5549 // error if no gid specified
5551 throw new BadRequestException('gid not specified');
5555 $members = Contact::getByGroupId($gid);
5556 foreach ($members as $member) {
5557 $cid = $member['id'];
5558 foreach ($users as $user) {
5559 $found = ($user['cid'] == $cid ? true : false);
5562 $ret = Group::removeMemberByName($uid, $name, $cid);
5567 $erroraddinguser = false;
5568 $errorusers = array();
5569 foreach ($users as $user) {
5570 $cid = $user['cid'];
5571 // check if user really exists as contact
5573 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5578 if (count($contact)) {
5579 $result = Group::addMember($gid, $cid);
5581 $erroraddinguser = true;
5582 $errorusers[] = $cid;
5586 // return success message incl. missing users in array
5587 $status = ($erroraddinguser ? "missing user" : "ok");
5588 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
5589 return api_format_data("group_update", $type, array('result' => $success));
5592 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5596 * @param string $type Return type (atom, rss, xml, json)
5598 * @return array|string
5600 function api_friendica_activity($type)
5604 if (api_user() === false) {
5605 throw new ForbiddenException();
5607 $verb = strtolower($a->argv[3]);
5608 $verb = preg_replace("|\..*$|", "", $verb);
5610 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5612 $res = do_like($id, $verb);
5615 if ($type == "xml") {
5620 return api_format_data('ok', $type, array('ok' => $ok));
5622 throw new BadRequestException('Error adding activity');
5626 /// @TODO move to top of file or somewhere better
5627 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5628 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5629 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5630 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5631 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5632 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5633 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5634 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5635 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5636 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5639 * @brief Returns notifications
5641 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5644 function api_friendica_notification($type)
5648 if (api_user() === false) {
5649 throw new ForbiddenException();
5652 throw new BadRequestException("Invalid argument count");
5654 $nm = new NotificationsManager();
5656 $notes = $nm->getAll(array(), "+seen -date", 50);
5658 if ($type == "xml") {
5659 $xmlnotes = array();
5660 foreach ($notes as $note) {
5661 $xmlnotes[] = array("@attributes" => $note);
5667 return api_format_data("notes", $type, array('note' => $notes));
5671 * POST request with 'id' param as notification id
5673 * @brief Set notification as seen and returns associated item (if possible)
5675 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5678 function api_friendica_notification_seen($type)
5682 if (api_user() === false) {
5683 throw new ForbiddenException();
5686 throw new BadRequestException("Invalid argument count");
5689 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5691 $nm = new NotificationsManager();
5692 $note = $nm->getByID($id);
5693 if (is_null($note)) {
5694 throw new BadRequestException("Invalid argument");
5697 $nm->setSeen($note);
5698 if ($note['otype']=='item') {
5699 // would be really better with an ItemsManager and $im->getByID() :-P
5701 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5702 intval($note['iid']),
5703 intval(local_user())
5706 // we found the item, return it to the user
5707 $user_info = api_get_user($a);
5708 $ret = api_format_items($r, $user_info, false, $type);
5709 $data = array('status' => $ret);
5710 return api_format_data("status", $type, $data);
5712 // the item can't be found, but we set the note as seen, so we count this as a success
5714 return api_format_data('result', $type, array('result' => "success"));
5717 /// @TODO move to top of file or somewhere better
5718 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5719 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5722 * @brief update a direct_message to seen state
5724 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5725 * @return string (success result=ok, error result=error with error message)
5727 function api_friendica_direct_messages_setseen($type)
5730 if (api_user() === false) {
5731 throw new ForbiddenException();
5735 $user_info = api_get_user($a);
5736 $uid = $user_info['uid'];
5737 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5739 // return error if id is zero
5741 $answer = array('result' => 'error', 'message' => 'message id not specified');
5742 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5745 // get data of the specified message id
5747 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5752 // error message if specified id is not in database
5753 if (!DBM::is_result($r)) {
5754 $answer = array('result' => 'error', 'message' => 'message id not in database');
5755 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5758 // update seen indicator
5760 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5767 $answer = array('result' => 'ok', 'message' => 'message set to seen');
5768 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
5770 $answer = array('result' => 'error', 'message' => 'unknown error');
5771 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5775 /// @TODO move to top of file or somewhere better
5776 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5779 * @brief search for direct_messages containing a searchstring through api
5781 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5782 * @return string (success: success=true if found and search_result contains found messages,
5783 * success=false if nothing was found, search_result='nothing found',
5784 * error: result=error with error message)
5786 function api_friendica_direct_messages_search($type)
5790 if (api_user() === false) {
5791 throw new ForbiddenException();
5795 $user_info = api_get_user($a);
5796 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5797 $uid = $user_info['uid'];
5799 // error if no searchstring specified
5800 if ($searchstring == "") {
5801 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
5802 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
5805 // get data for the specified searchstring
5807 "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",
5809 dbesc('%'.$searchstring.'%')
5812 $profile_url = $user_info["url"];
5814 // message if nothing was found
5815 if (!DBM::is_result($r)) {
5816 $success = array('success' => false, 'search_results' => 'problem with query');
5817 } elseif (count($r) == 0) {
5818 $success = array('success' => false, 'search_results' => 'nothing found');
5821 foreach ($r as $item) {
5822 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5823 $recipient = $user_info;
5824 $sender = api_get_user($a, normalise_link($item['contact-url']));
5825 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5826 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5827 $sender = $user_info;
5830 $ret[] = api_format_messages($item, $recipient, $sender);
5832 $success = array('success' => true, 'search_results' => $ret);
5835 return api_format_data("direct_message_search", $type, array('$result' => $success));
5838 /// @TODO move to top of file or somewhere better
5839 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5842 * @brief return data of all the profiles a user has to the client
5844 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5847 function api_friendica_profile_show($type)
5851 if (api_user() === false) {
5852 throw new ForbiddenException();
5856 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5858 // retrieve general information about profiles for user
5859 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5860 $directory = Config::get('system', 'directory');
5862 // get data of the specified profile id or all profiles of the user if not specified
5863 if ($profileid != 0) {
5865 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5870 // error message if specified gid is not in database
5871 if (!DBM::is_result($r)) {
5872 throw new BadRequestException("profile_id not available");
5876 "SELECT * FROM `profile` WHERE `uid` = %d",
5880 // loop through all returned profiles and retrieve data and users
5882 foreach ($r as $rr) {
5883 $profile = api_format_items_profiles($rr, $type);
5885 // select all users from contact table, loop and prepare standard return for user data
5888 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5890 intval($rr['profile_id'])
5893 foreach ($r as $rr) {
5894 $user = api_get_user($a, $rr['nurl']);
5895 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5897 $profile['users'] = $users;
5899 // add prepared profile data to array for final return
5900 if ($type == "xml") {
5901 $profiles[$k++ . ":profile"] = $profile;
5903 $profiles[] = $profile;
5907 // return settings, authenticated user and profiles data
5908 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5910 $result = array('multi_profiles' => $multi_profiles ? true : false,
5911 'global_dir' => $directory,
5912 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5913 'profiles' => $profiles);
5914 return api_format_data("friendica_profiles", $type, array('$result' => $result));
5916 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5919 * Returns a list of saved searches.
5921 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5923 * @param string $type Return format: json or xml
5925 * @return string|array
5927 function api_saved_searches_list($type)
5929 $terms = dba::select('search', array('id', 'term'), array('uid' => local_user()));
5932 while ($term = $terms->fetch()) {
5934 'name' => $term['term'],
5935 'query' => $term['term'],
5936 'id_str' => $term['id'],
5937 'id' => intval($term['id'])
5943 return api_format_data("terms", $type, array('terms' => $result));
5946 /// @TODO move to top of file or somewhere better
5947 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5950 @TODO Maybe open to implement?
5952 [pagename] => api/1.1/statuses/lookup.json
5953 [id] => 605138389168451584
5954 [include_cards] => true
5955 [cards_platform] => Android-12
5956 [include_entities] => true
5957 [include_my_retweet] => 1
5959 [include_reply_count] => true
5960 [include_descendent_reply_count] => true
5964 Not implemented by now:
5965 statuses/retweets_of_me
5970 account/update_location
5971 account/update_profile_background_image
5974 friendica/profile/update
5975 friendica/profile/create
5976 friendica/profile/delete
5978 Not implemented in status.net:
5979 statuses/retweeted_to_me
5980 statuses/retweeted_by_me
5981 direct_messages/destroy
5983 account/update_delivery_device
5984 notifications/follow