3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\Content\ContactSelector;
11 use Friendica\Content\Feature;
12 use Friendica\Content\Text\BBCode;
13 use Friendica\Core\Addon;
14 use Friendica\Core\Config;
15 use Friendica\Core\L10n;
16 use Friendica\Core\NotificationsManager;
17 use Friendica\Core\PConfig;
18 use Friendica\Core\System;
19 use Friendica\Core\Worker;
20 use Friendica\Database\DBM;
21 use Friendica\Model\Contact;
22 use Friendica\Model\Group;
23 use Friendica\Model\Item;
24 use Friendica\Model\Mail;
25 use Friendica\Model\Photo;
26 use Friendica\Model\User;
27 use Friendica\Network\FKOAuth1;
28 use Friendica\Network\HTTPException;
29 use Friendica\Network\HTTPException\BadRequestException;
30 use Friendica\Network\HTTPException\ForbiddenException;
31 use Friendica\Network\HTTPException\InternalServerErrorException;
32 use Friendica\Network\HTTPException\MethodNotAllowedException;
33 use Friendica\Network\HTTPException\NotFoundException;
34 use Friendica\Network\HTTPException\NotImplementedException;
35 use Friendica\Network\HTTPException\TooManyRequestsException;
36 use Friendica\Network\HTTPException\UnauthorizedException;
37 use Friendica\Object\Image;
38 use Friendica\Protocol\Diaspora;
39 use Friendica\Util\Network;
40 use Friendica\Util\Temporal;
41 use Friendica\Util\XML;
43 require_once 'include/bbcode.php';
44 require_once 'include/datetime.php';
45 require_once 'include/conversation.php';
46 require_once 'include/html2plain.php';
47 require_once 'mod/share.php';
48 require_once 'mod/item.php';
49 require_once 'include/security.php';
50 require_once 'include/html2bbcode.php';
51 require_once 'mod/wall_upload.php';
52 require_once 'mod/proxy.php';
54 define('API_METHOD_ANY', '*');
55 define('API_METHOD_GET', 'GET');
56 define('API_METHOD_POST', 'POST,PUT');
57 define('API_METHOD_DELETE', 'POST,DELETE');
63 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
64 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
65 * into a page, and visitors will post something without noticing it).
67 * @brief Auth API user
71 if (x($_SESSION, 'allow_api')) {
79 * Clients can send 'source' parameter to be show in post metadata
80 * as "sent via <source>".
81 * Some clients doesn't send a source param, we support ones we know
84 * @brief Get source name from API client
87 * Client source name, default to "api" if unset/unknown
91 if (requestdata('source')) {
92 return requestdata('source');
95 // Support for known clients that doesn't send a source name
96 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
100 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
106 * @brief Format date for API
108 * @param string $str Source date, as UTC
109 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
111 function api_date($str)
113 // Wed May 23 06:01:13 +0000 2007
114 return Temporal::convert($str, 'UTC', 'UTC', "D M d H:i:s +0000 Y");
118 * Register a function to be the endpoint for defined API path.
120 * @brief Register API endpoint
122 * @param string $path API URL path, relative to System::baseUrl()
123 * @param string $func Function name to call on path request
124 * @param bool $auth API need logged user
125 * @param string $method HTTP method reqiured to call this endpoint.
126 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
127 * Default to API_METHOD_ANY
129 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
139 // Workaround for hotot
140 $path = str_replace("api/", "api/1.1/", $path);
150 * Log in user via OAuth1 or Simple HTTP Auth.
151 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
153 * @brief Login API user
155 * @param object $a App
156 * @hook 'authenticate'
158 * 'username' => username from login form
159 * 'password' => password from login form
160 * 'authenticated' => return status,
161 * 'user_record' => return authenticated user record
163 * array $user logged user record
165 function api_login(App $a)
167 $oauth1 = new FKOAuth1();
170 list($consumer, $token) = $oauth1->verify_request(OAuthRequest::from_request());
171 if (!is_null($token)) {
172 $oauth1->loginUser($token->uid);
173 Addon::callHooks('logged_in', $a->user);
176 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
177 var_dump($consumer, $token);
179 } catch (Exception $e) {
183 // workaround for HTTP-auth in CGI mode
184 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
185 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
186 if (strlen($userpass)) {
187 list($name, $password) = explode(':', $userpass);
188 $_SERVER['PHP_AUTH_USER'] = $name;
189 $_SERVER['PHP_AUTH_PW'] = $password;
193 if (!x($_SERVER, 'PHP_AUTH_USER')) {
194 logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
195 header('WWW-Authenticate: Basic realm="Friendica"');
196 throw new UnauthorizedException("This API requires login");
199 $user = $_SERVER['PHP_AUTH_USER'];
200 $password = $_SERVER['PHP_AUTH_PW'];
202 // allow "user@server" login (but ignore 'server' part)
203 $at = strstr($user, "@", true);
208 // next code from mod/auth.php. needs better solution
212 'username' => trim($user),
213 'password' => trim($password),
214 'authenticated' => 0,
215 'user_record' => null,
219 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
220 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
221 * and later addons should not interfere with an earlier one that succeeded.
223 Addon::callHooks('authenticate', $addon_auth);
225 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
226 $record = $addon_auth['user_record'];
228 $user_id = User::authenticate(trim($user), trim($password));
230 $record = dba::selectFirst('user', [], ['uid' => $user_id]);
234 if (!DBM::is_result($record)) {
235 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
236 header('WWW-Authenticate: Basic realm="Friendica"');
237 //header('HTTP/1.0 401 Unauthorized');
238 //die('This api requires login');
239 throw new UnauthorizedException("This API requires login");
242 authenticate_success($record);
244 $_SESSION["allow_api"] = true;
246 Addon::callHooks('logged_in', $a->user);
250 * API endpoints can define which HTTP method to accept when called.
251 * This function check the current HTTP method agains endpoint
254 * @brief Check HTTP method of called API
256 * @param string $method Required methods, uppercase, separated by comma
259 function api_check_method($method)
261 if ($method == "*") {
264 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
268 * Authenticate user, call registered API function, set HTTP headers
270 * @brief Main API entry point
272 * @param object $a App
273 * @return string API call result
275 function api_call(App $a)
277 global $API, $called_api;
280 if (strpos($a->query_string, ".xml") > 0) {
283 if (strpos($a->query_string, ".json") > 0) {
286 if (strpos($a->query_string, ".rss") > 0) {
289 if (strpos($a->query_string, ".atom") > 0) {
294 foreach ($API as $p => $info) {
295 if (strpos($a->query_string, $p) === 0) {
296 if (!api_check_method($info['method'])) {
297 throw new MethodNotAllowedException();
300 $called_api = explode("/", $p);
301 //unset($_SERVER['PHP_AUTH_USER']);
303 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
304 if ($info['auth'] === true && api_user() === false) {
308 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
309 logger('API parameters: ' . print_r($_REQUEST, true));
311 $stamp = microtime(true);
312 $return = call_user_func($info['func'], $type);
313 $duration = (float) (microtime(true) - $stamp);
314 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
316 if (Config::get("system", "profiler")) {
317 $duration = microtime(true)-$a->performance["start"];
319 /// @TODO round() really everywhere?
321 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
322 "Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
323 round($a->performance["database"] - $a->performance["database_write"], 3),
324 round($a->performance["database_write"], 3),
325 round($a->performance["network"], 2),
326 round($a->performance["file"], 2),
327 round($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
333 if (Config::get("rendertime", "callstack")) {
334 $o = "Database Read:\n";
335 foreach ($a->callstack["database"] as $func => $time) {
336 $time = round($time, 3);
338 $o .= $func . ": " . $time . "\n";
341 $o .= "\nDatabase Write:\n";
342 foreach ($a->callstack["database_write"] as $func => $time) {
343 $time = round($time, 3);
345 $o .= $func . ": " . $time . "\n";
349 $o .= "\nNetwork:\n";
350 foreach ($a->callstack["network"] as $func => $time) {
351 $time = round($time, 3);
353 $o .= $func . ": " . $time . "\n";
356 logger($o, LOGGER_DEBUG);
360 if (false === $return) {
362 * api function returned false withour throw an
363 * exception. This should not happend, throw a 500
365 throw new InternalServerErrorException();
370 header("Content-Type: text/xml");
373 header("Content-Type: application/json");
374 foreach ($return as $rr) {
375 $json = json_encode($rr);
377 if (x($_GET, 'callback')) {
378 $json = $_GET['callback'] . "(" . $json . ")";
383 header("Content-Type: application/rss+xml");
384 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
387 header("Content-Type: application/atom+xml");
388 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
395 logger('API call not implemented: ' . $a->query_string);
396 throw new NotImplementedException();
397 } catch (HTTPException $e) {
398 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
399 return api_error($type, $e);
404 * @brief Format API error string
406 * @param string $type Return type (xml, json, rss, as)
407 * @param object $e HTTPException Error object
408 * @return string error message formatted as $type
410 function api_error($type, $e)
414 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
415 /// @TODO: https://dev.twitter.com/overview/api/response-codes
417 $error = ["error" => $error,
418 "code" => $e->httpcode . " " . $e->httpdesc,
419 "request" => $a->query_string];
421 $return = api_format_data('status', $type, ['status' => $error]);
425 header("Content-Type: text/xml");
428 header("Content-Type: application/json");
429 $return = json_encode($return);
432 header("Content-Type: application/rss+xml");
435 header("Content-Type: application/atom+xml");
443 * @brief Set values for RSS template
446 * @param array $arr Array to be passed to template
447 * @param array $user_info User info
449 * @todo find proper type-hints
451 function api_rss_extra(App $a, $arr, $user_info)
453 if (is_null($user_info)) {
454 $user_info = api_get_user($a);
457 $arr['$user'] = $user_info;
459 'alternate' => $user_info['url'],
460 'self' => System::baseUrl() . "/" . $a->query_string,
461 'base' => System::baseUrl(),
462 'updated' => api_date(null),
463 'atom_updated' => Temporal::convert('now', 'UTC', 'UTC', Temporal::ATOM),
464 'language' => $user_info['language'],
465 'logo' => System::baseUrl() . "/images/friendica-32.png",
473 * @brief Unique contact to contact url.
475 * @param int $id Contact id
476 * @return bool|string
477 * Contact url or False if contact id is unknown
479 function api_unique_id_to_nurl($id)
481 $r = dba::selectFirst('contact', ['nurl'], ['uid' => 0, 'id' => $id]);
483 if (DBM::is_result($r)) {
491 * @brief Get user info array.
493 * @param object $a App
494 * @param int|string $contact_id Contact ID or URL
496 function api_get_user(App $a, $contact_id = null)
504 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
506 // Searching for contact URL
507 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
508 $user = dbesc(normalise_link($contact_id));
510 $extra_query = "AND `contact`.`nurl` = '%s' ";
511 if (api_user() !== false) {
512 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
516 // Searching for contact id with uid = 0
517 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
518 $user = dbesc(api_unique_id_to_nurl($contact_id));
521 throw new BadRequestException("User not found.");
525 $extra_query = "AND `contact`.`nurl` = '%s' ";
526 if (api_user() !== false) {
527 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
531 if (is_null($user) && x($_GET, 'user_id')) {
532 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
535 throw new BadRequestException("User not found.");
539 $extra_query = "AND `contact`.`nurl` = '%s' ";
540 if (api_user() !== false) {
541 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
544 if (is_null($user) && x($_GET, 'screen_name')) {
545 $user = dbesc($_GET['screen_name']);
546 $extra_query = "AND `contact`.`nick` = '%s' ";
547 if (api_user() !== false) {
548 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
552 if (is_null($user) && x($_GET, 'profileurl')) {
553 $user = dbesc(normalise_link($_GET['profileurl']));
554 $extra_query = "AND `contact`.`nurl` = '%s' ";
555 if (api_user() !== false) {
556 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
560 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
561 $argid = count($called_api);
562 list($user, $null) = explode(".", $a->argv[$argid]);
563 if (is_numeric($user)) {
564 $user = dbesc(api_unique_id_to_nurl($user));
571 $extra_query = "AND `contact`.`nurl` = '%s' ";
572 if (api_user() !== false) {
573 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
576 $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 = ContactSelector::networkToName($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 = ContactSelector::networkToName($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::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
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 ([$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)
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 = ["" => "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, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
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 = [$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, ['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();
1121 // convert $_POST array items to the form we use for web posts.
1122 if (requestdata('htmlstatus')) {
1123 $txt = requestdata('htmlstatus');
1124 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1125 $txt = html2bb_video($txt);
1127 $config = HTMLPurifier_Config::createDefault();
1128 $config->set('Cache.DefinitionImpl', null);
1130 $purifier = new HTMLPurifier($config);
1131 $txt = $purifier->purify($txt);
1133 $_REQUEST['body'] = html2bbcode($txt);
1136 $_REQUEST['body'] = requestdata('status');
1139 $_REQUEST['title'] = requestdata('title');
1141 $parent = requestdata('in_reply_to_status_id');
1143 // Twidere sends "-1" if it is no reply ...
1144 if ($parent == -1) {
1148 if (ctype_digit($parent)) {
1149 $_REQUEST['parent'] = $parent;
1151 $_REQUEST['parent_uri'] = $parent;
1154 if (requestdata('lat') && requestdata('long')) {
1155 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1157 $_REQUEST['profile_uid'] = api_user();
1160 $_REQUEST['type'] = 'net-comment';
1162 // Check for throttling (maximum posts per day, week and month)
1163 $throttle_day = Config::get('system', 'throttle_limit_day');
1164 if ($throttle_day > 0) {
1165 $datefrom = date(Temporal::MYSQL, time() - 24*60*60);
1168 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1169 AND `created` > '%s' AND `id` = `parent`",
1174 if (DBM::is_result($r)) {
1175 $posts_day = $r[0]["posts_day"];
1180 if ($posts_day > $throttle_day) {
1181 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1182 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1183 throw new TooManyRequestsException(L10n::tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1187 $throttle_week = Config::get('system', 'throttle_limit_week');
1188 if ($throttle_week > 0) {
1189 $datefrom = date(Temporal::MYSQL, time() - 24*60*60*7);
1192 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1193 AND `created` > '%s' AND `id` = `parent`",
1198 if (DBM::is_result($r)) {
1199 $posts_week = $r[0]["posts_week"];
1204 if ($posts_week > $throttle_week) {
1205 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1206 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1207 throw new TooManyRequestsException(L10n::tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week));
1211 $throttle_month = Config::get('system', 'throttle_limit_month');
1212 if ($throttle_month > 0) {
1213 $datefrom = date(Temporal::MYSQL, time() - 24*60*60*30);
1216 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1217 AND `created` > '%s' AND `id` = `parent`",
1222 if (DBM::is_result($r)) {
1223 $posts_month = $r[0]["posts_month"];
1228 if ($posts_month > $throttle_month) {
1229 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1230 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1231 throw new TooManyRequestsException(L10n::t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1235 $_REQUEST['type'] = 'wall';
1238 if (x($_FILES, 'media')) {
1239 // upload the image if we have one
1240 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1241 $media = wall_upload_post($a);
1242 if (strlen($media) > 0) {
1243 $_REQUEST['body'] .= "\n\n" . $media;
1247 // To-Do: Multiple IDs
1248 if (requestdata('media_ids')) {
1250 "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",
1251 intval(requestdata('media_ids')),
1254 if (DBM::is_result($r)) {
1255 $phototypes = Image::supportedTypes();
1256 $ext = $phototypes[$r[0]['type']];
1257 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1258 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1262 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1264 $_REQUEST['api_source'] = true;
1266 if (!x($_REQUEST, "source")) {
1267 $_REQUEST["source"] = api_source();
1270 // call out normal post function
1273 // this should output the last post (the one we just posted).
1274 return api_status_show($type);
1277 /// @TODO move to top of file or somewhere better
1278 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1279 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1282 * Uploads an image to Friendica.
1285 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1287 function api_media_upload()
1291 if (api_user() === false) {
1293 throw new ForbiddenException();
1298 if (!x($_FILES, 'media')) {
1300 throw new BadRequestException("No media.");
1303 $media = wall_upload_post($a, false);
1306 throw new InternalServerErrorException();
1310 $returndata["media_id"] = $media["id"];
1311 $returndata["media_id_string"] = (string)$media["id"];
1312 $returndata["size"] = $media["size"];
1313 $returndata["image"] = ["w" => $media["width"],
1314 "h" => $media["height"],
1315 "image_type" => $media["type"]];
1317 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1319 return ["media" => $returndata];
1322 /// @TODO move to top of file or somewhere better
1323 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1327 * @param string $type Return type (atom, rss, xml, json)
1329 * @return array|string
1331 function api_status_show($type)
1335 $user_info = api_get_user($a);
1337 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1339 if ($type == "raw") {
1340 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1345 // get last public wall message
1349 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1350 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1351 AND `item`.`type` != 'activity' $privacy_sql
1352 ORDER BY `item`.`id` DESC
1354 intval($user_info['cid']),
1356 dbesc($user_info['url']),
1357 dbesc(normalise_link($user_info['url'])),
1358 dbesc($user_info['url']),
1359 dbesc(normalise_link($user_info['url']))
1362 if (DBM::is_result($lastwall)) {
1363 $lastwall = $lastwall[0];
1365 $in_reply_to = api_in_reply_to($lastwall);
1367 $converted = api_convert_item($lastwall);
1369 if ($type == "xml") {
1370 $geo = "georss:point";
1376 'created_at' => api_date($lastwall['created']),
1377 'id' => intval($lastwall['id']),
1378 'id_str' => (string) $lastwall['id'],
1379 'text' => $converted["text"],
1380 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1381 'truncated' => false,
1382 'in_reply_to_status_id' => $in_reply_to['status_id'],
1383 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1384 'in_reply_to_user_id' => $in_reply_to['user_id'],
1385 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1386 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1387 'user' => $user_info,
1389 'coordinates' => "",
1391 'contributors' => "",
1392 'is_quote_status' => false,
1393 'retweet_count' => 0,
1394 'favorite_count' => 0,
1395 'favorited' => $lastwall['starred'] ? true : false,
1396 'retweeted' => false,
1397 'possibly_sensitive' => false,
1399 'statusnet_html' => $converted["html"],
1400 'statusnet_conversation_id' => $lastwall['parent'],
1401 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1404 if (count($converted["attachments"]) > 0) {
1405 $status_info["attachments"] = $converted["attachments"];
1408 if (count($converted["entities"]) > 0) {
1409 $status_info["entities"] = $converted["entities"];
1412 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1413 $status_info["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1414 } elseif (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1415 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['item_network'], $user_info['url']).')');
1418 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1419 unset($status_info["user"]["uid"]);
1420 unset($status_info["user"]["self"]);
1423 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1425 if ($type == "raw") {
1426 return $status_info;
1429 return api_format_data("statuses", $type, ['status' => $status_info]);
1433 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1434 * The author's most recent status will be returned inline.
1436 * @param string $type Return type (atom, rss, xml, json)
1437 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1439 function api_users_show($type)
1443 $user_info = api_get_user($a);
1447 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1448 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1449 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1450 AND `type`!='activity'
1451 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1455 dbesc(ACTIVITY_POST),
1456 intval($user_info['cid']),
1457 dbesc($user_info['url']),
1458 dbesc(normalise_link($user_info['url'])),
1459 dbesc($user_info['url']),
1460 dbesc(normalise_link($user_info['url']))
1463 if (DBM::is_result($lastwall)) {
1464 $lastwall = $lastwall[0];
1466 $in_reply_to = api_in_reply_to($lastwall);
1468 $converted = api_convert_item($lastwall);
1470 if ($type == "xml") {
1471 $geo = "georss:point";
1476 $user_info['status'] = [
1477 'text' => $converted["text"],
1478 'truncated' => false,
1479 'created_at' => api_date($lastwall['created']),
1480 'in_reply_to_status_id' => $in_reply_to['status_id'],
1481 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1482 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1483 'id' => intval($lastwall['contact-id']),
1484 'id_str' => (string) $lastwall['contact-id'],
1485 'in_reply_to_user_id' => $in_reply_to['user_id'],
1486 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1487 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1489 'favorited' => $lastwall['starred'] ? true : false,
1490 'statusnet_html' => $converted["html"],
1491 'statusnet_conversation_id' => $lastwall['parent'],
1492 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1495 if (count($converted["attachments"]) > 0) {
1496 $user_info["status"]["attachments"] = $converted["attachments"];
1499 if (count($converted["entities"]) > 0) {
1500 $user_info["status"]["entities"] = $converted["entities"];
1503 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1504 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1507 if (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1508 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) . ')');
1512 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1513 unset($user_info["uid"]);
1514 unset($user_info["self"]);
1516 return api_format_data("user", $type, ['user' => $user_info]);
1519 /// @TODO move to top of file or somewhere better
1520 api_register_func('api/users/show', 'api_users_show');
1521 api_register_func('api/externalprofile/show', 'api_users_show');
1524 * Search a public user account.
1526 * @param string $type Return type (atom, rss, xml, json)
1528 * @return array|string
1529 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1531 function api_users_search($type)
1537 if (x($_GET, 'q')) {
1538 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1540 if (!DBM::is_result($r)) {
1541 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1544 if (DBM::is_result($r)) {
1546 foreach ($r as $user) {
1547 $user_info = api_get_user($a, $user["id"]);
1549 if ($type == "xml") {
1550 $userlist[$k++.":user"] = $user_info;
1552 $userlist[] = $user_info;
1555 $userlist = ["users" => $userlist];
1557 throw new BadRequestException("User not found.");
1560 throw new BadRequestException("User not found.");
1563 return api_format_data("users", $type, $userlist);
1566 /// @TODO move to top of file or somewhere better
1567 api_register_func('api/users/search', 'api_users_search');
1570 * Return user objects
1572 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1574 * @param string $type Return format: json or xml
1576 * @return array|string
1577 * @throws NotFoundException if the results are empty.
1579 function api_users_lookup($type)
1583 if (x($_REQUEST['user_id'])) {
1584 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1586 $users[] = api_get_user(get_app(), $id);
1591 if (empty($users)) {
1592 throw new NotFoundException;
1595 return api_format_data("users", $type, ['users' => $users]);
1598 /// @TODO move to top of file or somewhere better
1599 api_register_func('api/users/lookup', 'api_users_lookup', true);
1602 * Returns statuses that match a specified query.
1604 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1606 * @param string $type Return format: json, xml, atom, rss
1608 * @return array|string
1609 * @throws BadRequestException if the "q" parameter is missing.
1611 function api_search($type)
1615 if (!x($_REQUEST, 'q')) {
1616 throw new BadRequestException("q parameter is required.");
1619 if (x($_REQUEST, 'rpp')) {
1620 $count = $_REQUEST['rpp'];
1621 } elseif (x($_REQUEST, 'count')) {
1622 $count = $_REQUEST['count'];
1627 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1628 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1629 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1631 $start = $page * $count;
1634 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1638 "SELECT ".item_fieldlists()."
1639 FROM `item` ".item_joins()."
1640 WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1641 AND `item`.`body` LIKE CONCAT('%',?,'%')
1644 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
1650 $data['status'] = api_format_items(dba::inArray($r), api_get_user(get_app()));
1652 return api_format_data("statuses", $type, $data);
1655 /// @TODO move to top of file or somewhere better
1656 api_register_func('api/search/tweets', 'api_search', true);
1657 api_register_func('api/search', 'api_search', true);
1660 * Returns the most recent statuses posted by the user and the users they follow.
1662 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1664 * @param string $type Return type (atom, rss, xml, json)
1666 * @todo Optional parameters
1667 * @todo Add reply info
1669 function api_statuses_home_timeline($type)
1673 if (api_user() === false) {
1674 throw new ForbiddenException();
1677 unset($_REQUEST["user_id"]);
1678 unset($_GET["user_id"]);
1680 unset($_REQUEST["screen_name"]);
1681 unset($_GET["screen_name"]);
1683 $user_info = api_get_user($a);
1684 // get last newtork messages
1687 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1688 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1692 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1693 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1694 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1695 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1696 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1698 $start = $page * $count;
1702 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1704 if ($exclude_replies > 0) {
1705 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1707 if ($conversation_id > 0) {
1708 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1712 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1713 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1714 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1715 `contact`.`id` AS `cid`
1717 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1718 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1719 WHERE `item`.`uid` = %d AND `verb` = '%s'
1720 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1723 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1725 dbesc(ACTIVITY_POST),
1731 $ret = api_format_items($r, $user_info, false, $type);
1733 // Set all posts from the query above to seen
1735 foreach ($r as $item) {
1736 $idarray[] = intval($item["id"]);
1739 $idlist = implode(",", $idarray);
1741 if ($idlist != "") {
1742 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1745 q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1749 $data = ['status' => $ret];
1753 $data = api_rss_extra($a, $data, $user_info);
1757 return api_format_data("statuses", $type, $data);
1760 /// @TODO move to top of file or somewhere better
1761 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1762 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1765 * Returns the most recent statuses from public users.
1767 * @param string $type Return type (atom, rss, xml, json)
1769 * @return array|string
1771 function api_statuses_public_timeline($type)
1775 if (api_user() === false) {
1776 throw new ForbiddenException();
1779 $user_info = api_get_user($a);
1780 // get last newtork messages
1783 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1784 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1788 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1789 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1790 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1791 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1792 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1794 $start = $page * $count;
1796 if ($exclude_replies && !$conversation_id) {
1798 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1802 "SELECT " . item_fieldlists() . "
1804 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1805 " . item_joins() . "
1806 STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1807 AND NOT `user`.`hidewall`
1809 AND NOT `thread`.`private`
1811 AND `thread`.`visible`
1812 AND NOT `thread`.`deleted`
1813 AND NOT `thread`.`moderated`
1814 AND `thread`.`iid` > ?
1816 ORDER BY `thread`.`iid` DESC
1817 LIMIT " . intval($start) . ", " . intval($count),
1822 $r = dba::inArray($r);
1825 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1827 if ($conversation_id > 0) {
1828 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1832 "SELECT " . item_fieldlists() . "
1834 " . item_joins() . "
1835 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1836 AND NOT `user`.`hidewall`
1838 AND NOT `item`.`private`
1840 AND `item`.`visible`
1841 AND NOT `item`.`deleted`
1842 AND NOT `item`.`moderated`
1845 ORDER BY `item`.`id` DESC
1846 LIMIT " . intval($start) . ", " . intval($count),
1851 $r = dba::inArray($r);
1854 $ret = api_format_items($r, $user_info, false, $type);
1856 $data = ['status' => $ret];
1860 $data = api_rss_extra($a, $data, $user_info);
1864 return api_format_data("statuses", $type, $data);
1867 /// @TODO move to top of file or somewhere better
1868 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1871 * Returns the most recent statuses posted by users this node knows about.
1873 * @brief Returns the list of public federated posts this node knows about
1875 * @param string $type Return format: json, xml, atom, rss
1876 * @return array|string
1877 * @throws ForbiddenException
1879 function api_statuses_networkpublic_timeline($type)
1883 if (api_user() === false) {
1884 throw new ForbiddenException();
1887 $user_info = api_get_user($a);
1889 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1890 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1893 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1894 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1898 $start = ($page - 1) * $count;
1902 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1906 "SELECT " . item_fieldlists() . "
1908 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1909 " . item_joins() . "
1910 WHERE `thread`.`uid` = 0
1912 AND NOT `thread`.`private`
1913 AND `thread`.`visible`
1914 AND NOT `thread`.`deleted`
1915 AND NOT `thread`.`moderated`
1916 AND `thread`.`iid` > ?
1918 ORDER BY `thread`.`iid` DESC
1919 LIMIT " . intval($start) . ", " . intval($count),
1924 $r = dba::inArray($r);
1926 $ret = api_format_items($r, $user_info, false, $type);
1928 $data = ['status' => $ret];
1932 $data = api_rss_extra($a, $data, $user_info);
1936 return api_format_data("statuses", $type, $data);
1939 /// @TODO move to top of file or somewhere better
1940 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1943 * Returns a single status.
1945 * @param string $type Return type (atom, rss, xml, json)
1947 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1949 function api_statuses_show($type)
1953 if (api_user() === false) {
1954 throw new ForbiddenException();
1957 $user_info = api_get_user($a);
1960 $id = intval($a->argv[3]);
1963 $id = intval($_REQUEST["id"]);
1968 $id = intval($a->argv[4]);
1971 logger('API: api_statuses_show: ' . $id);
1973 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1976 if ($conversation) {
1977 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1979 $sql_extra .= " AND `item`.`id` = %d";
1983 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1984 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1985 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1986 `contact`.`id` AS `cid`
1988 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1989 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1990 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1991 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1994 dbesc(ACTIVITY_POST),
1998 /// @TODO How about copying this to above methods which don't check $r ?
1999 if (!DBM::is_result($r)) {
2000 throw new BadRequestException("There is no status with this id.");
2003 $ret = api_format_items($r, $user_info, false, $type);
2005 if ($conversation) {
2006 $data = ['status' => $ret];
2007 return api_format_data("statuses", $type, $data);
2009 $data = ['status' => $ret[0]];
2010 return api_format_data("status", $type, $data);
2014 /// @TODO move to top of file or somewhere better
2015 api_register_func('api/statuses/show', 'api_statuses_show', true);
2019 * @param string $type Return type (atom, rss, xml, json)
2021 * @todo nothing to say?
2023 function api_conversation_show($type)
2027 if (api_user() === false) {
2028 throw new ForbiddenException();
2031 $user_info = api_get_user($a);
2034 $id = intval($a->argv[3]);
2035 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2036 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
2040 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2041 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2043 $start = $page*$count;
2046 $id = intval($_REQUEST["id"]);
2051 $id = intval($a->argv[4]);
2054 logger('API: api_conversation_show: '.$id);
2056 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
2057 if (DBM::is_result($r)) {
2058 $id = $r[0]["parent"];
2064 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2067 // Not sure why this query was so complicated. We should keep it here for a while,
2068 // just to make sure that we really don't need it.
2069 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
2070 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
2073 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2074 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2075 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2076 `contact`.`id` AS `cid`
2078 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2079 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2080 WHERE `item`.`parent` = %d AND `item`.`visible`
2081 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2082 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2083 AND `item`.`id`>%d $sql_extra
2084 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2087 dbesc(ACTIVITY_POST),
2093 if (!DBM::is_result($r)) {
2094 throw new BadRequestException("There is no status with this id.");
2097 $ret = api_format_items($r, $user_info, false, $type);
2099 $data = ['status' => $ret];
2100 return api_format_data("statuses", $type, $data);
2103 /// @TODO move to top of file or somewhere better
2104 api_register_func('api/conversation/show', 'api_conversation_show', true);
2105 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2110 * @param string $type Return type (atom, rss, xml, json)
2112 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2114 function api_statuses_repeat($type)
2120 if (api_user() === false) {
2121 throw new ForbiddenException();
2127 $id = intval($a->argv[3]);
2130 $id = intval($_REQUEST["id"]);
2135 $id = intval($a->argv[4]);
2138 logger('API: api_statuses_repeat: '.$id);
2141 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2142 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2143 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2144 `contact`.`id` AS `cid`
2146 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2147 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2148 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2149 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2150 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2152 AND `item`.`id`=%d",
2156 /// @TODO other style than above functions!
2157 if (DBM::is_result($r) && $r[0]['body'] != "") {
2158 if (strpos($r[0]['body'], "[/share]") !== false) {
2159 $pos = strpos($r[0]['body'], "[share");
2160 $post = substr($r[0]['body'], $pos);
2162 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2164 $post .= $r[0]['body'];
2165 $post .= "[/share]";
2167 $_REQUEST['body'] = $post;
2168 $_REQUEST['profile_uid'] = api_user();
2169 $_REQUEST['type'] = 'wall';
2170 $_REQUEST['api_source'] = true;
2172 if (!x($_REQUEST, "source")) {
2173 $_REQUEST["source"] = api_source();
2178 throw new ForbiddenException();
2181 // this should output the last post (the one we just posted).
2183 return api_status_show($type);
2186 /// @TODO move to top of file or somewhere better
2187 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2190 * Destroys a specific status.
2192 * @param string $type Return type (atom, rss, xml, json)
2194 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2196 function api_statuses_destroy($type)
2200 if (api_user() === false) {
2201 throw new ForbiddenException();
2207 $id = intval($a->argv[3]);
2210 $id = intval($_REQUEST["id"]);
2215 $id = intval($a->argv[4]);
2218 logger('API: api_statuses_destroy: '.$id);
2220 $ret = api_statuses_show($type);
2227 /// @TODO move to top of file or somewhere better
2228 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2231 * Returns the most recent mentions.
2233 * @param string $type Return type (atom, rss, xml, json)
2235 * @see http://developer.twitter.com/doc/get/statuses/mentions
2237 function api_statuses_mentions($type)
2241 if (api_user() === false) {
2242 throw new ForbiddenException();
2245 unset($_REQUEST["user_id"]);
2246 unset($_GET["user_id"]);
2248 unset($_REQUEST["screen_name"]);
2249 unset($_GET["screen_name"]);
2251 $user_info = api_get_user($a);
2252 // get last newtork messages
2256 $since_id = defaults($_REQUEST, 'since_id', 0);
2257 $max_id = defaults($_REQUEST, 'max_id' , 0);
2258 $count = defaults($_REQUEST, 'count' , 20);
2259 $page = defaults($_REQUEST, 'page' , 1);
2264 $start = ($page - 1) * $count;
2266 // Ugly code - should be changed
2267 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2268 $myurl = substr($myurl, strpos($myurl, '://') + 3);
2269 $myurl = str_replace('www.', '', $myurl);
2272 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2276 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2277 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2278 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2279 `contact`.`id` AS `cid`
2280 FROM `item` FORCE INDEX (`uid_id`)
2281 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2282 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2283 WHERE `item`.`uid` = %d AND `verb` = '%s'
2284 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2285 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2286 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2289 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2291 dbesc(ACTIVITY_POST),
2292 dbesc(protect_sprintf($myurl)),
2293 dbesc(protect_sprintf($myurl)),
2300 $ret = api_format_items($r, $user_info, false, $type);
2302 $data = ['status' => $ret];
2306 $data = api_rss_extra($a, $data, $user_info);
2310 return api_format_data("statuses", $type, $data);
2313 /// @TODO move to top of file or somewhere better
2314 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2315 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2318 * Returns the most recent statuses posted by the user.
2320 * @brief Returns a user's public timeline
2322 * @param string $type Either "json" or "xml"
2323 * @return string|array
2324 * @throws ForbiddenException
2325 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2327 function api_statuses_user_timeline($type)
2331 if (api_user() === false) {
2332 throw new ForbiddenException();
2335 $user_info = api_get_user($a);
2338 "api_statuses_user_timeline: api_user: ". api_user() .
2339 "\nuser_info: ".print_r($user_info, true) .
2340 "\n_REQUEST: ".print_r($_REQUEST, true),
2344 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2345 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2346 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2347 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2350 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2351 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2355 $start = ($page - 1) * $count;
2358 if ($user_info['self'] == 1) {
2359 $sql_extra .= " AND `item`.`wall` = 1 ";
2362 if ($exclude_replies > 0) {
2363 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2366 if ($conversation_id > 0) {
2367 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2371 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2375 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2376 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2377 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2378 `contact`.`id` AS `cid`
2379 FROM `item` FORCE INDEX (`uid_contactid_id`)
2380 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2381 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2382 WHERE `item`.`uid` = %d AND `verb` = '%s'
2383 AND `item`.`contact-id` = %d
2384 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2386 AND `item`.`id` > %d
2387 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2389 dbesc(ACTIVITY_POST),
2390 intval($user_info['cid']),
2396 $ret = api_format_items($r, $user_info, true, $type);
2398 $data = ['status' => $ret];
2402 $data = api_rss_extra($a, $data, $user_info);
2406 return api_format_data("statuses", $type, $data);
2409 /// @TODO move to top of file or somewhere better
2410 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2413 * Star/unstar an item.
2414 * param: id : id of the item
2416 * @param string $type Return type (atom, rss, xml, json)
2418 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2420 function api_favorites_create_destroy($type)
2424 if (api_user() === false) {
2425 throw new ForbiddenException();
2428 // for versioned api.
2429 /// @TODO We need a better global soluton
2430 $action_argv_id = 2;
2431 if ($a->argv[1] == "1.1") {
2432 $action_argv_id = 3;
2435 if ($a->argc <= $action_argv_id) {
2436 throw new BadRequestException("Invalid request.");
2438 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2439 if ($a->argc == $action_argv_id + 2) {
2440 $itemid = intval($a->argv[$action_argv_id + 1]);
2442 /// @TODO use x() to check if _REQUEST contains 'id'
2443 $itemid = intval($_REQUEST['id']);
2446 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2448 if (!DBM::is_result($item) || count($item) == 0) {
2449 throw new BadRequestException("Invalid item.");
2454 $item[0]['starred'] = 1;
2457 $item[0]['starred'] = 0;
2460 throw new BadRequestException("Invalid action ".$action);
2463 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2465 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2468 throw new InternalServerErrorException("DB error");
2472 $user_info = api_get_user($a);
2473 $rets = api_format_items($item, $user_info, false, $type);
2476 $data = ['status' => $ret];
2480 $data = api_rss_extra($a, $data, $user_info);
2483 return api_format_data("status", $type, $data);
2486 /// @TODO move to top of file or somewhere better
2487 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2488 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2491 * Returns the most recent favorite statuses.
2493 * @param string $type Return type (atom, rss, xml, json)
2495 * @return string|array
2497 function api_favorites($type)
2503 if (api_user() === false) {
2504 throw new ForbiddenException();
2509 $user_info = api_get_user($a);
2511 // in friendica starred item are private
2512 // return favorites only for self
2513 logger('api_favorites: self:' . $user_info['self']);
2515 if ($user_info['self'] == 0) {
2521 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2522 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2523 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2524 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2529 $start = $page*$count;
2532 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2536 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2537 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2538 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2539 `contact`.`id` AS `cid`
2540 FROM `item`, `contact`
2541 WHERE `item`.`uid` = %d
2542 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2543 AND `item`.`starred` = 1
2544 AND `contact`.`id` = `item`.`contact-id`
2545 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2548 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2555 $ret = api_format_items($r, $user_info, false, $type);
2558 $data = ['status' => $ret];
2562 $data = api_rss_extra($a, $data, $user_info);
2565 return api_format_data("statuses", $type, $data);
2568 /// @TODO move to top of file or somewhere better
2569 api_register_func('api/favorites', 'api_favorites', true);
2573 * @param array $item
2574 * @param array $recipient
2575 * @param array $sender
2579 function api_format_messages($item, $recipient, $sender)
2581 // standard meta information
2583 'id' => $item['id'],
2584 'sender_id' => $sender['id'] ,
2586 'recipient_id' => $recipient['id'],
2587 'created_at' => api_date($item['created']),
2588 'sender_screen_name' => $sender['screen_name'],
2589 'recipient_screen_name' => $recipient['screen_name'],
2590 'sender' => $sender,
2591 'recipient' => $recipient,
2593 'friendica_seen' => $item['seen'],
2594 'friendica_parent_uri' => $item['parent-uri'],
2597 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2598 unset($ret["sender"]["uid"]);
2599 unset($ret["sender"]["self"]);
2600 unset($ret["recipient"]["uid"]);
2601 unset($ret["recipient"]["self"]);
2603 //don't send title to regular StatusNET requests to avoid confusing these apps
2604 if (x($_GET, 'getText')) {
2605 $ret['title'] = $item['title'];
2606 if ($_GET['getText'] == 'html') {
2607 $ret['text'] = bbcode($item['body'], false, false);
2608 } elseif ($_GET['getText'] == 'plain') {
2609 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2610 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2613 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2615 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2616 unset($ret['sender']);
2617 unset($ret['recipient']);
2625 * @param array $item
2629 function api_convert_item($item)
2631 $body = $item['body'];
2632 $attachments = api_get_attachments($body);
2634 // Workaround for ostatus messages where the title is identically to the body
2635 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2636 $statusbody = trim(html2plain($html, 0));
2638 // handle data: images
2639 $statusbody = api_format_items_embeded_images($item, $statusbody);
2641 $statustitle = trim($item['title']);
2643 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2644 $statustext = trim($statusbody);
2646 $statustext = trim($statustitle."\n\n".$statusbody);
2649 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2650 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2653 $statushtml = trim(bbcode($body, false, false));
2655 // Workaround for clients with limited HTML parser functionality
2656 $search = ["<br>", "<blockquote>", "</blockquote>",
2657 "<h1>", "</h1>", "<h2>", "</h2>",
2658 "<h3>", "</h3>", "<h4>", "</h4>",
2659 "<h5>", "</h5>", "<h6>", "</h6>"];
2660 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2661 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2662 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2663 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2664 $statushtml = str_replace($search, $replace, $statushtml);
2666 if ($item['title'] != "") {
2667 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2671 $oldtext = $statushtml;
2672 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2673 } while ($oldtext != $statushtml);
2675 if (substr($statushtml, 0, 4) == '<br>') {
2676 $statushtml = substr($statushtml, 4);
2679 if (substr($statushtml, 0, -4) == '<br>') {
2680 $statushtml = substr($statushtml, -4);
2683 // feeds without body should contain the link
2684 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2685 $statushtml .= bbcode($item['plink']);
2688 $entities = api_get_entitities($statustext, $body);
2691 "text" => $statustext,
2692 "html" => $statushtml,
2693 "attachments" => $attachments,
2694 "entities" => $entities
2700 * @param string $body
2702 * @return array|false
2704 function api_get_attachments(&$body)
2707 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2709 $URLSearchString = "^\[\]";
2710 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2718 foreach ($images[1] as $image) {
2719 $imagedata = Image::getInfoFromURL($image);
2722 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2726 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2727 foreach ($images[0] as $orig) {
2728 $body = str_replace($orig, "", $body);
2732 return $attachments;
2737 * @param string $text
2738 * @param string $bbcode
2741 * @todo Links at the first character of the post
2743 function api_get_entitities(&$text, $bbcode)
2745 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2747 if ($include_entities != "true") {
2748 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2750 foreach ($images[1] as $image) {
2751 $replace = proxy_url($image);
2752 $text = str_replace($image, $replace, $text);
2757 $bbcode = bb_CleanPictureLinks($bbcode);
2759 // Change pure links in text to bbcode uris
2760 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2763 $entities["hashtags"] = [];
2764 $entities["symbols"] = [];
2765 $entities["urls"] = [];
2766 $entities["user_mentions"] = [];
2768 $URLSearchString = "^\[\]";
2770 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2772 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2773 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2774 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2776 $bbcode = preg_replace(
2777 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2778 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2781 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2783 $bbcode = preg_replace(
2784 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2785 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2788 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2790 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2792 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2793 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2796 foreach ($urls[1] as $id => $url) {
2797 //$start = strpos($text, $url, $offset);
2798 $start = iconv_strpos($text, $url, 0, "UTF-8");
2799 if (!($start === false)) {
2800 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2804 ksort($ordered_urls);
2807 //foreach ($urls[1] AS $id=>$url) {
2808 foreach ($ordered_urls as $url) {
2809 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2810 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2812 $display_url = $url["title"];
2814 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2815 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2817 if (strlen($display_url) > 26) {
2818 $display_url = substr($display_url, 0, 25)."…";
2822 //$start = strpos($text, $url, $offset);
2823 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2824 if (!($start === false)) {
2825 $entities["urls"][] = ["url" => $url["url"],
2826 "expanded_url" => $url["url"],
2827 "display_url" => $display_url,
2828 "indices" => [$start, $start+strlen($url["url"])]];
2829 $offset = $start + 1;
2833 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2834 $ordered_images = [];
2835 foreach ($images[1] as $image) {
2836 //$start = strpos($text, $url, $offset);
2837 $start = iconv_strpos($text, $image, 0, "UTF-8");
2838 if (!($start === false)) {
2839 $ordered_images[$start] = $image;
2842 //$entities["media"] = array();
2845 foreach ($ordered_images as $url) {
2846 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2847 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2849 if (strlen($display_url) > 26) {
2850 $display_url = substr($display_url, 0, 25)."…";
2853 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2854 if (!($start === false)) {
2855 $image = Image::getInfoFromURL($url);
2857 // If image cache is activated, then use the following sizes:
2858 // thumb (150), small (340), medium (600) and large (1024)
2859 if (!Config::get("system", "proxy_disabled")) {
2860 $media_url = proxy_url($url);
2863 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2864 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2866 if (($image[0] > 150) || ($image[1] > 150)) {
2867 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2868 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2871 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2872 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2874 if (($image[0] > 600) || ($image[1] > 600)) {
2875 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2876 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2880 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2883 $entities["media"][] = [
2885 "id_str" => (string)$start+1,
2886 "indices" => [$start, $start+strlen($url)],
2887 "media_url" => normalise_link($media_url),
2888 "media_url_https" => $media_url,
2890 "display_url" => $display_url,
2891 "expanded_url" => $url,
2895 $offset = $start + 1;
2904 * @param array $item
2905 * @param string $text
2909 function api_format_items_embeded_images($item, $text)
2911 $text = preg_replace_callback(
2912 '|data:image/([^;]+)[^=]+=*|m',
2913 function () use ($item) {
2914 return System::baseUrl() . '/display/' . $item['guid'];
2922 * @brief return <a href='url'>name</a> as array
2924 * @param string $txt text
2929 function api_contactlink_to_array($txt)
2932 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2933 if ($r && count($match)==3) {
2935 'name' => $match[2],
2949 * @brief return likes, dislikes and attend status for item
2951 * @param array $item array
2952 * @param string $type Return type (atom, rss, xml, json)
2955 * likes => int count,
2956 * dislikes => int count
2958 function api_format_items_activities(&$item, $type = "json")
2967 'attendmaybe' => [],
2972 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2973 intval($item['uid']),
2977 foreach ($items as $i) {
2978 // not used as result should be structured like other user data
2979 //builtin_activity_puller($i, $activities);
2981 // get user data and add it to the array of the activity
2982 $user = api_get_user($a, $i['author-link']);
2983 switch ($i['verb']) {
2985 $activities['like'][] = $user;
2987 case ACTIVITY_DISLIKE:
2988 $activities['dislike'][] = $user;
2990 case ACTIVITY_ATTEND:
2991 $activities['attendyes'][] = $user;
2993 case ACTIVITY_ATTENDNO:
2994 $activities['attendno'][] = $user;
2996 case ACTIVITY_ATTENDMAYBE:
2997 $activities['attendmaybe'][] = $user;
3004 if ($type == "xml") {
3005 $xml_activities = [];
3006 foreach ($activities as $k => $v) {
3007 // change xml element from "like" to "friendica:like"
3008 $xml_activities["friendica:".$k] = $v;
3009 // add user data into xml output
3011 foreach ($v as $user) {
3012 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
3015 $activities = $xml_activities;
3023 * @brief return data from profiles
3025 * @param array $profile_row array containing data from db table 'profile'
3028 function api_format_items_profiles($profile_row)
3031 'profile_id' => $profile_row['id'],
3032 'profile_name' => $profile_row['profile-name'],
3033 'is_default' => $profile_row['is-default'] ? true : false,
3034 'hide_friends' => $profile_row['hide-friends'] ? true : false,
3035 'profile_photo' => $profile_row['photo'],
3036 'profile_thumb' => $profile_row['thumb'],
3037 'publish' => $profile_row['publish'] ? true : false,
3038 'net_publish' => $profile_row['net-publish'] ? true : false,
3039 'description' => $profile_row['pdesc'],
3040 'date_of_birth' => $profile_row['dob'],
3041 'address' => $profile_row['address'],
3042 'city' => $profile_row['locality'],
3043 'region' => $profile_row['region'],
3044 'postal_code' => $profile_row['postal-code'],
3045 'country' => $profile_row['country-name'],
3046 'hometown' => $profile_row['hometown'],
3047 'gender' => $profile_row['gender'],
3048 'marital' => $profile_row['marital'],
3049 'marital_with' => $profile_row['with'],
3050 'marital_since' => $profile_row['howlong'],
3051 'sexual' => $profile_row['sexual'],
3052 'politic' => $profile_row['politic'],
3053 'religion' => $profile_row['religion'],
3054 'public_keywords' => $profile_row['pub_keywords'],
3055 'private_keywords' => $profile_row['prv_keywords'],
3056 'likes' => bbcode(api_clean_plain_items($profile_row['likes']) , false, false, 2, false),
3057 'dislikes' => bbcode(api_clean_plain_items($profile_row['dislikes']) , false, false, 2, false),
3058 'about' => bbcode(api_clean_plain_items($profile_row['about']) , false, false, 2, false),
3059 'music' => bbcode(api_clean_plain_items($profile_row['music']) , false, false, 2, false),
3060 'book' => bbcode(api_clean_plain_items($profile_row['book']) , false, false, 2, false),
3061 'tv' => bbcode(api_clean_plain_items($profile_row['tv']) , false, false, 2, false),
3062 'film' => bbcode(api_clean_plain_items($profile_row['film']) , false, false, 2, false),
3063 'interest' => bbcode(api_clean_plain_items($profile_row['interest']) , false, false, 2, false),
3064 'romance' => bbcode(api_clean_plain_items($profile_row['romance']) , false, false, 2, false),
3065 'work' => bbcode(api_clean_plain_items($profile_row['work']) , false, false, 2, false),
3066 'education' => bbcode(api_clean_plain_items($profile_row['education']), false, false, 2, false),
3067 'social_networks' => bbcode(api_clean_plain_items($profile_row['contact']) , false, false, 2, false),
3068 'homepage' => $profile_row['homepage'],
3075 * @brief format items to be returned by api
3077 * @param array $r array of items
3078 * @param array $user_info
3079 * @param bool $filter_user filter items by $user_info
3080 * @param string $type Return type (atom, rss, xml, json)
3082 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
3088 foreach ($r as $item) {
3089 localize_item($item);
3090 list($status_user, $owner_user) = api_item_get_user($a, $item);
3092 // Look if the posts are matching if they should be filtered by user id
3093 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3097 $in_reply_to = api_in_reply_to($item);
3099 $converted = api_convert_item($item);
3101 if ($type == "xml") {
3102 $geo = "georss:point";
3108 'text' => $converted["text"],
3109 'truncated' => false,
3110 'created_at'=> api_date($item['created']),
3111 'in_reply_to_status_id' => $in_reply_to['status_id'],
3112 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3113 'source' => (($item['app']) ? $item['app'] : 'web'),
3114 'id' => intval($item['id']),
3115 'id_str' => (string) intval($item['id']),
3116 'in_reply_to_user_id' => $in_reply_to['user_id'],
3117 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3118 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3120 'favorited' => $item['starred'] ? true : false,
3121 'user' => $status_user ,
3122 'friendica_owner' => $owner_user,
3123 //'entities' => NULL,
3124 'statusnet_html' => $converted["html"],
3125 'statusnet_conversation_id' => $item['parent'],
3126 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3127 'friendica_activities' => api_format_items_activities($item, $type),
3130 if (count($converted["attachments"]) > 0) {
3131 $status["attachments"] = $converted["attachments"];
3134 if (count($converted["entities"]) > 0) {
3135 $status["entities"] = $converted["entities"];
3138 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
3139 $status["source"] = ContactSelector::networkToName($item['item_network'], $user_info['url']);
3140 } elseif (($item['item_network'] != "") && (ContactSelector::networkToName($item['item_network'], $user_info['url']) != $status["source"])) {
3141 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['item_network'], $user_info['url']).')');
3145 // Retweets are only valid for top postings
3146 // It doesn't work reliable with the link if its a feed
3147 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
3149 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
3152 if ($item["id"] == $item["parent"]) {
3153 $retweeted_item = api_share_as_retweet($item);
3154 if ($retweeted_item !== false) {
3155 $retweeted_status = $status;
3157 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
3158 } catch (BadRequestException $e) {
3159 // user not found. should be found?
3160 /// @todo check if the user should be always found
3161 $retweeted_status["user"] = [];
3164 $rt_converted = api_convert_item($retweeted_item);
3166 $retweeted_status['text'] = $rt_converted["text"];
3167 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3168 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3169 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3170 $status['retweeted_status'] = $retweeted_status;
3174 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3175 unset($status["user"]["uid"]);
3176 unset($status["user"]["self"]);
3178 if ($item["coord"] != "") {
3179 $coords = explode(' ', $item["coord"]);
3180 if (count($coords) == 2) {
3181 if ($type == "json") {
3182 $status["geo"] = ['type' => 'Point',
3183 'coordinates' => [(float) $coords[0],
3184 (float) $coords[1]]];
3185 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3186 $status["georss:point"] = $item["coord"];
3196 * Returns the remaining number of API requests available to the user before the API limit is reached.
3198 * @param string $type Return type (atom, rss, xml, json)
3200 * @return array|string
3202 function api_account_rate_limit_status($type)
3204 if ($type == "xml") {
3206 'remaining-hits' => '150',
3207 '@attributes' => ["type" => "integer"],
3208 'hourly-limit' => '150',
3209 '@attributes2' => ["type" => "integer"],
3210 'reset-time' => Temporal::convert('now + 1 hour', 'UTC', 'UTC', Temporal::ATOM),
3211 '@attributes3' => ["type" => "datetime"],
3212 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3213 '@attributes4' => ["type" => "integer"],
3217 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3218 'remaining_hits' => '150',
3219 'hourly_limit' => '150',
3220 'reset_time' => api_date(Temporal::convert('now + 1 hour', 'UTC', 'UTC', Temporal::ATOM)),
3224 return api_format_data('hash', $type, ['hash' => $hash]);
3227 /// @TODO move to top of file or somewhere better
3228 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3231 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3233 * @param string $type Return type (atom, rss, xml, json)
3235 * @return array|string
3237 function api_help_test($type)
3239 if ($type == 'xml') {
3245 return api_format_data('ok', $type, ["ok" => $ok]);
3248 /// @TODO move to top of file or somewhere better
3249 api_register_func('api/help/test', 'api_help_test', false);
3253 * @param string $type Return type (atom, rss, xml, json)
3255 * @return array|string
3257 function api_lists($type)
3260 /// @TODO $ret is not filled here?
3261 return api_format_data('lists', $type, ["lists_list" => $ret]);
3264 /// @TODO move to top of file or somewhere better
3265 api_register_func('api/lists', 'api_lists', true);
3268 * Returns all lists the user subscribes to.
3270 * @param string $type Return type (atom, rss, xml, json)
3272 * @return array|string
3273 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3275 function api_lists_list($type)
3278 /// @TODO $ret is not filled here?
3279 return api_format_data('lists', $type, ["lists_list" => $ret]);
3282 /// @TODO move to top of file or somewhere better
3283 api_register_func('api/lists/list', 'api_lists_list', true);
3286 * Considers friends and followers lists to be private and won't return
3287 * anything if any user_id parameter is passed.
3289 * @brief Returns either the friends of the follower list
3291 * @param string $qtype Either "friends" or "followers"
3292 * @return boolean|array
3293 * @throws ForbiddenException
3295 function api_statuses_f($qtype)
3299 if (api_user() === false) {
3300 throw new ForbiddenException();
3304 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3305 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3309 $start = ($page - 1) * $count;
3311 $user_info = api_get_user($a);
3313 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3314 /* this is to stop Hotot to load friends multiple times
3315 * I'm not sure if I'm missing return something or
3316 * is a bug in hotot. Workaround, meantime
3320 return array('$users' => $ret);*/
3325 if ($qtype == 'friends') {
3326 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3327 } elseif ($qtype == 'followers') {
3328 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3331 // friends and followers only for self
3332 if ($user_info['self'] == 0) {
3333 $sql_extra = " AND false ";
3336 if ($qtype == 'blocks') {
3337 $sql_filter = 'AND `blocked` AND NOT `pending`';
3338 } elseif ($qtype == 'incoming') {
3339 $sql_filter = 'AND `pending`';
3341 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3359 foreach ($r as $cid) {
3360 $user = api_get_user($a, $cid['nurl']);
3361 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3362 unset($user["uid"]);
3363 unset($user["self"]);
3370 return ['user' => $ret];
3375 * Returns the user's friends.
3377 * @brief Returns the list of friends of the provided user
3379 * @deprecated By Twitter API in favor of friends/list
3381 * @param string $type Either "json" or "xml"
3382 * @return boolean|string|array
3384 function api_statuses_friends($type)
3386 $data = api_statuses_f("friends");
3387 if ($data === false) {
3390 return api_format_data("users", $type, $data);
3394 * Returns the user's followers.
3396 * @brief Returns the list of followers of the provided user
3398 * @deprecated By Twitter API in favor of friends/list
3400 * @param string $type Either "json" or "xml"
3401 * @return boolean|string|array
3403 function api_statuses_followers($type)
3405 $data = api_statuses_f("followers");
3406 if ($data === false) {
3409 return api_format_data("users", $type, $data);
3412 /// @TODO move to top of file or somewhere better
3413 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3414 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3417 * Returns the list of blocked users
3419 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3421 * @param string $type Either "json" or "xml"
3423 * @return boolean|string|array
3425 function api_blocks_list($type)
3427 $data = api_statuses_f('blocks');
3428 if ($data === false) {
3431 return api_format_data("users", $type, $data);
3434 /// @TODO move to top of file or somewhere better
3435 api_register_func('api/blocks/list', 'api_blocks_list', true);
3438 * Returns the list of pending users IDs
3440 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3442 * @param string $type Either "json" or "xml"
3444 * @return boolean|string|array
3446 function api_friendships_incoming($type)
3448 $data = api_statuses_f('incoming');
3449 if ($data === false) {
3454 foreach ($data['user'] as $user) {
3455 $ids[] = $user['id'];
3458 return api_format_data("ids", $type, ['id' => $ids]);
3461 /// @TODO move to top of file or somewhere better
3462 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3465 * Returns the instance's configuration information.
3467 * @param string $type Return type (atom, rss, xml, json)
3469 * @return array|string
3471 function api_statusnet_config($type)
3475 $name = $a->config['sitename'];
3476 $server = $a->get_hostname();
3477 $logo = System::baseUrl() . '/images/friendica-64.png';
3478 $email = $a->config['admin_email'];
3479 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3480 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3481 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3482 if ($a->config['api_import_size']) {
3483 $textlimit = (string) $a->config['api_import_size'];
3485 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3486 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3489 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3490 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3491 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3492 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3493 'shorturllength' => '30',
3495 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3496 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3497 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3498 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3503 return api_format_data('config', $type, ['config' => $config]);
3506 /// @TODO move to top of file or somewhere better
3507 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3508 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3512 * @param string $type Return type (atom, rss, xml, json)
3514 * @return array|string
3516 function api_statusnet_version($type)
3519 $fake_statusnet_version = "0.9.7";
3521 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3524 /// @TODO move to top of file or somewhere better
3525 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3526 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3530 * @param string $type Return type (atom, rss, xml, json)
3532 * @todo use api_format_data() to return data
3534 function api_ff_ids($type)
3537 throw new ForbiddenException();
3542 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3545 "SELECT `pcontact`.`id` FROM `contact`
3546 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3547 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3550 if (!DBM::is_result($r)) {
3555 foreach ($r as $rr) {
3556 if ($stringify_ids) {
3559 $ids[] = intval($rr['id']);
3563 return api_format_data("ids", $type, ['id' => $ids]);
3567 * Returns the ID of every user the user is following.
3569 * @param string $type Return type (atom, rss, xml, json)
3571 * @return array|string
3572 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3574 function api_friends_ids($type)
3576 return api_ff_ids($type);
3580 * Returns the ID of every user following the user.
3582 * @param string $type Return type (atom, rss, xml, json)
3584 * @return array|string
3585 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3587 function api_followers_ids($type)
3589 return api_ff_ids($type);
3592 /// @TODO move to top of file or somewhere better
3593 api_register_func('api/friends/ids', 'api_friends_ids', true);
3594 api_register_func('api/followers/ids', 'api_followers_ids', true);
3597 * Sends a new direct message.
3599 * @param string $type Return type (atom, rss, xml, json)
3601 * @return array|string
3602 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3604 function api_direct_messages_new($type)
3609 if (api_user() === false) {
3610 throw new ForbiddenException();
3613 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3617 $sender = api_get_user($a);
3619 if ($_POST['screen_name']) {
3621 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3623 dbesc($_POST['screen_name'])
3626 // Selecting the id by priority, friendica first
3627 api_best_nickname($r);
3629 $recipient = api_get_user($a, $r[0]['nurl']);
3631 $recipient = api_get_user($a, $_POST['user_id']);
3636 if (x($_REQUEST, 'replyto')) {
3638 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3640 intval($_REQUEST['replyto'])
3642 $replyto = $r[0]['parent-uri'];
3643 $sub = $r[0]['title'];
3645 if (x($_REQUEST, 'title')) {
3646 $sub = $_REQUEST['title'];
3648 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3652 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3655 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3656 $ret = api_format_messages($r[0], $recipient, $sender);
3658 $ret = ["error"=>$id];
3661 $data = ['direct_message'=>$ret];
3666 $data = api_rss_extra($a, $data, $user_info);
3669 return api_format_data("direct-messages", $type, $data);
3672 /// @TODO move to top of file or somewhere better
3673 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3676 * Destroys a direct message.
3678 * @brief delete a direct_message from mail table through api
3680 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3682 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3684 function api_direct_messages_destroy($type)
3688 if (api_user() === false) {
3689 throw new ForbiddenException();
3693 $user_info = api_get_user($a);
3695 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3697 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3698 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3699 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3701 $uid = $user_info['uid'];
3702 // error if no id or parenturi specified (for clients posting parent-uri as well)
3703 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3704 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3705 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3708 // BadRequestException if no id specified (for clients using Twitter API)
3710 throw new BadRequestException('Message id not specified');
3713 // add parent-uri to sql command if specified by calling app
3714 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3716 // get data of the specified message id
3718 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3723 // error message if specified id is not in database
3724 if (!DBM::is_result($r)) {
3725 if ($verbose == "true") {
3726 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3727 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3729 /// @todo BadRequestException ok for Twitter API clients?
3730 throw new BadRequestException('message id not in database');
3735 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3740 if ($verbose == "true") {
3743 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3744 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3746 $answer = ['result' => 'error', 'message' => 'unknown error'];
3747 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3750 /// @todo return JSON data like Twitter API not yet implemented
3753 /// @TODO move to top of file or somewhere better
3754 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3758 * @param string $type Return type (atom, rss, xml, json)
3759 * @param string $box
3760 * @param string $verbose
3762 * @return array|string
3764 function api_direct_messages_box($type, $box, $verbose)
3768 if (api_user() === false) {
3769 throw new ForbiddenException();
3773 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3774 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3779 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3780 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3782 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3783 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3786 unset($_REQUEST["user_id"]);
3787 unset($_GET["user_id"]);
3789 unset($_REQUEST["screen_name"]);
3790 unset($_GET["screen_name"]);
3792 $user_info = api_get_user($a);
3793 $profile_url = $user_info["url"];
3796 $start = $page * $count;
3799 if ($box=="sentbox") {
3800 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3801 } elseif ($box == "conversation") {
3802 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3803 } elseif ($box == "all") {
3804 $sql_extra = "true";
3805 } elseif ($box == "inbox") {
3806 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3810 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3813 if ($user_id != "") {
3814 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3815 } elseif ($screen_name !="") {
3816 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3820 "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",
3826 if ($verbose == "true" && !DBM::is_result($r)) {
3827 $answer = ['result' => 'error', 'message' => 'no mails available'];
3828 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3832 foreach ($r as $item) {
3833 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3834 $recipient = $user_info;
3835 $sender = api_get_user($a, normalise_link($item['contact-url']));
3836 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3837 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3838 $sender = $user_info;
3841 $ret[] = api_format_messages($item, $recipient, $sender);
3845 $data = ['direct_message' => $ret];
3849 $data = api_rss_extra($a, $data, $user_info);
3852 return api_format_data("direct-messages", $type, $data);
3856 * Returns the most recent direct messages sent by the user.
3858 * @param string $type Return type (atom, rss, xml, json)
3860 * @return array|string
3861 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3863 function api_direct_messages_sentbox($type)
3865 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3866 return api_direct_messages_box($type, "sentbox", $verbose);
3870 * Returns the most recent direct messages sent to the user.
3872 * @param string $type Return type (atom, rss, xml, json)
3874 * @return array|string
3875 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3877 function api_direct_messages_inbox($type)
3879 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3880 return api_direct_messages_box($type, "inbox", $verbose);
3885 * @param string $type Return type (atom, rss, xml, json)
3887 * @return array|string
3889 function api_direct_messages_all($type)
3891 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3892 return api_direct_messages_box($type, "all", $verbose);
3897 * @param string $type Return type (atom, rss, xml, json)
3899 * @return array|string
3901 function api_direct_messages_conversation($type)
3903 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3904 return api_direct_messages_box($type, "conversation", $verbose);
3907 /// @TODO move to top of file or somewhere better
3908 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3909 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3910 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3911 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3914 * Returns an OAuth Request Token.
3916 * @see https://oauth.net/core/1.0/#auth_step1
3918 function api_oauth_request_token()
3920 $oauth1 = new FKOAuth1();
3922 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3923 } catch (Exception $e) {
3924 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3932 * Returns an OAuth Access Token.
3934 * @return array|string
3935 * @see https://oauth.net/core/1.0/#auth_step3
3937 function api_oauth_access_token()
3939 $oauth1 = new FKOAuth1();
3941 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3942 } catch (Exception $e) {
3943 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3950 /// @TODO move to top of file or somewhere better
3951 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3952 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3956 * @brief delete a complete photoalbum with all containing photos from database through api
3958 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3961 function api_fr_photoalbum_delete($type)
3963 if (api_user() === false) {
3964 throw new ForbiddenException();
3967 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3969 // we do not allow calls without album string
3971 throw new BadRequestException("no albumname specified");
3973 // check if album is existing
3975 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3979 if (!DBM::is_result($r)) {
3980 throw new BadRequestException("album not available");
3983 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3984 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3985 foreach ($r as $rr) {
3987 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3988 intval(local_user()),
3989 dbesc($rr['resource-id'])
3992 if (!DBM::is_result($photo_item)) {
3993 throw new InternalServerErrorException("problem with deleting items occured");
3995 Item::delete($photo_item[0]['id']);
3998 // now let's delete all photos from the album
3999 $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
4001 // return success of deletion or error message
4003 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4004 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4006 throw new InternalServerErrorException("unknown error - deleting from database failed");
4011 * @brief update the name of the album for all photos of an album
4013 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4016 function api_fr_photoalbum_update($type)
4018 if (api_user() === false) {
4019 throw new ForbiddenException();
4022 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
4023 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
4025 // we do not allow calls without album string
4027 throw new BadRequestException("no albumname specified");
4029 if ($album_new == "") {
4030 throw new BadRequestException("no new albumname specified");
4032 // check if album is existing
4034 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4038 if (!DBM::is_result($r)) {
4039 throw new BadRequestException("album not available");
4041 // now let's update all photos to the albumname
4043 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
4049 // return success of updating or error message
4051 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4052 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4054 throw new InternalServerErrorException("unknown error - updating in database failed");
4060 * @brief list all photos of the authenticated user
4062 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4065 function api_fr_photos_list($type)
4067 if (api_user() === false) {
4068 throw new ForbiddenException();
4071 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4072 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4073 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4074 intval(local_user())
4077 'image/jpeg' => 'jpg',
4078 'image/png' => 'png',
4079 'image/gif' => 'gif'
4081 $data = ['photo'=>[]];
4082 if (DBM::is_result($r)) {
4083 foreach ($r as $rr) {
4085 $photo['id'] = $rr['resource-id'];
4086 $photo['album'] = $rr['album'];
4087 $photo['filename'] = $rr['filename'];
4088 $photo['type'] = $rr['type'];
4089 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4090 $photo['created'] = $rr['created'];
4091 $photo['edited'] = $rr['edited'];
4092 $photo['desc'] = $rr['desc'];
4094 if ($type == "xml") {
4095 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4097 $photo['thumb'] = $thumb;
4098 $data['photo'][] = $photo;
4102 return api_format_data("photos", $type, $data);
4106 * @brief upload a new photo or change an existing photo
4108 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4111 function api_fr_photo_create_update($type)
4113 if (api_user() === false) {
4114 throw new ForbiddenException();
4117 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4118 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4119 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4120 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4121 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4122 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4123 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4124 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4125 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4127 // do several checks on input parameters
4128 // we do not allow calls without album string
4129 if ($album == null) {
4130 throw new BadRequestException("no albumname specified");
4132 // if photo_id == null --> we are uploading a new photo
4133 if ($photo_id == null) {
4136 // error if no media posted in create-mode
4137 if (!x($_FILES, 'media')) {
4139 throw new BadRequestException("no media data submitted");
4142 // album_new will be ignored in create-mode
4147 // check if photo is existing in database
4149 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4154 if (!DBM::is_result($r)) {
4155 throw new BadRequestException("photo not available");
4159 // checks on acl strings provided by clients
4160 $acl_input_error = false;
4161 $acl_input_error |= check_acl_input($allow_cid);
4162 $acl_input_error |= check_acl_input($deny_cid);
4163 $acl_input_error |= check_acl_input($allow_gid);
4164 $acl_input_error |= check_acl_input($deny_gid);
4165 if ($acl_input_error) {
4166 throw new BadRequestException("acl data invalid");
4168 // now let's upload the new media in create-mode
4169 if ($mode == "create") {
4170 $media = $_FILES['media'];
4171 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4173 // return success of updating or error message
4174 if (!is_null($data)) {
4175 return api_format_data("photo_create", $type, $data);
4177 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4181 // now let's do the changes in update-mode
4182 if ($mode == "update") {
4185 if (!is_null($desc)) {
4186 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4189 if (!is_null($album_new)) {
4190 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4193 if (!is_null($allow_cid)) {
4194 $allow_cid = trim($allow_cid);
4195 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4198 if (!is_null($deny_cid)) {
4199 $deny_cid = trim($deny_cid);
4200 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4203 if (!is_null($allow_gid)) {
4204 $allow_gid = trim($allow_gid);
4205 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4208 if (!is_null($deny_gid)) {
4209 $deny_gid = trim($deny_gid);
4210 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4214 if ($sql_extra != "") {
4215 $nothingtodo = false;
4217 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4219 Temporal::convert(), // update edited timestamp
4225 $nothingtodo = true;
4228 if (x($_FILES, 'media')) {
4229 $nothingtodo = false;
4230 $media = $_FILES['media'];
4231 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4232 if (!is_null($data)) {
4233 return api_format_data("photo_update", $type, $data);
4237 // return success of updating or error message
4239 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4240 return api_format_data("photo_update", $type, ['$result' => $answer]);
4243 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4244 return api_format_data("photo_update", $type, ['$result' => $answer]);
4246 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4249 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4254 * @brief delete a single photo from the database through api
4256 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4259 function api_fr_photo_delete($type)
4261 if (api_user() === false) {
4262 throw new ForbiddenException();
4265 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4267 // do several checks on input parameters
4268 // we do not allow calls without photo id
4269 if ($photo_id == null) {
4270 throw new BadRequestException("no photo_id specified");
4272 // check if photo is existing in database
4274 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4278 if (!DBM::is_result($r)) {
4279 throw new BadRequestException("photo not available");
4281 // now we can perform on the deletion of the photo
4282 $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4284 // return success of deletion or error message
4286 // retrieve the id of the parent element (the photo element)
4288 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4289 intval(local_user()),
4293 if (!DBM::is_result($photo_item)) {
4294 throw new InternalServerErrorException("problem with deleting items occured");
4296 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4297 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4298 Item::delete($photo_item[0]['id']);
4300 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4301 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4303 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4309 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4311 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4312 * @return string|array
4314 function api_fr_photo_detail($type)
4316 if (api_user() === false) {
4317 throw new ForbiddenException();
4319 if (!x($_REQUEST, 'photo_id')) {
4320 throw new BadRequestException("No photo id.");
4323 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4324 $photo_id = $_REQUEST['photo_id'];
4326 // prepare json/xml output with data from database for the requested photo
4327 $data = prepare_photo_data($type, $scale, $photo_id);
4329 return api_format_data("photo_detail", $type, $data);
4334 * Updates the user’s profile image.
4336 * @brief updates the profile image for the user (either a specified profile or the default profile)
4338 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4341 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4343 function api_account_update_profile_image($type)
4345 if (api_user() === false) {
4346 throw new ForbiddenException();
4349 $profileid = defaults($_REQUEST, 'profile_id', 0);
4351 // error if image data is missing
4352 if (!x($_FILES, 'image')) {
4353 throw new BadRequestException("no media data submitted");
4356 // check if specified profile id is valid
4357 if ($profileid != 0) {
4359 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4363 // error message if specified profile id is not in database
4364 if (!DBM::is_result($r)) {
4365 throw new BadRequestException("profile_id not available");
4367 $is_default_profile = $r['profile'];
4369 $is_default_profile = 1;
4372 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4374 if (x($_FILES, 'image')) {
4375 $media = $_FILES['image'];
4376 } elseif (x($_FILES, 'media')) {
4377 $media = $_FILES['media'];
4379 // save new profile image
4380 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4383 if (is_array($media['type'])) {
4384 $filetype = $media['type'][0];
4386 $filetype = $media['type'];
4388 if ($filetype == "image/jpeg") {
4390 } elseif ($filetype == "image/png") {
4393 // change specified profile or all profiles to the new resource-id
4394 if ($is_default_profile) {
4396 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4397 dbesc($data['photo']['id']),
4398 intval(local_user())
4402 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
4403 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4404 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4405 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4406 intval(local_user())
4410 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4411 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4412 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4413 intval($_REQUEST['profile']),
4414 intval(local_user())
4418 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4419 // so that browsers will do a cache update unconditionally
4422 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4423 dbesc(Temporal::convert()),
4424 intval(local_user())
4427 // Update global directory in background
4428 //$user = api_get_user(get_app());
4429 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4430 if ($url && strlen(Config::get('system', 'directory'))) {
4431 Worker::add(PRIORITY_LOW, "Directory", $url);
4434 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4436 // output for client
4438 return api_account_verify_credentials($type);
4440 // SaveMediaToDatabase failed for some reason
4441 throw new InternalServerErrorException("image upload failed");
4445 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4446 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4447 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4448 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4449 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4450 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4451 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4452 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4453 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4456 * Update user profile
4458 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4460 * @return array|string
4462 function api_account_update_profile($type)
4464 $local_user = api_user();
4465 $api_user = api_get_user(get_app());
4467 if (!empty($_POST['name'])) {
4468 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4469 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4470 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4471 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4474 if (isset($_POST['description'])) {
4475 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4476 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4477 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4480 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4481 // Update global directory in background
4482 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4483 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4486 return api_account_verify_credentials($type);
4489 /// @TODO move to top of file or somewhere better
4490 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4494 * @param string $acl_string
4496 function check_acl_input($acl_string)
4498 if ($acl_string == null || $acl_string == " ") {
4501 $contact_not_found = false;
4503 // split <x><y><z> into array of cid's
4504 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4506 // check for each cid if it is available on server
4507 $cid_array = $array[0];
4508 foreach ($cid_array as $cid) {
4509 $cid = str_replace("<", "", $cid);
4510 $cid = str_replace(">", "", $cid);
4512 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4516 $contact_not_found |= !DBM::is_result($contact);
4518 return $contact_not_found;
4523 * @param string $mediatype
4524 * @param array $media
4525 * @param string $type
4526 * @param string $album
4527 * @param string $allow_cid
4528 * @param string $deny_cid
4529 * @param string $allow_gid
4530 * @param string $deny_gid
4531 * @param string $desc
4532 * @param integer $profile
4533 * @param boolean $visibility
4534 * @param string $photo_id
4536 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)
4544 if (is_array($media)) {
4545 if (is_array($media['tmp_name'])) {
4546 $src = $media['tmp_name'][0];
4548 $src = $media['tmp_name'];
4550 if (is_array($media['name'])) {
4551 $filename = basename($media['name'][0]);
4553 $filename = basename($media['name']);
4555 if (is_array($media['size'])) {
4556 $filesize = intval($media['size'][0]);
4558 $filesize = intval($media['size']);
4560 if (is_array($media['type'])) {
4561 $filetype = $media['type'][0];
4563 $filetype = $media['type'];
4567 if ($filetype == "") {
4568 $filetype=Image::guessType($filename);
4570 $imagedata = getimagesize($src);
4572 $filetype = $imagedata['mime'];
4575 "File upload src: " . $src . " - filename: " . $filename .
4576 " - size: " . $filesize . " - type: " . $filetype,
4580 // check if there was a php upload error
4581 if ($filesize == 0 && $media['error'] == 1) {
4582 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4584 // check against max upload size within Friendica instance
4585 $maximagesize = Config::get('system', 'maximagesize');
4586 if ($maximagesize && ($filesize > $maximagesize)) {
4587 $formattedBytes = formatBytes($maximagesize);
4588 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4591 // create Photo instance with the data of the image
4592 $imagedata = @file_get_contents($src);
4593 $Image = new Image($imagedata, $filetype);
4594 if (! $Image->isValid()) {
4595 throw new InternalServerErrorException("unable to process image data");
4598 // check orientation of image
4599 $Image->orient($src);
4602 // check max length of images on server
4603 $max_length = Config::get('system', 'max_image_length');
4604 if (! $max_length) {
4605 $max_length = MAX_IMAGE_LENGTH;
4607 if ($max_length > 0) {
4608 $Image->scaleDown($max_length);
4609 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4611 $width = $Image->getWidth();
4612 $height = $Image->getHeight();
4614 // create a new resource-id if not already provided
4615 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
4617 if ($mediatype == "photo") {
4618 // upload normal image (scales 0, 1, 2)
4619 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4621 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4623 logger("photo upload: image upload with scale 0 (original size) failed");
4625 if ($width > 640 || $height > 640) {
4626 $Image->scaleDown(640);
4627 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4629 logger("photo upload: image upload with scale 1 (640x640) failed");
4633 if ($width > 320 || $height > 320) {
4634 $Image->scaleDown(320);
4635 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4637 logger("photo upload: image upload with scale 2 (320x320) failed");
4640 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4641 } elseif ($mediatype == "profileimage") {
4642 // upload profile image (scales 4, 5, 6)
4643 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4645 if ($width > 175 || $height > 175) {
4646 $Image->scaleDown(175);
4647 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4649 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4653 if ($width > 80 || $height > 80) {
4654 $Image->scaleDown(80);
4655 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4657 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4661 if ($width > 48 || $height > 48) {
4662 $Image->scaleDown(48);
4663 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4665 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4668 $Image->__destruct();
4669 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4673 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4674 if ($photo_id == null && $mediatype == "photo") {
4675 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4677 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4678 return prepare_photo_data($type, false, $hash);
4680 throw new InternalServerErrorException("image upload failed");
4686 * @param string $hash
4687 * @param string $allow_cid
4688 * @param string $deny_cid
4689 * @param string $allow_gid
4690 * @param string $deny_gid
4691 * @param string $filetype
4692 * @param boolean $visibility
4694 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4696 // get data about the api authenticated user
4697 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4698 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4701 $arr['guid'] = get_guid(32);
4702 $arr['uid'] = intval(api_user());
4704 $arr['parent-uri'] = $uri;
4705 $arr['type'] = 'photo';
4707 $arr['resource-id'] = $hash;
4708 $arr['contact-id'] = $owner_record[0]['id'];
4709 $arr['owner-name'] = $owner_record[0]['name'];
4710 $arr['owner-link'] = $owner_record[0]['url'];
4711 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4712 $arr['author-name'] = $owner_record[0]['name'];
4713 $arr['author-link'] = $owner_record[0]['url'];
4714 $arr['author-avatar'] = $owner_record[0]['thumb'];
4716 $arr['allow_cid'] = $allow_cid;
4717 $arr['allow_gid'] = $allow_gid;
4718 $arr['deny_cid'] = $deny_cid;
4719 $arr['deny_gid'] = $deny_gid;
4720 $arr['visible'] = $visibility;
4724 'image/jpeg' => 'jpg',
4725 'image/png' => 'png',
4726 'image/gif' => 'gif'
4729 // adds link to the thumbnail scale photo
4730 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4731 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4734 // do the magic for storing the item in the database and trigger the federation to other contacts
4740 * @param string $type
4742 * @param string $photo_id
4746 function prepare_photo_data($type, $scale, $photo_id)
4748 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4749 $data_sql = ($scale === false ? "" : "data, ");
4751 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4752 // clients needs to convert this in their way for further processing
4754 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4755 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4756 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4757 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4759 intval(local_user()),
4765 'image/jpeg' => 'jpg',
4766 'image/png' => 'png',
4767 'image/gif' => 'gif'
4770 // prepare output data for photo
4771 if (DBM::is_result($r)) {
4772 $data = ['photo' => $r[0]];
4773 $data['photo']['id'] = $data['photo']['resource-id'];
4774 if ($scale !== false) {
4775 $data['photo']['data'] = base64_encode($data['photo']['data']);
4777 unset($data['photo']['datasize']); //needed only with scale param
4779 if ($type == "xml") {
4780 $data['photo']['links'] = [];
4781 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4782 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4784 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4787 $data['photo']['link'] = [];
4788 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4790 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4791 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4795 unset($data['photo']['resource-id']);
4796 unset($data['photo']['minscale']);
4797 unset($data['photo']['maxscale']);
4799 throw new NotFoundException();
4802 // retrieve item element for getting activities (like, dislike etc.) related to photo
4804 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4805 intval(local_user()),
4808 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4810 // retrieve comments on photo
4812 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4813 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4814 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4815 `contact`.`id` AS `cid`
4817 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4818 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4819 WHERE `item`.`parent` = %d AND `item`.`visible`
4820 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4821 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4822 intval($item[0]['parent']),
4824 dbesc(ACTIVITY_POST)
4827 // prepare output of comments
4828 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4830 if ($type == "xml") {
4832 foreach ($commentData as $comment) {
4833 $comments[$k++ . ":comment"] = $comment;
4836 foreach ($commentData as $comment) {
4837 $comments[] = $comment;
4840 $data['photo']['friendica_comments'] = $comments;
4842 // include info if rights on photo and rights on item are mismatching
4843 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4844 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4845 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4846 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4847 $data['photo']['rights_mismatch'] = $rights_mismatch;
4854 * Similar as /mod/redir.php
4855 * redirect to 'url' after dfrn auth
4857 * Why this when there is mod/redir.php already?
4858 * This use api_user() and api_login()
4861 * c_url: url of remote contact to auth to
4862 * url: string, url to redirect after auth
4864 function api_friendica_remoteauth()
4866 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4867 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4869 if ($url === '' || $c_url === '') {
4870 throw new BadRequestException("Wrong parameters.");
4873 $c_url = normalise_link($c_url);
4877 $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4879 if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
4880 throw new BadRequestException("Unknown contact");
4883 $cid = $contact['id'];
4885 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4887 if ($contact['duplex'] && $contact['issued-id']) {
4888 $orig_id = $contact['issued-id'];
4889 $dfrn_id = '1:' . $orig_id;
4891 if ($contact['duplex'] && $contact['dfrn-id']) {
4892 $orig_id = $contact['dfrn-id'];
4893 $dfrn_id = '0:' . $orig_id;
4896 $sec = random_string();
4899 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4900 VALUES( %d, %s, '%s', '%s', %d )",
4908 logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
4909 $dest = ($url ? '&destination_url=' . $url : '');
4911 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4912 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4913 . '&type=profile&sec=' . $sec . $dest . $quiet
4916 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4919 * @brief Return the item shared, if the item contains only the [share] tag
4921 * @param array $item Sharer item
4922 * @return array|false Shared item or false if not a reshare
4924 function api_share_as_retweet(&$item)
4926 $body = trim($item["body"]);
4928 if (Diaspora::isReshare($body, false)===false) {
4932 /// @TODO "$1" should maybe mean '$1' ?
4933 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4935 * Skip if there is no shared message in there
4936 * we already checked this in diaspora::isReshare()
4937 * but better one more than one less...
4939 if ($body == $attributes) {
4944 // build the fake reshared item
4945 $reshared_item = $item;
4948 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4949 if ($matches[1] != "") {
4950 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4953 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4954 if ($matches[1] != "") {
4955 $author = $matches[1];
4959 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4960 if ($matches[1] != "") {
4961 $profile = $matches[1];
4964 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4965 if ($matches[1] != "") {
4966 $profile = $matches[1];
4970 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4971 if ($matches[1] != "") {
4972 $avatar = $matches[1];
4975 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4976 if ($matches[1] != "") {
4977 $avatar = $matches[1];
4981 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4982 if ($matches[1] != "") {
4983 $link = $matches[1];
4986 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4987 if ($matches[1] != "") {
4988 $link = $matches[1];
4992 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4993 if ($matches[1] != "") {
4994 $posted = $matches[1];
4997 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4998 if ($matches[1] != "") {
4999 $posted = $matches[1];
5002 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5004 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5008 $reshared_item["body"] = $shared_body;
5009 $reshared_item["author-name"] = $author;
5010 $reshared_item["author-link"] = $profile;
5011 $reshared_item["author-avatar"] = $avatar;
5012 $reshared_item["plink"] = $link;
5013 $reshared_item["created"] = $posted;
5014 $reshared_item["edited"] = $posted;
5016 return $reshared_item;
5021 * @param string $profile
5023 * @return string|false
5024 * @todo remove trailing junk from profile url
5025 * @todo pump.io check has to check the website
5027 function api_get_nick($profile)
5032 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5033 dbesc(normalise_link($profile))
5036 if (DBM::is_result($r)) {
5037 $nick = $r[0]["nick"];
5042 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5043 dbesc(normalise_link($profile))
5046 if (DBM::is_result($r)) {
5047 $nick = $r[0]["nick"];
5052 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5053 if ($friendica != $profile) {
5059 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5060 if ($diaspora != $profile) {
5066 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5067 if ($twitter != $profile) {
5074 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5075 if ($StatusnetHost != $profile) {
5076 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5077 if ($StatusnetUser != $profile) {
5078 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5079 $user = json_decode($UserData);
5081 $nick = $user->screen_name;
5087 // To-Do: look at the page if its really a pumpio site
5088 //if (!$nick == "") {
5089 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5090 // if ($pumpio != $profile)
5092 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5105 * @param array $item
5109 function api_in_reply_to($item)
5113 $in_reply_to['status_id'] = null;
5114 $in_reply_to['user_id'] = null;
5115 $in_reply_to['status_id_str'] = null;
5116 $in_reply_to['user_id_str'] = null;
5117 $in_reply_to['screen_name'] = null;
5119 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5121 "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
5122 intval($item['uid']),
5123 dbesc($item['thr-parent'])
5126 if (DBM::is_result($r)) {
5127 $in_reply_to['status_id'] = intval($r[0]['id']);
5129 $in_reply_to['status_id'] = intval($item['parent']);
5132 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5135 "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
5136 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
5137 WHERE `item`.`id` = %d LIMIT 1",
5138 intval($in_reply_to['status_id'])
5141 if (DBM::is_result($r)) {
5142 if ($r[0]['nick'] == "") {
5143 $r[0]['nick'] = api_get_nick($r[0]["url"]);
5146 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
5147 $in_reply_to['user_id'] = intval($r[0]['id']);
5148 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
5151 // There seems to be situation, where both fields are identical:
5152 // https://github.com/friendica/friendica/issues/1010
5153 // This is a bugfix for that.
5154 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5155 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
5156 $in_reply_to['status_id'] = null;
5157 $in_reply_to['user_id'] = null;
5158 $in_reply_to['status_id_str'] = null;
5159 $in_reply_to['user_id_str'] = null;
5160 $in_reply_to['screen_name'] = null;
5164 return $in_reply_to;
5169 * @param string $Text
5173 function api_clean_plain_items($Text)
5175 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5177 $Text = bb_CleanPictureLinks($Text);
5178 $URLSearchString = "^\[\]";
5180 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
5182 if ($include_entities == "true") {
5183 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
5186 // Simplify "attachment" element
5187 $Text = api_clean_attachments($Text);
5193 * @brief Removes most sharing information for API text export
5195 * @param string $body The original body
5197 * @return string Cleaned body
5199 function api_clean_attachments($body)
5201 $data = BBCode::getAttachmentData($body);
5208 if (isset($data["text"])) {
5209 $body = $data["text"];
5211 if (($body == "") && isset($data["title"])) {
5212 $body = $data["title"];
5214 if (isset($data["url"])) {
5215 $body .= "\n".$data["url"];
5217 $body .= $data["after"];
5224 * @param array $contacts
5228 function api_best_nickname(&$contacts)
5232 if (count($contact) == 0) {
5236 foreach ($contacts as $contact) {
5237 if ($contact["network"] == "") {
5238 $contact["network"] = "dfrn";
5239 $best_contact = [$contact];
5243 if (sizeof($best_contact) == 0) {
5244 foreach ($contacts as $contact) {
5245 if ($contact["network"] == "dfrn") {
5246 $best_contact = [$contact];
5251 if (sizeof($best_contact) == 0) {
5252 foreach ($contacts as $contact) {
5253 if ($contact["network"] == "dspr") {
5254 $best_contact = [$contact];
5259 if (sizeof($best_contact) == 0) {
5260 foreach ($contacts as $contact) {
5261 if ($contact["network"] == "stat") {
5262 $best_contact = [$contact];
5267 if (sizeof($best_contact) == 0) {
5268 foreach ($contacts as $contact) {
5269 if ($contact["network"] == "pump") {
5270 $best_contact = [$contact];
5275 if (sizeof($best_contact) == 0) {
5276 foreach ($contacts as $contact) {
5277 if ($contact["network"] == "twit") {
5278 $best_contact = [$contact];
5283 if (sizeof($best_contact) == 1) {
5284 $contacts = $best_contact;
5286 $contacts = [$contacts[0]];
5291 * Return all or a specified group of the user with the containing contacts.
5293 * @param string $type Return type (atom, rss, xml, json)
5295 * @return array|string
5297 function api_friendica_group_show($type)
5301 if (api_user() === false) {
5302 throw new ForbiddenException();
5306 $user_info = api_get_user($a);
5307 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5308 $uid = $user_info['uid'];
5310 // get data of the specified group id or all groups if not specified
5313 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5317 // error message if specified gid is not in database
5318 if (!DBM::is_result($r)) {
5319 throw new BadRequestException("gid not available");
5323 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5328 // loop through all groups and retrieve all members for adding data in the user array
5329 foreach ($r as $rr) {
5330 $members = Contact::getByGroupId($rr['id']);
5333 if ($type == "xml") {
5334 $user_element = "users";
5336 foreach ($members as $member) {
5337 $user = api_get_user($a, $member['nurl']);
5338 $users[$k++.":user"] = $user;
5341 $user_element = "user";
5342 foreach ($members as $member) {
5343 $user = api_get_user($a, $member['nurl']);
5347 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5349 return api_format_data("groups", $type, ['group' => $grps]);
5351 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5355 * Delete the specified group of the user.
5357 * @param string $type Return type (atom, rss, xml, json)
5359 * @return array|string
5361 function api_friendica_group_delete($type)
5365 if (api_user() === false) {
5366 throw new ForbiddenException();
5370 $user_info = api_get_user($a);
5371 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5372 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5373 $uid = $user_info['uid'];
5375 // error if no gid specified
5376 if ($gid == 0 || $name == "") {
5377 throw new BadRequestException('gid or name not specified');
5380 // get data of the specified group id
5382 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5386 // error message if specified gid is not in database
5387 if (!DBM::is_result($r)) {
5388 throw new BadRequestException('gid not available');
5391 // get data of the specified group id and group name
5393 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5398 // error message if specified gid is not in database
5399 if (!DBM::is_result($rname)) {
5400 throw new BadRequestException('wrong group name');
5404 $ret = Group::removeByName($uid, $name);
5407 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5408 return api_format_data("group_delete", $type, ['result' => $success]);
5410 throw new BadRequestException('other API error');
5413 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5417 * Create the specified group with the posted array of contacts.
5419 * @param string $type Return type (atom, rss, xml, json)
5421 * @return array|string
5423 function api_friendica_group_create($type)
5427 if (api_user() === false) {
5428 throw new ForbiddenException();
5432 $user_info = api_get_user($a);
5433 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5434 $uid = $user_info['uid'];
5435 $json = json_decode($_POST['json'], true);
5436 $users = $json['user'];
5438 // error if no name specified
5440 throw new BadRequestException('group name not specified');
5443 // get data of the specified group name
5445 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5449 // error message if specified group name already exists
5450 if (DBM::is_result($rname)) {
5451 throw new BadRequestException('group name already exists');
5454 // check if specified group name is a deleted group
5456 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5460 // error message if specified group name already exists
5461 if (DBM::is_result($rname)) {
5462 $reactivate_group = true;
5466 $ret = Group::create($uid, $name);
5468 $gid = Group::getIdByName($uid, $name);
5470 throw new BadRequestException('other API error');
5474 $erroraddinguser = false;
5476 foreach ($users as $user) {
5477 $cid = $user['cid'];
5478 // check if user really exists as contact
5480 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5484 if (count($contact)) {
5485 Group::addMember($gid, $cid);
5487 $erroraddinguser = true;
5488 $errorusers[] = $cid;
5492 // return success message incl. missing users in array
5493 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
5494 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5495 return api_format_data("group_create", $type, ['result' => $success]);
5497 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5501 * Update the specified group with the posted array of contacts.
5503 * @param string $type Return type (atom, rss, xml, json)
5505 * @return array|string
5507 function api_friendica_group_update($type)
5511 if (api_user() === false) {
5512 throw new ForbiddenException();
5516 $user_info = api_get_user($a);
5517 $uid = $user_info['uid'];
5518 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5519 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5520 $json = json_decode($_POST['json'], true);
5521 $users = $json['user'];
5523 // error if no name specified
5525 throw new BadRequestException('group name not specified');
5528 // error if no gid specified
5530 throw new BadRequestException('gid not specified');
5534 $members = Contact::getByGroupId($gid);
5535 foreach ($members as $member) {
5536 $cid = $member['id'];
5537 foreach ($users as $user) {
5538 $found = ($user['cid'] == $cid ? true : false);
5541 Group::removeMemberByName($uid, $name, $cid);
5546 $erroraddinguser = false;
5548 foreach ($users as $user) {
5549 $cid = $user['cid'];
5550 // check if user really exists as contact
5552 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5557 if (count($contact)) {
5558 Group::addMember($gid, $cid);
5560 $erroraddinguser = true;
5561 $errorusers[] = $cid;
5565 // return success message incl. missing users in array
5566 $status = ($erroraddinguser ? "missing user" : "ok");
5567 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5568 return api_format_data("group_update", $type, ['result' => $success]);
5571 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5575 * @param string $type Return type (atom, rss, xml, json)
5577 * @return array|string
5579 function api_friendica_activity($type)
5583 if (api_user() === false) {
5584 throw new ForbiddenException();
5586 $verb = strtolower($a->argv[3]);
5587 $verb = preg_replace("|\..*$|", "", $verb);
5589 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5591 $res = Item::performLike($id, $verb);
5594 if ($type == "xml") {
5599 return api_format_data('ok', $type, ['ok' => $ok]);
5601 throw new BadRequestException('Error adding activity');
5605 /// @TODO move to top of file or somewhere better
5606 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5607 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5608 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5609 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5610 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5611 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5612 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5613 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5614 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5615 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5618 * @brief Returns notifications
5620 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5623 function api_friendica_notification($type)
5627 if (api_user() === false) {
5628 throw new ForbiddenException();
5631 throw new BadRequestException("Invalid argument count");
5633 $nm = new NotificationsManager();
5635 $notes = $nm->getAll([], "+seen -date", 50);
5637 if ($type == "xml") {
5639 foreach ($notes as $note) {
5640 $xmlnotes[] = ["@attributes" => $note];
5646 return api_format_data("notes", $type, ['note' => $notes]);
5650 * POST request with 'id' param as notification id
5652 * @brief Set notification as seen and returns associated item (if possible)
5654 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5657 function api_friendica_notification_seen($type)
5661 if (api_user() === false) {
5662 throw new ForbiddenException();
5665 throw new BadRequestException("Invalid argument count");
5668 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5670 $nm = new NotificationsManager();
5671 $note = $nm->getByID($id);
5672 if (is_null($note)) {
5673 throw new BadRequestException("Invalid argument");
5676 $nm->setSeen($note);
5677 if ($note['otype']=='item') {
5678 // would be really better with an ItemsManager and $im->getByID() :-P
5680 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5681 intval($note['iid']),
5682 intval(local_user())
5685 // we found the item, return it to the user
5686 $user_info = api_get_user($a);
5687 $ret = api_format_items($r, $user_info, false, $type);
5688 $data = ['status' => $ret];
5689 return api_format_data("status", $type, $data);
5691 // the item can't be found, but we set the note as seen, so we count this as a success
5693 return api_format_data('result', $type, ['result' => "success"]);
5696 /// @TODO move to top of file or somewhere better
5697 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5698 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5701 * @brief update a direct_message to seen state
5703 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5704 * @return string (success result=ok, error result=error with error message)
5706 function api_friendica_direct_messages_setseen($type)
5709 if (api_user() === false) {
5710 throw new ForbiddenException();
5714 $user_info = api_get_user($a);
5715 $uid = $user_info['uid'];
5716 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5718 // return error if id is zero
5720 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5721 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5724 // get data of the specified message id
5726 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5731 // error message if specified id is not in database
5732 if (!DBM::is_result($r)) {
5733 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5734 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5737 // update seen indicator
5739 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5746 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5747 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5749 $answer = ['result' => 'error', 'message' => 'unknown error'];
5750 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5754 /// @TODO move to top of file or somewhere better
5755 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5758 * @brief search for direct_messages containing a searchstring through api
5760 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5761 * @return string (success: success=true if found and search_result contains found messages,
5762 * success=false if nothing was found, search_result='nothing found',
5763 * error: result=error with error message)
5765 function api_friendica_direct_messages_search($type)
5769 if (api_user() === false) {
5770 throw new ForbiddenException();
5774 $user_info = api_get_user($a);
5775 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5776 $uid = $user_info['uid'];
5778 // error if no searchstring specified
5779 if ($searchstring == "") {
5780 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5781 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5784 // get data for the specified searchstring
5786 "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",
5788 dbesc('%'.$searchstring.'%')
5791 $profile_url = $user_info["url"];
5793 // message if nothing was found
5794 if (!DBM::is_result($r)) {
5795 $success = ['success' => false, 'search_results' => 'problem with query'];
5796 } elseif (count($r) == 0) {
5797 $success = ['success' => false, 'search_results' => 'nothing found'];
5800 foreach ($r as $item) {
5801 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5802 $recipient = $user_info;
5803 $sender = api_get_user($a, normalise_link($item['contact-url']));
5804 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5805 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5806 $sender = $user_info;
5809 $ret[] = api_format_messages($item, $recipient, $sender);
5811 $success = ['success' => true, 'search_results' => $ret];
5814 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5817 /// @TODO move to top of file or somewhere better
5818 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5821 * @brief return data of all the profiles a user has to the client
5823 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5826 function api_friendica_profile_show($type)
5830 if (api_user() === false) {
5831 throw new ForbiddenException();
5835 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5837 // retrieve general information about profiles for user
5838 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5839 $directory = Config::get('system', 'directory');
5841 // get data of the specified profile id or all profiles of the user if not specified
5842 if ($profileid != 0) {
5844 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5849 // error message if specified gid is not in database
5850 if (!DBM::is_result($r)) {
5851 throw new BadRequestException("profile_id not available");
5855 "SELECT * FROM `profile` WHERE `uid` = %d",
5859 // loop through all returned profiles and retrieve data and users
5861 foreach ($r as $rr) {
5862 $profile = api_format_items_profiles($rr);
5864 // select all users from contact table, loop and prepare standard return for user data
5867 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5869 intval($rr['profile_id'])
5872 foreach ($r as $rr) {
5873 $user = api_get_user($a, $rr['nurl']);
5874 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5876 $profile['users'] = $users;
5878 // add prepared profile data to array for final return
5879 if ($type == "xml") {
5880 $profiles[$k++ . ":profile"] = $profile;
5882 $profiles[] = $profile;
5886 // return settings, authenticated user and profiles data
5887 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5889 $result = ['multi_profiles' => $multi_profiles ? true : false,
5890 'global_dir' => $directory,
5891 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5892 'profiles' => $profiles];
5893 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5895 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5898 * Returns a list of saved searches.
5900 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5902 * @param string $type Return format: json or xml
5904 * @return string|array
5906 function api_saved_searches_list($type)
5908 $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
5911 while ($term = $terms->fetch()) {
5913 'name' => $term['term'],
5914 'query' => $term['term'],
5915 'id_str' => $term['id'],
5916 'id' => intval($term['id'])
5922 return api_format_data("terms", $type, ['terms' => $result]);
5925 /// @TODO move to top of file or somewhere better
5926 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5929 @TODO Maybe open to implement?
5931 [pagename] => api/1.1/statuses/lookup.json
5932 [id] => 605138389168451584
5933 [include_cards] => true
5934 [cards_platform] => Android-12
5935 [include_entities] => true
5936 [include_my_retweet] => 1
5938 [include_reply_count] => true
5939 [include_descendent_reply_count] => true
5943 Not implemented by now:
5944 statuses/retweets_of_me
5949 account/update_location
5950 account/update_profile_background_image
5953 friendica/profile/update
5954 friendica/profile/create
5955 friendica/profile/delete
5957 Not implemented in status.net:
5958 statuses/retweeted_to_me
5959 statuses/retweeted_by_me
5960 direct_messages/destroy
5962 account/update_delivery_device
5963 notifications/follow