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\DateTimeFormat;
40 use Friendica\Util\Network;
41 use Friendica\Util\XML;
43 require_once 'include/conversation.php';
44 require_once 'include/html2plain.php';
45 require_once 'mod/share.php';
46 require_once 'mod/item.php';
47 require_once 'include/security.php';
48 require_once 'include/html2bbcode.php';
49 require_once 'mod/wall_upload.php';
50 require_once 'mod/proxy.php';
52 define('API_METHOD_ANY', '*');
53 define('API_METHOD_GET', 'GET');
54 define('API_METHOD_POST', 'POST,PUT');
55 define('API_METHOD_DELETE', 'POST,DELETE');
61 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
62 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
63 * into a page, and visitors will post something without noticing it).
65 * @brief Auth API user
69 if (x($_SESSION, 'allow_api')) {
77 * Clients can send 'source' parameter to be show in post metadata
78 * as "sent via <source>".
79 * Some clients doesn't send a source param, we support ones we know
82 * @brief Get source name from API client
85 * Client source name, default to "api" if unset/unknown
89 if (requestdata('source')) {
90 return requestdata('source');
93 // Support for known clients that doesn't send a source name
94 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
98 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
104 * @brief Format date for API
106 * @param string $str Source date, as UTC
107 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
109 function api_date($str)
111 // Wed May 23 06:01:13 +0000 2007
112 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
116 * Register a function to be the endpoint for defined API path.
118 * @brief Register API endpoint
120 * @param string $path API URL path, relative to System::baseUrl()
121 * @param string $func Function name to call on path request
122 * @param bool $auth API need logged user
123 * @param string $method HTTP method reqiured to call this endpoint.
124 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
125 * Default to API_METHOD_ANY
127 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
137 // Workaround for hotot
138 $path = str_replace("api/", "api/1.1/", $path);
148 * Log in user via OAuth1 or Simple HTTP Auth.
149 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
151 * @brief Login API user
153 * @param object $a App
154 * @hook 'authenticate'
156 * 'username' => username from login form
157 * 'password' => password from login form
158 * 'authenticated' => return status,
159 * 'user_record' => return authenticated user record
161 * array $user logged user record
163 function api_login(App $a)
165 $oauth1 = new FKOAuth1();
168 list($consumer, $token) = $oauth1->verify_request(OAuthRequest::from_request());
169 if (!is_null($token)) {
170 $oauth1->loginUser($token->uid);
171 Addon::callHooks('logged_in', $a->user);
174 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
175 var_dump($consumer, $token);
177 } catch (Exception $e) {
181 // workaround for HTTP-auth in CGI mode
182 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
183 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
184 if (strlen($userpass)) {
185 list($name, $password) = explode(':', $userpass);
186 $_SERVER['PHP_AUTH_USER'] = $name;
187 $_SERVER['PHP_AUTH_PW'] = $password;
191 if (!x($_SERVER, 'PHP_AUTH_USER')) {
192 logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
193 header('WWW-Authenticate: Basic realm="Friendica"');
194 throw new UnauthorizedException("This API requires login");
197 $user = $_SERVER['PHP_AUTH_USER'];
198 $password = $_SERVER['PHP_AUTH_PW'];
200 // allow "user@server" login (but ignore 'server' part)
201 $at = strstr($user, "@", true);
206 // next code from mod/auth.php. needs better solution
210 'username' => trim($user),
211 'password' => trim($password),
212 'authenticated' => 0,
213 'user_record' => null,
217 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
218 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
219 * and later addons should not interfere with an earlier one that succeeded.
221 Addon::callHooks('authenticate', $addon_auth);
223 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
224 $record = $addon_auth['user_record'];
226 $user_id = User::authenticate(trim($user), trim($password));
228 $record = dba::selectFirst('user', [], ['uid' => $user_id]);
232 if (!DBM::is_result($record)) {
233 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
234 header('WWW-Authenticate: Basic realm="Friendica"');
235 //header('HTTP/1.0 401 Unauthorized');
236 //die('This api requires login');
237 throw new UnauthorizedException("This API requires login");
240 authenticate_success($record);
242 $_SESSION["allow_api"] = true;
244 Addon::callHooks('logged_in', $a->user);
248 * API endpoints can define which HTTP method to accept when called.
249 * This function check the current HTTP method agains endpoint
252 * @brief Check HTTP method of called API
254 * @param string $method Required methods, uppercase, separated by comma
257 function api_check_method($method)
259 if ($method == "*") {
262 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
266 * Authenticate user, call registered API function, set HTTP headers
268 * @brief Main API entry point
270 * @param object $a App
271 * @return string API call result
273 function api_call(App $a)
275 global $API, $called_api;
278 if (strpos($a->query_string, ".xml") > 0) {
281 if (strpos($a->query_string, ".json") > 0) {
284 if (strpos($a->query_string, ".rss") > 0) {
287 if (strpos($a->query_string, ".atom") > 0) {
292 foreach ($API as $p => $info) {
293 if (strpos($a->query_string, $p) === 0) {
294 if (!api_check_method($info['method'])) {
295 throw new MethodNotAllowedException();
298 $called_api = explode("/", $p);
299 //unset($_SERVER['PHP_AUTH_USER']);
301 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
302 if ($info['auth'] === true && api_user() === false) {
306 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
307 logger('API parameters: ' . print_r($_REQUEST, true));
309 $stamp = microtime(true);
310 $return = call_user_func($info['func'], $type);
311 $duration = (float) (microtime(true) - $stamp);
312 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
314 if (Config::get("system", "profiler")) {
315 $duration = microtime(true)-$a->performance["start"];
317 /// @TODO round() really everywhere?
319 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
320 "Database: %s/%s, Cache %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
321 round($a->performance["database"] - $a->performance["database_write"], 3),
322 round($a->performance["database_write"], 3),
323 round($a->performance["cache"], 3),
324 round($a->performance["cache_write"], 3),
325 round($a->performance["network"], 2),
326 round($a->performance["file"], 2),
327 round($duration - ($a->performance["database"]
328 + $a->performance["cache"] + $a->performance["cache_write"]
329 + $a->performance["network"] + $a->performance["file"]), 2),
335 if (Config::get("rendertime", "callstack")) {
336 $o = "Database Read:\n";
337 foreach ($a->callstack["database"] as $func => $time) {
338 $time = round($time, 3);
340 $o .= $func . ": " . $time . "\n";
343 $o .= "\nDatabase Write:\n";
344 foreach ($a->callstack["database_write"] as $func => $time) {
345 $time = round($time, 3);
347 $o .= $func . ": " . $time . "\n";
351 $o = "Cache Read:\n";
352 foreach ($a->callstack["cache"] as $func => $time) {
353 $time = round($time, 3);
355 $o .= $func . ": " . $time . "\n";
358 $o .= "\nCache Write:\n";
359 foreach ($a->callstack["cache_write"] as $func => $time) {
360 $time = round($time, 3);
362 $o .= $func . ": " . $time . "\n";
366 $o .= "\nNetwork:\n";
367 foreach ($a->callstack["network"] as $func => $time) {
368 $time = round($time, 3);
370 $o .= $func . ": " . $time . "\n";
373 logger($o, LOGGER_DEBUG);
377 if (false === $return) {
379 * api function returned false withour throw an
380 * exception. This should not happend, throw a 500
382 throw new InternalServerErrorException();
387 header("Content-Type: text/xml");
390 header("Content-Type: application/json");
391 foreach ($return as $rr) {
392 $json = json_encode($rr);
394 if (x($_GET, 'callback')) {
395 $json = $_GET['callback'] . "(" . $json . ")";
400 header("Content-Type: application/rss+xml");
401 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
404 header("Content-Type: application/atom+xml");
405 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
412 logger('API call not implemented: ' . $a->query_string);
413 throw new NotImplementedException();
414 } catch (HTTPException $e) {
415 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
416 return api_error($type, $e);
421 * @brief Format API error string
423 * @param string $type Return type (xml, json, rss, as)
424 * @param object $e HTTPException Error object
425 * @return string error message formatted as $type
427 function api_error($type, $e)
431 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
432 /// @TODO: https://dev.twitter.com/overview/api/response-codes
434 $error = ["error" => $error,
435 "code" => $e->httpcode . " " . $e->httpdesc,
436 "request" => $a->query_string];
438 $return = api_format_data('status', $type, ['status' => $error]);
442 header("Content-Type: text/xml");
445 header("Content-Type: application/json");
446 $return = json_encode($return);
449 header("Content-Type: application/rss+xml");
452 header("Content-Type: application/atom+xml");
460 * @brief Set values for RSS template
463 * @param array $arr Array to be passed to template
464 * @param array $user_info User info
466 * @todo find proper type-hints
468 function api_rss_extra(App $a, $arr, $user_info)
470 if (is_null($user_info)) {
471 $user_info = api_get_user($a);
474 $arr['$user'] = $user_info;
476 'alternate' => $user_info['url'],
477 'self' => System::baseUrl() . "/" . $a->query_string,
478 'base' => System::baseUrl(),
479 'updated' => api_date(null),
480 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
481 'language' => $user_info['language'],
482 'logo' => System::baseUrl() . "/images/friendica-32.png",
490 * @brief Unique contact to contact url.
492 * @param int $id Contact id
493 * @return bool|string
494 * Contact url or False if contact id is unknown
496 function api_unique_id_to_nurl($id)
498 $r = dba::selectFirst('contact', ['nurl'], ['uid' => 0, 'id' => $id]);
500 if (DBM::is_result($r)) {
508 * @brief Get user info array.
510 * @param object $a App
511 * @param int|string $contact_id Contact ID or URL
513 function api_get_user(App $a, $contact_id = null)
521 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
523 // Searching for contact URL
524 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
525 $user = dbesc(normalise_link($contact_id));
527 $extra_query = "AND `contact`.`nurl` = '%s' ";
528 if (api_user() !== false) {
529 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
533 // Searching for contact id with uid = 0
534 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
535 $user = dbesc(api_unique_id_to_nurl($contact_id));
538 throw new BadRequestException("User not found.");
542 $extra_query = "AND `contact`.`nurl` = '%s' ";
543 if (api_user() !== false) {
544 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
548 if (is_null($user) && x($_GET, 'user_id')) {
549 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
552 throw new BadRequestException("User not found.");
556 $extra_query = "AND `contact`.`nurl` = '%s' ";
557 if (api_user() !== false) {
558 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
561 if (is_null($user) && x($_GET, 'screen_name')) {
562 $user = dbesc($_GET['screen_name']);
563 $extra_query = "AND `contact`.`nick` = '%s' ";
564 if (api_user() !== false) {
565 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
569 if (is_null($user) && x($_GET, 'profileurl')) {
570 $user = dbesc(normalise_link($_GET['profileurl']));
571 $extra_query = "AND `contact`.`nurl` = '%s' ";
572 if (api_user() !== false) {
573 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
577 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
578 $argid = count($called_api);
579 list($user, $null) = explode(".", $a->argv[$argid]);
580 if (is_numeric($user)) {
581 $user = dbesc(api_unique_id_to_nurl($user));
588 $extra_query = "AND `contact`.`nurl` = '%s' ";
589 if (api_user() !== false) {
590 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
593 $user = dbesc($user);
594 $extra_query = "AND `contact`.`nick` = '%s' ";
595 if (api_user() !== false) {
596 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
601 logger("api_get_user: user ".$user, LOGGER_DEBUG);
604 if (api_user() === false) {
608 $user = $_SESSION['uid'];
609 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
613 logger('api_user: ' . $extra_query . ', user: ' . $user);
617 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
623 // Selecting the id by priority, friendica first
624 api_best_nickname($uinfo);
626 // if the contact wasn't found, fetch it from the contacts with uid = 0
627 if (!DBM::is_result($uinfo)) {
631 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
634 if (DBM::is_result($r)) {
635 $network_name = ContactSelector::networkToName($r[0]['network'], $r[0]['url']);
637 // If no nick where given, extract it from the address
638 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
639 $r[0]['nick'] = api_get_nick($r[0]["url"]);
644 'id_str' => (string) $r[0]["id"],
645 'name' => $r[0]["name"],
646 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
647 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
648 'description' => $r[0]["about"],
649 'profile_image_url' => $r[0]["micro"],
650 'profile_image_url_https' => $r[0]["micro"],
651 'url' => $r[0]["url"],
652 'protected' => false,
653 'followers_count' => 0,
654 'friends_count' => 0,
656 'created_at' => api_date($r[0]["created"]),
657 'favourites_count' => 0,
659 'time_zone' => 'UTC',
660 'geo_enabled' => false,
662 'statuses_count' => 0,
664 'contributors_enabled' => false,
665 'is_translator' => false,
666 'is_translation_enabled' => false,
667 'following' => false,
668 'follow_request_sent' => false,
669 'statusnet_blocking' => false,
670 'notifications' => false,
671 'statusnet_profile_url' => $r[0]["url"],
673 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
675 'network' => $r[0]["network"],
680 throw new BadRequestException("User not found.");
684 if ($uinfo[0]['self']) {
685 if ($uinfo[0]['network'] == "") {
686 $uinfo[0]['network'] = NETWORK_DFRN;
690 "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
694 "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
698 /// @TODO old-lost code? (twice)
699 // Counting is deactivated by now, due to performance issues
700 // count public wall messages
701 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
702 // intval($uinfo[0]['uid'])
704 //$countitms = $r[0]['count'];
707 // Counting is deactivated by now, due to performance issues
708 //$r = q("SELECT count(*) as `count` FROM `item`
709 // WHERE `contact-id` = %d",
710 // intval($uinfo[0]['id'])
712 //$countitms = $r[0]['count'];
716 /// @TODO old-lost code? (twice)
718 // Counting is deactivated by now, due to performance issues
720 $r = q("SELECT count(*) as `count` FROM `contact`
721 WHERE `uid` = %d AND `rel` IN ( %d, %d )
722 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
723 intval($uinfo[0]['uid']),
724 intval(CONTACT_IS_SHARING),
725 intval(CONTACT_IS_FRIEND)
727 $countfriends = $r[0]['count'];
729 $r = q("SELECT count(*) as `count` FROM `contact`
730 WHERE `uid` = %d AND `rel` IN ( %d, %d )
731 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
732 intval($uinfo[0]['uid']),
733 intval(CONTACT_IS_FOLLOWER),
734 intval(CONTACT_IS_FRIEND)
736 $countfollowers = $r[0]['count'];
738 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
739 intval($uinfo[0]['uid'])
741 $starred = $r[0]['count'];
744 if (! $uinfo[0]['self']) {
754 // Add a nick if it isn't present there
755 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
756 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
759 $network_name = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
761 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
763 if (!empty($profile[0]['about'])) {
764 $description = $profile[0]['about'];
766 $description = $uinfo[0]["about"];
769 if (!empty($usr[0]['default-location'])) {
770 $location = $usr[0]['default-location'];
771 } elseif (!empty($uinfo[0]["location"])) {
772 $location = $uinfo[0]["location"];
774 $location = $network_name;
778 'id' => intval($pcontact_id),
779 'id_str' => (string) intval($pcontact_id),
780 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
781 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
782 'location' => $location,
783 'description' => $description,
784 'profile_image_url' => $uinfo[0]['micro'],
785 'profile_image_url_https' => $uinfo[0]['micro'],
786 'url' => $uinfo[0]['url'],
787 'protected' => false,
788 'followers_count' => intval($countfollowers),
789 'friends_count' => intval($countfriends),
791 'created_at' => api_date($uinfo[0]['created']),
792 'favourites_count' => intval($starred),
794 'time_zone' => 'UTC',
795 'geo_enabled' => false,
797 'statuses_count' => intval($countitms),
799 'contributors_enabled' => false,
800 'is_translator' => false,
801 'is_translation_enabled' => false,
802 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
803 'follow_request_sent' => false,
804 'statusnet_blocking' => false,
805 'notifications' => false,
807 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
808 'statusnet_profile_url' => $uinfo[0]['url'],
809 'uid' => intval($uinfo[0]['uid']),
810 'cid' => intval($uinfo[0]['cid']),
811 'self' => $uinfo[0]['self'],
812 'network' => $uinfo[0]['network'],
815 // If this is a local user and it uses Frio, we can get its color preferences.
817 $theme_info = dba::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
818 if ($theme_info['theme'] === 'frio') {
819 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
820 if ($schema && ($schema != '---')) {
821 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
822 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
823 require_once $schemefile;
826 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
827 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
828 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
834 $link_color = "#6fdbe8";
837 $bgcolor = "#ededed";
840 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
841 $ret['profile_link_color'] = str_replace('#', '', $link_color);
842 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
850 * @brief return api-formatted array for item's author and owner
852 * @param object $a App
853 * @param array $item item from db
854 * @return array(array:author, array:owner)
856 function api_item_get_user(App $a, $item)
858 $status_user = api_get_user($a, $item["author-link"]);
860 $status_user["protected"] = (($item["allow_cid"] != "") ||
861 ($item["allow_gid"] != "") ||
862 ($item["deny_cid"] != "") ||
863 ($item["deny_gid"] != "") ||
866 if ($item['thr-parent'] == $item['uri']) {
867 $owner_user = api_get_user($a, $item["owner-link"]);
869 $owner_user = $status_user;
872 return ([$status_user, $owner_user]);
876 * @brief walks recursively through an array with the possibility to change value and key
878 * @param array $array The array to walk through
879 * @param string $callback The callback function
881 * @return array the transformed array
883 function api_walk_recursive(array &$array, callable $callback)
887 foreach ($array as $k => $v) {
889 if ($callback($v, $k)) {
890 $new_array[$k] = api_walk_recursive($v, $callback);
893 if ($callback($v, $k)) {
904 * @brief Callback function to transform the array in an array that can be transformed in a XML file
906 * @param mixed $item Array item value
907 * @param string $key Array key
909 * @return boolean Should the array item be deleted?
911 function api_reformat_xml(&$item, &$key)
913 if (is_bool($item)) {
914 $item = ($item ? "true" : "false");
917 if (substr($key, 0, 10) == "statusnet_") {
918 $key = "statusnet:".substr($key, 10);
919 } elseif (substr($key, 0, 10) == "friendica_") {
920 $key = "friendica:".substr($key, 10);
922 /// @TODO old-lost code?
924 // $key = "default:".$key;
930 * @brief Creates the XML from a JSON style array
932 * @param array $data JSON style array
933 * @param string $root_element Name of the root element
935 * @return string The XML data
937 function api_create_xml($data, $root_element)
939 $childname = key($data);
940 $data2 = array_pop($data);
943 $namespaces = ["" => "http://api.twitter.com",
944 "statusnet" => "http://status.net/schema/api/1/",
945 "friendica" => "http://friendi.ca/schema/api/1/",
946 "georss" => "http://www.georss.org/georss"];
948 /// @todo Auto detection of needed namespaces
949 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
953 if (is_array($data2)) {
954 api_walk_recursive($data2, "api_reformat_xml");
961 foreach ($data2 as $item) {
962 $data4[$i++.":".$childname] = $item;
968 $data3 = [$root_element => $data2];
970 $ret = XML::fromArray($data3, $xml, false, $namespaces);
975 * @brief Formats the data according to the data type
977 * @param string $root_element Name of the root element
978 * @param string $type Return type (atom, rss, xml, json)
979 * @param array $data JSON style array
981 * @return (string|object|array) XML data or JSON data
983 function api_format_data($root_element, $type, $data)
989 $ret = api_create_xml($data, $root_element);
1004 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
1005 * returns a 401 status code and an error message if not.
1006 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
1008 * @param string $type Return type (atom, rss, xml, json)
1010 function api_account_verify_credentials($type)
1015 if (api_user() === false) {
1016 throw new ForbiddenException();
1019 unset($_REQUEST["user_id"]);
1020 unset($_GET["user_id"]);
1022 unset($_REQUEST["screen_name"]);
1023 unset($_GET["screen_name"]);
1025 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
1027 $user_info = api_get_user($a);
1029 // "verified" isn't used here in the standard
1030 unset($user_info["verified"]);
1032 // - Adding last status
1033 if (!$skip_status) {
1034 $user_info["status"] = api_status_show("raw");
1035 if (!count($user_info["status"])) {
1036 unset($user_info["status"]);
1038 unset($user_info["status"]["user"]);
1042 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1043 unset($user_info["uid"]);
1044 unset($user_info["self"]);
1046 return api_format_data("user", $type, ['user' => $user_info]);
1049 /// @TODO move to top of file or somewhere better
1050 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1053 * Get data from $_POST or $_GET
1057 function requestdata($k)
1059 if (x($_POST, $k)) {
1069 * Waitman Gobble Mod
1071 * @param string $type Return type (atom, rss, xml, json)
1073 * @return array|string
1075 function api_statuses_mediap($type)
1079 if (api_user() === false) {
1080 logger('api_statuses_update: no user');
1081 throw new ForbiddenException();
1083 $user_info = api_get_user($a);
1085 $_REQUEST['type'] = 'wall';
1086 $_REQUEST['profile_uid'] = api_user();
1087 $_REQUEST['api_source'] = true;
1088 $txt = requestdata('status');
1089 /// @TODO old-lost code?
1090 //$txt = urldecode(requestdata('status'));
1092 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1093 $txt = html2bb_video($txt);
1094 $config = HTMLPurifier_Config::createDefault();
1095 $config->set('Cache.DefinitionImpl', null);
1096 $purifier = new HTMLPurifier($config);
1097 $txt = $purifier->purify($txt);
1099 $txt = html2bbcode($txt);
1101 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1103 // tell wall_upload function to return img info instead of echo
1104 $_REQUEST['hush'] = 'yeah';
1105 $bebop = wall_upload_post($a);
1107 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1108 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1111 // this should output the last post (the one we just posted).
1112 return api_status_show($type);
1115 /// @TODO move this to top of file or somewhere better!
1116 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1119 * Updates the user’s current status.
1121 * @param string $type Return type (atom, rss, xml, json)
1123 * @return array|string
1124 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1126 function api_statuses_update($type)
1131 if (api_user() === false) {
1132 logger('api_statuses_update: no user');
1133 throw new ForbiddenException();
1138 // convert $_POST array items to the form we use for web posts.
1139 if (requestdata('htmlstatus')) {
1140 $txt = requestdata('htmlstatus');
1141 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1142 $txt = html2bb_video($txt);
1144 $config = HTMLPurifier_Config::createDefault();
1145 $config->set('Cache.DefinitionImpl', null);
1147 $purifier = new HTMLPurifier($config);
1148 $txt = $purifier->purify($txt);
1150 $_REQUEST['body'] = html2bbcode($txt);
1153 $_REQUEST['body'] = requestdata('status');
1156 $_REQUEST['title'] = requestdata('title');
1158 $parent = requestdata('in_reply_to_status_id');
1160 // Twidere sends "-1" if it is no reply ...
1161 if ($parent == -1) {
1165 if (ctype_digit($parent)) {
1166 $_REQUEST['parent'] = $parent;
1168 $_REQUEST['parent_uri'] = $parent;
1171 if (requestdata('lat') && requestdata('long')) {
1172 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1174 $_REQUEST['profile_uid'] = api_user();
1177 $_REQUEST['type'] = 'net-comment';
1179 // Check for throttling (maximum posts per day, week and month)
1180 $throttle_day = Config::get('system', 'throttle_limit_day');
1181 if ($throttle_day > 0) {
1182 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1185 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1186 AND `created` > '%s' AND `id` = `parent`",
1191 if (DBM::is_result($r)) {
1192 $posts_day = $r[0]["posts_day"];
1197 if ($posts_day > $throttle_day) {
1198 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1199 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1200 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));
1204 $throttle_week = Config::get('system', 'throttle_limit_week');
1205 if ($throttle_week > 0) {
1206 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1209 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1210 AND `created` > '%s' AND `id` = `parent`",
1215 if (DBM::is_result($r)) {
1216 $posts_week = $r[0]["posts_week"];
1221 if ($posts_week > $throttle_week) {
1222 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1223 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1224 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));
1228 $throttle_month = Config::get('system', 'throttle_limit_month');
1229 if ($throttle_month > 0) {
1230 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1233 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1234 AND `created` > '%s' AND `id` = `parent`",
1239 if (DBM::is_result($r)) {
1240 $posts_month = $r[0]["posts_month"];
1245 if ($posts_month > $throttle_month) {
1246 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1247 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1248 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));
1252 $_REQUEST['type'] = 'wall';
1255 if (x($_FILES, 'media')) {
1256 // upload the image if we have one
1257 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1258 $media = wall_upload_post($a);
1259 if (strlen($media) > 0) {
1260 $_REQUEST['body'] .= "\n\n" . $media;
1264 // To-Do: Multiple IDs
1265 if (requestdata('media_ids')) {
1267 "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",
1268 intval(requestdata('media_ids')),
1271 if (DBM::is_result($r)) {
1272 $phototypes = Image::supportedTypes();
1273 $ext = $phototypes[$r[0]['type']];
1274 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1275 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1279 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1281 $_REQUEST['api_source'] = true;
1283 if (!x($_REQUEST, "source")) {
1284 $_REQUEST["source"] = api_source();
1287 // call out normal post function
1290 // this should output the last post (the one we just posted).
1291 return api_status_show($type);
1294 /// @TODO move to top of file or somewhere better
1295 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1296 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1299 * Uploads an image to Friendica.
1302 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1304 function api_media_upload()
1308 if (api_user() === false) {
1310 throw new ForbiddenException();
1315 if (!x($_FILES, 'media')) {
1317 throw new BadRequestException("No media.");
1320 $media = wall_upload_post($a, false);
1323 throw new InternalServerErrorException();
1327 $returndata["media_id"] = $media["id"];
1328 $returndata["media_id_string"] = (string)$media["id"];
1329 $returndata["size"] = $media["size"];
1330 $returndata["image"] = ["w" => $media["width"],
1331 "h" => $media["height"],
1332 "image_type" => $media["type"]];
1334 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1336 return ["media" => $returndata];
1339 /// @TODO move to top of file or somewhere better
1340 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1344 * @param string $type Return type (atom, rss, xml, json)
1346 * @return array|string
1348 function api_status_show($type)
1352 $user_info = api_get_user($a);
1354 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1356 if ($type == "raw") {
1357 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1362 // get last public wall message
1366 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1367 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1368 AND `item`.`type` != 'activity' $privacy_sql
1369 ORDER BY `item`.`id` DESC
1371 intval($user_info['cid']),
1373 dbesc($user_info['url']),
1374 dbesc(normalise_link($user_info['url'])),
1375 dbesc($user_info['url']),
1376 dbesc(normalise_link($user_info['url']))
1379 if (DBM::is_result($lastwall)) {
1380 $lastwall = $lastwall[0];
1382 $in_reply_to = api_in_reply_to($lastwall);
1384 $converted = api_convert_item($lastwall);
1386 if ($type == "xml") {
1387 $geo = "georss:point";
1393 'created_at' => api_date($lastwall['created']),
1394 'id' => intval($lastwall['id']),
1395 'id_str' => (string) $lastwall['id'],
1396 'text' => $converted["text"],
1397 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1398 'truncated' => false,
1399 'in_reply_to_status_id' => $in_reply_to['status_id'],
1400 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1401 'in_reply_to_user_id' => $in_reply_to['user_id'],
1402 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1403 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1404 'user' => $user_info,
1406 'coordinates' => "",
1408 'contributors' => "",
1409 'is_quote_status' => false,
1410 'retweet_count' => 0,
1411 'favorite_count' => 0,
1412 'favorited' => $lastwall['starred'] ? true : false,
1413 'retweeted' => false,
1414 'possibly_sensitive' => false,
1416 'statusnet_html' => $converted["html"],
1417 'statusnet_conversation_id' => $lastwall['parent'],
1418 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1421 if (count($converted["attachments"]) > 0) {
1422 $status_info["attachments"] = $converted["attachments"];
1425 if (count($converted["entities"]) > 0) {
1426 $status_info["entities"] = $converted["entities"];
1429 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1430 $status_info["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1431 } elseif (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1432 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['item_network'], $user_info['url']).')');
1435 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1436 unset($status_info["user"]["uid"]);
1437 unset($status_info["user"]["self"]);
1440 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1442 if ($type == "raw") {
1443 return $status_info;
1446 return api_format_data("statuses", $type, ['status' => $status_info]);
1450 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1451 * The author's most recent status will be returned inline.
1453 * @param string $type Return type (atom, rss, xml, json)
1454 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1456 function api_users_show($type)
1460 $user_info = api_get_user($a);
1464 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1465 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1466 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1467 AND `type`!='activity'
1468 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1472 dbesc(ACTIVITY_POST),
1473 intval($user_info['cid']),
1474 dbesc($user_info['url']),
1475 dbesc(normalise_link($user_info['url'])),
1476 dbesc($user_info['url']),
1477 dbesc(normalise_link($user_info['url']))
1480 if (DBM::is_result($lastwall)) {
1481 $lastwall = $lastwall[0];
1483 $in_reply_to = api_in_reply_to($lastwall);
1485 $converted = api_convert_item($lastwall);
1487 if ($type == "xml") {
1488 $geo = "georss:point";
1493 $user_info['status'] = [
1494 'text' => $converted["text"],
1495 'truncated' => false,
1496 'created_at' => api_date($lastwall['created']),
1497 'in_reply_to_status_id' => $in_reply_to['status_id'],
1498 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1499 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1500 'id' => intval($lastwall['contact-id']),
1501 'id_str' => (string) $lastwall['contact-id'],
1502 'in_reply_to_user_id' => $in_reply_to['user_id'],
1503 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1504 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1506 'favorited' => $lastwall['starred'] ? true : false,
1507 'statusnet_html' => $converted["html"],
1508 'statusnet_conversation_id' => $lastwall['parent'],
1509 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1512 if (count($converted["attachments"]) > 0) {
1513 $user_info["status"]["attachments"] = $converted["attachments"];
1516 if (count($converted["entities"]) > 0) {
1517 $user_info["status"]["entities"] = $converted["entities"];
1520 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1521 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1524 if (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1525 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) . ')');
1529 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1530 unset($user_info["uid"]);
1531 unset($user_info["self"]);
1533 return api_format_data("user", $type, ['user' => $user_info]);
1536 /// @TODO move to top of file or somewhere better
1537 api_register_func('api/users/show', 'api_users_show');
1538 api_register_func('api/externalprofile/show', 'api_users_show');
1541 * Search a public user account.
1543 * @param string $type Return type (atom, rss, xml, json)
1545 * @return array|string
1546 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1548 function api_users_search($type)
1554 if (x($_GET, 'q')) {
1555 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1557 if (!DBM::is_result($r)) {
1558 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1561 if (DBM::is_result($r)) {
1563 foreach ($r as $user) {
1564 $user_info = api_get_user($a, $user["id"]);
1566 if ($type == "xml") {
1567 $userlist[$k++.":user"] = $user_info;
1569 $userlist[] = $user_info;
1572 $userlist = ["users" => $userlist];
1574 throw new BadRequestException("User not found.");
1577 throw new BadRequestException("User not found.");
1580 return api_format_data("users", $type, $userlist);
1583 /// @TODO move to top of file or somewhere better
1584 api_register_func('api/users/search', 'api_users_search');
1587 * Return user objects
1589 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1591 * @param string $type Return format: json or xml
1593 * @return array|string
1594 * @throws NotFoundException if the results are empty.
1596 function api_users_lookup($type)
1600 if (x($_REQUEST['user_id'])) {
1601 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1603 $users[] = api_get_user(get_app(), $id);
1608 if (empty($users)) {
1609 throw new NotFoundException;
1612 return api_format_data("users", $type, ['users' => $users]);
1615 /// @TODO move to top of file or somewhere better
1616 api_register_func('api/users/lookup', 'api_users_lookup', true);
1619 * Returns statuses that match a specified query.
1621 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1623 * @param string $type Return format: json, xml, atom, rss
1625 * @return array|string
1626 * @throws BadRequestException if the "q" parameter is missing.
1628 function api_search($type)
1633 if (!x($_REQUEST, 'q')) {
1634 throw new BadRequestException("q parameter is required.");
1637 if (x($_REQUEST, 'rpp')) {
1638 $count = $_REQUEST['rpp'];
1639 } elseif (x($_REQUEST, 'count')) {
1640 $count = $_REQUEST['count'];
1645 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1646 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1647 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1649 $start = $page * $count;
1652 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1656 "SELECT ".item_fieldlists()."
1657 FROM `item` ".item_joins()."
1658 WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1659 AND `item`.`body` LIKE CONCAT('%',?,'%')
1662 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
1668 $data['status'] = api_format_items(dba::inArray($r), api_get_user(get_app()));
1670 return api_format_data("statuses", $type, $data);
1673 /// @TODO move to top of file or somewhere better
1674 api_register_func('api/search/tweets', 'api_search', true);
1675 api_register_func('api/search', 'api_search', true);
1678 * Returns the most recent statuses posted by the user and the users they follow.
1680 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1682 * @param string $type Return type (atom, rss, xml, json)
1684 * @todo Optional parameters
1685 * @todo Add reply info
1687 function api_statuses_home_timeline($type)
1691 if (api_user() === false) {
1692 throw new ForbiddenException();
1695 unset($_REQUEST["user_id"]);
1696 unset($_GET["user_id"]);
1698 unset($_REQUEST["screen_name"]);
1699 unset($_GET["screen_name"]);
1701 $user_info = api_get_user($a);
1702 // get last newtork messages
1705 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1706 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1710 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1711 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1712 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1713 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1714 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1716 $start = $page * $count;
1720 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1722 if ($exclude_replies > 0) {
1723 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1725 if ($conversation_id > 0) {
1726 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1730 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1731 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1732 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1733 `contact`.`id` AS `cid`
1735 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1736 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1737 WHERE `item`.`uid` = %d AND `verb` = '%s'
1738 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1741 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1743 dbesc(ACTIVITY_POST),
1749 $ret = api_format_items($r, $user_info, false, $type);
1751 // Set all posts from the query above to seen
1753 foreach ($r as $item) {
1754 $idarray[] = intval($item["id"]);
1757 $idlist = implode(",", $idarray);
1759 if ($idlist != "") {
1760 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1763 q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1767 $data = ['status' => $ret];
1771 $data = api_rss_extra($a, $data, $user_info);
1775 return api_format_data("statuses", $type, $data);
1778 /// @TODO move to top of file or somewhere better
1779 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1780 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1783 * Returns the most recent statuses from public users.
1785 * @param string $type Return type (atom, rss, xml, json)
1787 * @return array|string
1789 function api_statuses_public_timeline($type)
1793 if (api_user() === false) {
1794 throw new ForbiddenException();
1797 $user_info = api_get_user($a);
1798 // get last newtork messages
1801 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1802 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1806 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1807 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1808 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1809 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1810 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1812 $start = $page * $count;
1815 if ($exclude_replies && !$conversation_id) {
1817 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1821 "SELECT " . item_fieldlists() . "
1823 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1824 " . item_joins() . "
1825 STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1826 AND NOT `user`.`hidewall`
1828 AND NOT `thread`.`private`
1830 AND `thread`.`visible`
1831 AND NOT `thread`.`deleted`
1832 AND NOT `thread`.`moderated`
1833 AND `thread`.`iid` > ?
1835 ORDER BY `thread`.`iid` DESC
1836 LIMIT " . intval($start) . ", " . intval($count),
1841 $r = dba::inArray($r);
1844 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1846 if ($conversation_id > 0) {
1847 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1851 "SELECT " . item_fieldlists() . "
1853 " . item_joins() . "
1854 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1855 AND NOT `user`.`hidewall`
1857 AND NOT `item`.`private`
1859 AND `item`.`visible`
1860 AND NOT `item`.`deleted`
1861 AND NOT `item`.`moderated`
1864 ORDER BY `item`.`id` DESC
1865 LIMIT " . intval($start) . ", " . intval($count),
1870 $r = dba::inArray($r);
1873 $ret = api_format_items($r, $user_info, false, $type);
1875 $data = ['status' => $ret];
1879 $data = api_rss_extra($a, $data, $user_info);
1883 return api_format_data("statuses", $type, $data);
1886 /// @TODO move to top of file or somewhere better
1887 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1890 * Returns the most recent statuses posted by users this node knows about.
1892 * @brief Returns the list of public federated posts this node knows about
1894 * @param string $type Return format: json, xml, atom, rss
1895 * @return array|string
1896 * @throws ForbiddenException
1898 function api_statuses_networkpublic_timeline($type)
1902 if (api_user() === false) {
1903 throw new ForbiddenException();
1906 $user_info = api_get_user($a);
1908 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1909 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1912 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1913 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1917 $start = ($page - 1) * $count;
1921 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1925 "SELECT " . item_fieldlists() . "
1927 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1928 " . item_joins() . "
1929 WHERE `thread`.`uid` = 0
1931 AND NOT `thread`.`private`
1932 AND `thread`.`visible`
1933 AND NOT `thread`.`deleted`
1934 AND NOT `thread`.`moderated`
1935 AND `thread`.`iid` > ?
1937 ORDER BY `thread`.`iid` DESC
1938 LIMIT " . intval($start) . ", " . intval($count),
1943 $r = dba::inArray($r);
1945 $ret = api_format_items($r, $user_info, false, $type);
1947 $data = ['status' => $ret];
1951 $data = api_rss_extra($a, $data, $user_info);
1955 return api_format_data("statuses", $type, $data);
1958 /// @TODO move to top of file or somewhere better
1959 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1962 * Returns a single status.
1964 * @param string $type Return type (atom, rss, xml, json)
1966 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1968 function api_statuses_show($type)
1972 if (api_user() === false) {
1973 throw new ForbiddenException();
1976 $user_info = api_get_user($a);
1979 $id = intval($a->argv[3]);
1982 $id = intval($_REQUEST["id"]);
1987 $id = intval($a->argv[4]);
1990 logger('API: api_statuses_show: ' . $id);
1992 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1995 if ($conversation) {
1996 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1998 $sql_extra .= " AND `item`.`id` = %d";
2002 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2003 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2004 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2005 `contact`.`id` AS `cid`
2007 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2008 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2009 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2010 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2013 dbesc(ACTIVITY_POST),
2017 /// @TODO How about copying this to above methods which don't check $r ?
2018 if (!DBM::is_result($r)) {
2019 throw new BadRequestException("There is no status with this id.");
2022 $ret = api_format_items($r, $user_info, false, $type);
2024 if ($conversation) {
2025 $data = ['status' => $ret];
2026 return api_format_data("statuses", $type, $data);
2028 $data = ['status' => $ret[0]];
2029 return api_format_data("status", $type, $data);
2033 /// @TODO move to top of file or somewhere better
2034 api_register_func('api/statuses/show', 'api_statuses_show', true);
2038 * @param string $type Return type (atom, rss, xml, json)
2040 * @todo nothing to say?
2042 function api_conversation_show($type)
2046 if (api_user() === false) {
2047 throw new ForbiddenException();
2050 $user_info = api_get_user($a);
2053 $id = intval($a->argv[3]);
2054 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2055 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
2059 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2060 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2062 $start = $page*$count;
2065 $id = intval($_REQUEST["id"]);
2070 $id = intval($a->argv[4]);
2073 logger('API: api_conversation_show: '.$id);
2075 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
2076 if (DBM::is_result($r)) {
2077 $id = $r[0]["parent"];
2083 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2086 // Not sure why this query was so complicated. We should keep it here for a while,
2087 // just to make sure that we really don't need it.
2088 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
2089 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
2092 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2093 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2094 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2095 `contact`.`id` AS `cid`
2097 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2098 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2099 WHERE `item`.`parent` = %d AND `item`.`visible`
2100 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2101 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2102 AND `item`.`id`>%d $sql_extra
2103 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2106 dbesc(ACTIVITY_POST),
2112 if (!DBM::is_result($r)) {
2113 throw new BadRequestException("There is no status with this id.");
2116 $ret = api_format_items($r, $user_info, false, $type);
2118 $data = ['status' => $ret];
2119 return api_format_data("statuses", $type, $data);
2122 /// @TODO move to top of file or somewhere better
2123 api_register_func('api/conversation/show', 'api_conversation_show', true);
2124 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2129 * @param string $type Return type (atom, rss, xml, json)
2131 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2133 function api_statuses_repeat($type)
2139 if (api_user() === false) {
2140 throw new ForbiddenException();
2146 $id = intval($a->argv[3]);
2149 $id = intval($_REQUEST["id"]);
2154 $id = intval($a->argv[4]);
2157 logger('API: api_statuses_repeat: '.$id);
2160 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2161 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2162 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2163 `contact`.`id` AS `cid`
2165 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2166 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2167 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2168 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2169 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2170 AND `item`.`id`=%d",
2174 /// @TODO other style than above functions!
2175 if (DBM::is_result($r) && $r[0]['body'] != "") {
2176 if (strpos($r[0]['body'], "[/share]") !== false) {
2177 $pos = strpos($r[0]['body'], "[share");
2178 $post = substr($r[0]['body'], $pos);
2180 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2182 $post .= $r[0]['body'];
2183 $post .= "[/share]";
2185 $_REQUEST['body'] = $post;
2186 $_REQUEST['profile_uid'] = api_user();
2187 $_REQUEST['type'] = 'wall';
2188 $_REQUEST['api_source'] = true;
2190 if (!x($_REQUEST, "source")) {
2191 $_REQUEST["source"] = api_source();
2196 throw new ForbiddenException();
2199 // this should output the last post (the one we just posted).
2201 return api_status_show($type);
2204 /// @TODO move to top of file or somewhere better
2205 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2208 * Destroys a specific status.
2210 * @param string $type Return type (atom, rss, xml, json)
2212 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2214 function api_statuses_destroy($type)
2218 if (api_user() === false) {
2219 throw new ForbiddenException();
2225 $id = intval($a->argv[3]);
2228 $id = intval($_REQUEST["id"]);
2233 $id = intval($a->argv[4]);
2236 logger('API: api_statuses_destroy: '.$id);
2238 $ret = api_statuses_show($type);
2240 Item::deleteById($id);
2245 /// @TODO move to top of file or somewhere better
2246 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2249 * Returns the most recent mentions.
2251 * @param string $type Return type (atom, rss, xml, json)
2253 * @see http://developer.twitter.com/doc/get/statuses/mentions
2255 function api_statuses_mentions($type)
2259 if (api_user() === false) {
2260 throw new ForbiddenException();
2263 unset($_REQUEST["user_id"]);
2264 unset($_GET["user_id"]);
2266 unset($_REQUEST["screen_name"]);
2267 unset($_GET["screen_name"]);
2269 $user_info = api_get_user($a);
2270 // get last newtork messages
2274 $since_id = defaults($_REQUEST, 'since_id', 0);
2275 $max_id = defaults($_REQUEST, 'max_id' , 0);
2276 $count = defaults($_REQUEST, 'count' , 20);
2277 $page = defaults($_REQUEST, 'page' , 1);
2282 $start = ($page - 1) * $count;
2284 // Ugly code - should be changed
2285 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2286 $myurl = substr($myurl, strpos($myurl, '://') + 3);
2287 $myurl = str_replace('www.', '', $myurl);
2292 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2296 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2297 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2298 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2299 `contact`.`id` AS `cid`
2300 FROM `item` FORCE INDEX (`uid_id`)
2301 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2302 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2303 WHERE `item`.`uid` = %d AND `verb` = '%s'
2304 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2305 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2306 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2309 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2311 dbesc(ACTIVITY_POST),
2312 dbesc(protect_sprintf($myurl)),
2313 dbesc(protect_sprintf($myurl)),
2320 $ret = api_format_items($r, $user_info, false, $type);
2322 $data = ['status' => $ret];
2326 $data = api_rss_extra($a, $data, $user_info);
2330 return api_format_data("statuses", $type, $data);
2333 /// @TODO move to top of file or somewhere better
2334 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2335 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2338 * Returns the most recent statuses posted by the user.
2340 * @brief Returns a user's public timeline
2342 * @param string $type Either "json" or "xml"
2343 * @return string|array
2344 * @throws ForbiddenException
2345 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2347 function api_statuses_user_timeline($type)
2351 if (api_user() === false) {
2352 throw new ForbiddenException();
2355 $user_info = api_get_user($a);
2358 "api_statuses_user_timeline: api_user: ". api_user() .
2359 "\nuser_info: ".print_r($user_info, true) .
2360 "\n_REQUEST: ".print_r($_REQUEST, true),
2364 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2365 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2366 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2367 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2370 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2371 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2375 $start = ($page - 1) * $count;
2378 if ($user_info['self'] == 1) {
2379 $sql_extra .= " AND `item`.`wall` = 1 ";
2382 if ($exclude_replies > 0) {
2383 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2386 if ($conversation_id > 0) {
2387 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2391 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2395 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2396 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2397 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2398 `contact`.`id` AS `cid`
2399 FROM `item` FORCE INDEX (`uid_contactid_id`)
2400 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2401 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2402 WHERE `item`.`uid` = %d AND `verb` = '%s'
2403 AND `item`.`contact-id` = %d
2404 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2406 AND `item`.`id` > %d
2407 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2409 dbesc(ACTIVITY_POST),
2410 intval($user_info['cid']),
2416 $ret = api_format_items($r, $user_info, true, $type);
2418 $data = ['status' => $ret];
2422 $data = api_rss_extra($a, $data, $user_info);
2426 return api_format_data("statuses", $type, $data);
2429 /// @TODO move to top of file or somewhere better
2430 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2433 * Star/unstar an item.
2434 * param: id : id of the item
2436 * @param string $type Return type (atom, rss, xml, json)
2438 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2440 function api_favorites_create_destroy($type)
2444 if (api_user() === false) {
2445 throw new ForbiddenException();
2448 // for versioned api.
2449 /// @TODO We need a better global soluton
2450 $action_argv_id = 2;
2451 if ($a->argv[1] == "1.1") {
2452 $action_argv_id = 3;
2455 if ($a->argc <= $action_argv_id) {
2456 throw new BadRequestException("Invalid request.");
2458 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2459 if ($a->argc == $action_argv_id + 2) {
2460 $itemid = intval($a->argv[$action_argv_id + 1]);
2462 /// @TODO use x() to check if _REQUEST contains 'id'
2463 $itemid = intval($_REQUEST['id']);
2466 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2468 if (!DBM::is_result($item) || count($item) == 0) {
2469 throw new BadRequestException("Invalid item.");
2474 $item[0]['starred'] = 1;
2477 $item[0]['starred'] = 0;
2480 throw new BadRequestException("Invalid action ".$action);
2483 $r = Item::update(['starred' => $item[0]['starred']], ['id' => $itemid]);
2486 throw new InternalServerErrorException("DB error");
2490 $user_info = api_get_user($a);
2491 $rets = api_format_items($item, $user_info, false, $type);
2494 $data = ['status' => $ret];
2498 $data = api_rss_extra($a, $data, $user_info);
2501 return api_format_data("status", $type, $data);
2504 /// @TODO move to top of file or somewhere better
2505 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2506 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2509 * Returns the most recent favorite statuses.
2511 * @param string $type Return type (atom, rss, xml, json)
2513 * @return string|array
2515 function api_favorites($type)
2521 if (api_user() === false) {
2522 throw new ForbiddenException();
2527 $user_info = api_get_user($a);
2529 // in friendica starred item are private
2530 // return favorites only for self
2531 logger('api_favorites: self:' . $user_info['self']);
2533 if ($user_info['self'] == 0) {
2539 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2540 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2541 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2542 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2547 $start = $page*$count;
2550 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2554 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2555 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2556 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2557 `contact`.`id` AS `cid`
2558 FROM `item`, `contact`
2559 WHERE `item`.`uid` = %d
2560 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2561 AND `item`.`starred` = 1
2562 AND `contact`.`id` = `item`.`contact-id`
2563 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2566 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2573 $ret = api_format_items($r, $user_info, false, $type);
2576 $data = ['status' => $ret];
2580 $data = api_rss_extra($a, $data, $user_info);
2583 return api_format_data("statuses", $type, $data);
2586 /// @TODO move to top of file or somewhere better
2587 api_register_func('api/favorites', 'api_favorites', true);
2591 * @param array $item
2592 * @param array $recipient
2593 * @param array $sender
2597 function api_format_messages($item, $recipient, $sender)
2599 // standard meta information
2601 'id' => $item['id'],
2602 'sender_id' => $sender['id'] ,
2604 'recipient_id' => $recipient['id'],
2605 'created_at' => api_date($item['created']),
2606 'sender_screen_name' => $sender['screen_name'],
2607 'recipient_screen_name' => $recipient['screen_name'],
2608 'sender' => $sender,
2609 'recipient' => $recipient,
2611 'friendica_seen' => $item['seen'],
2612 'friendica_parent_uri' => $item['parent-uri'],
2615 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2616 unset($ret["sender"]["uid"]);
2617 unset($ret["sender"]["self"]);
2618 unset($ret["recipient"]["uid"]);
2619 unset($ret["recipient"]["self"]);
2621 //don't send title to regular StatusNET requests to avoid confusing these apps
2622 if (x($_GET, 'getText')) {
2623 $ret['title'] = $item['title'];
2624 if ($_GET['getText'] == 'html') {
2625 $ret['text'] = BBCode::convert($item['body'], false);
2626 } elseif ($_GET['getText'] == 'plain') {
2627 $ret['text'] = trim(html2plain(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2630 $ret['text'] = $item['title'] . "\n" . html2plain(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2632 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2633 unset($ret['sender']);
2634 unset($ret['recipient']);
2642 * @param array $item
2646 function api_convert_item($item)
2648 $body = $item['body'];
2649 $attachments = api_get_attachments($body);
2651 // Workaround for ostatus messages where the title is identically to the body
2652 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2653 $statusbody = trim(html2plain($html, 0));
2655 // handle data: images
2656 $statusbody = api_format_items_embeded_images($item, $statusbody);
2658 $statustitle = trim($item['title']);
2660 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2661 $statustext = trim($statusbody);
2663 $statustext = trim($statustitle."\n\n".$statusbody);
2666 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2667 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2670 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2672 // Workaround for clients with limited HTML parser functionality
2673 $search = ["<br>", "<blockquote>", "</blockquote>",
2674 "<h1>", "</h1>", "<h2>", "</h2>",
2675 "<h3>", "</h3>", "<h4>", "</h4>",
2676 "<h5>", "</h5>", "<h6>", "</h6>"];
2677 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2678 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2679 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2680 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2681 $statushtml = str_replace($search, $replace, $statushtml);
2683 if ($item['title'] != "") {
2684 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2688 $oldtext = $statushtml;
2689 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2690 } while ($oldtext != $statushtml);
2692 if (substr($statushtml, 0, 4) == '<br>') {
2693 $statushtml = substr($statushtml, 4);
2696 if (substr($statushtml, 0, -4) == '<br>') {
2697 $statushtml = substr($statushtml, -4);
2700 // feeds without body should contain the link
2701 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2702 $statushtml .= BBCode::convert($item['plink']);
2705 $entities = api_get_entitities($statustext, $body);
2708 "text" => $statustext,
2709 "html" => $statushtml,
2710 "attachments" => $attachments,
2711 "entities" => $entities
2717 * @param string $body
2719 * @return array|false
2721 function api_get_attachments(&$body)
2724 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2726 $URLSearchString = "^\[\]";
2727 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2735 foreach ($images[1] as $image) {
2736 $imagedata = Image::getInfoFromURL($image);
2739 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2743 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2744 foreach ($images[0] as $orig) {
2745 $body = str_replace($orig, "", $body);
2749 return $attachments;
2754 * @param string $text
2755 * @param string $bbcode
2758 * @todo Links at the first character of the post
2760 function api_get_entitities(&$text, $bbcode)
2762 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2764 if ($include_entities != "true") {
2765 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2767 foreach ($images[1] as $image) {
2768 $replace = proxy_url($image);
2769 $text = str_replace($image, $replace, $text);
2774 $bbcode = BBCode::cleanPictureLinks($bbcode);
2776 // Change pure links in text to bbcode uris
2777 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2780 $entities["hashtags"] = [];
2781 $entities["symbols"] = [];
2782 $entities["urls"] = [];
2783 $entities["user_mentions"] = [];
2785 $URLSearchString = "^\[\]";
2787 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2789 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2790 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2791 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2793 $bbcode = preg_replace(
2794 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2795 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2798 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2800 $bbcode = preg_replace(
2801 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2802 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2805 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2807 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2809 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2810 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2813 foreach ($urls[1] as $id => $url) {
2814 //$start = strpos($text, $url, $offset);
2815 $start = iconv_strpos($text, $url, 0, "UTF-8");
2816 if (!($start === false)) {
2817 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2821 ksort($ordered_urls);
2824 //foreach ($urls[1] AS $id=>$url) {
2825 foreach ($ordered_urls as $url) {
2826 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2827 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2829 $display_url = $url["title"];
2831 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2832 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2834 if (strlen($display_url) > 26) {
2835 $display_url = substr($display_url, 0, 25)."…";
2839 //$start = strpos($text, $url, $offset);
2840 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2841 if (!($start === false)) {
2842 $entities["urls"][] = ["url" => $url["url"],
2843 "expanded_url" => $url["url"],
2844 "display_url" => $display_url,
2845 "indices" => [$start, $start+strlen($url["url"])]];
2846 $offset = $start + 1;
2850 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2851 $ordered_images = [];
2852 foreach ($images[1] as $image) {
2853 //$start = strpos($text, $url, $offset);
2854 $start = iconv_strpos($text, $image, 0, "UTF-8");
2855 if (!($start === false)) {
2856 $ordered_images[$start] = $image;
2859 //$entities["media"] = array();
2862 foreach ($ordered_images as $url) {
2863 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2864 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2866 if (strlen($display_url) > 26) {
2867 $display_url = substr($display_url, 0, 25)."…";
2870 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2871 if (!($start === false)) {
2872 $image = Image::getInfoFromURL($url);
2874 // If image cache is activated, then use the following sizes:
2875 // thumb (150), small (340), medium (600) and large (1024)
2876 if (!Config::get("system", "proxy_disabled")) {
2877 $media_url = proxy_url($url);
2880 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2881 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2883 if (($image[0] > 150) || ($image[1] > 150)) {
2884 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2885 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2888 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2889 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2891 if (($image[0] > 600) || ($image[1] > 600)) {
2892 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2893 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2897 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2900 $entities["media"][] = [
2902 "id_str" => (string)$start+1,
2903 "indices" => [$start, $start+strlen($url)],
2904 "media_url" => normalise_link($media_url),
2905 "media_url_https" => $media_url,
2907 "display_url" => $display_url,
2908 "expanded_url" => $url,
2912 $offset = $start + 1;
2921 * @param array $item
2922 * @param string $text
2926 function api_format_items_embeded_images($item, $text)
2928 $text = preg_replace_callback(
2929 '|data:image/([^;]+)[^=]+=*|m',
2930 function () use ($item) {
2931 return System::baseUrl() . '/display/' . $item['guid'];
2939 * @brief return <a href='url'>name</a> as array
2941 * @param string $txt text
2946 function api_contactlink_to_array($txt)
2949 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2950 if ($r && count($match)==3) {
2952 'name' => $match[2],
2966 * @brief return likes, dislikes and attend status for item
2968 * @param array $item array
2969 * @param string $type Return type (atom, rss, xml, json)
2972 * likes => int count,
2973 * dislikes => int count
2975 function api_format_items_activities(&$item, $type = "json")
2984 'attendmaybe' => [],
2989 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2990 intval($item['uid']),
2994 foreach ($items as $i) {
2995 // not used as result should be structured like other user data
2996 //builtin_activity_puller($i, $activities);
2998 // get user data and add it to the array of the activity
2999 $user = api_get_user($a, $i['author-link']);
3000 switch ($i['verb']) {
3002 $activities['like'][] = $user;
3004 case ACTIVITY_DISLIKE:
3005 $activities['dislike'][] = $user;
3007 case ACTIVITY_ATTEND:
3008 $activities['attendyes'][] = $user;
3010 case ACTIVITY_ATTENDNO:
3011 $activities['attendno'][] = $user;
3013 case ACTIVITY_ATTENDMAYBE:
3014 $activities['attendmaybe'][] = $user;
3021 if ($type == "xml") {
3022 $xml_activities = [];
3023 foreach ($activities as $k => $v) {
3024 // change xml element from "like" to "friendica:like"
3025 $xml_activities["friendica:".$k] = $v;
3026 // add user data into xml output
3028 foreach ($v as $user) {
3029 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
3032 $activities = $xml_activities;
3040 * @brief return data from profiles
3042 * @param array $profile_row array containing data from db table 'profile'
3045 function api_format_items_profiles($profile_row)
3048 'profile_id' => $profile_row['id'],
3049 'profile_name' => $profile_row['profile-name'],
3050 'is_default' => $profile_row['is-default'] ? true : false,
3051 'hide_friends' => $profile_row['hide-friends'] ? true : false,
3052 'profile_photo' => $profile_row['photo'],
3053 'profile_thumb' => $profile_row['thumb'],
3054 'publish' => $profile_row['publish'] ? true : false,
3055 'net_publish' => $profile_row['net-publish'] ? true : false,
3056 'description' => $profile_row['pdesc'],
3057 'date_of_birth' => $profile_row['dob'],
3058 'address' => $profile_row['address'],
3059 'city' => $profile_row['locality'],
3060 'region' => $profile_row['region'],
3061 'postal_code' => $profile_row['postal-code'],
3062 'country' => $profile_row['country-name'],
3063 'hometown' => $profile_row['hometown'],
3064 'gender' => $profile_row['gender'],
3065 'marital' => $profile_row['marital'],
3066 'marital_with' => $profile_row['with'],
3067 'marital_since' => $profile_row['howlong'],
3068 'sexual' => $profile_row['sexual'],
3069 'politic' => $profile_row['politic'],
3070 'religion' => $profile_row['religion'],
3071 'public_keywords' => $profile_row['pub_keywords'],
3072 'private_keywords' => $profile_row['prv_keywords'],
3073 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
3074 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
3075 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
3076 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
3077 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
3078 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
3079 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
3080 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
3081 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
3082 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
3083 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
3084 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
3085 'homepage' => $profile_row['homepage'],
3092 * @brief format items to be returned by api
3094 * @param array $r array of items
3095 * @param array $user_info
3096 * @param bool $filter_user filter items by $user_info
3097 * @param string $type Return type (atom, rss, xml, json)
3099 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
3105 foreach ($r as $item) {
3106 localize_item($item);
3107 list($status_user, $owner_user) = api_item_get_user($a, $item);
3109 // Look if the posts are matching if they should be filtered by user id
3110 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3114 $in_reply_to = api_in_reply_to($item);
3116 $converted = api_convert_item($item);
3118 if ($type == "xml") {
3119 $geo = "georss:point";
3125 'text' => $converted["text"],
3126 'truncated' => false,
3127 'created_at'=> api_date($item['created']),
3128 'in_reply_to_status_id' => $in_reply_to['status_id'],
3129 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3130 'source' => (($item['app']) ? $item['app'] : 'web'),
3131 'id' => intval($item['id']),
3132 'id_str' => (string) intval($item['id']),
3133 'in_reply_to_user_id' => $in_reply_to['user_id'],
3134 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3135 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3137 'favorited' => $item['starred'] ? true : false,
3138 'user' => $status_user ,
3139 'friendica_owner' => $owner_user,
3140 //'entities' => NULL,
3141 'statusnet_html' => $converted["html"],
3142 'statusnet_conversation_id' => $item['parent'],
3143 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3144 'friendica_activities' => api_format_items_activities($item, $type),
3147 if (count($converted["attachments"]) > 0) {
3148 $status["attachments"] = $converted["attachments"];
3151 if (count($converted["entities"]) > 0) {
3152 $status["entities"] = $converted["entities"];
3155 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
3156 $status["source"] = ContactSelector::networkToName($item['item_network'], $user_info['url']);
3157 } elseif (($item['item_network'] != "") && (ContactSelector::networkToName($item['item_network'], $user_info['url']) != $status["source"])) {
3158 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['item_network'], $user_info['url']).')');
3162 // Retweets are only valid for top postings
3163 // It doesn't work reliable with the link if its a feed
3164 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
3166 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
3169 if ($item["id"] == $item["parent"]) {
3170 $retweeted_item = api_share_as_retweet($item);
3171 if ($retweeted_item !== false) {
3172 $retweeted_status = $status;
3174 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
3175 } catch (BadRequestException $e) {
3176 // user not found. should be found?
3177 /// @todo check if the user should be always found
3178 $retweeted_status["user"] = [];
3181 $rt_converted = api_convert_item($retweeted_item);
3183 $retweeted_status['text'] = $rt_converted["text"];
3184 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3185 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3186 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3187 $status['retweeted_status'] = $retweeted_status;
3191 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3192 unset($status["user"]["uid"]);
3193 unset($status["user"]["self"]);
3195 if ($item["coord"] != "") {
3196 $coords = explode(' ', $item["coord"]);
3197 if (count($coords) == 2) {
3198 if ($type == "json") {
3199 $status["geo"] = ['type' => 'Point',
3200 'coordinates' => [(float) $coords[0],
3201 (float) $coords[1]]];
3202 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3203 $status["georss:point"] = $item["coord"];
3213 * Returns the remaining number of API requests available to the user before the API limit is reached.
3215 * @param string $type Return type (atom, rss, xml, json)
3217 * @return array|string
3219 function api_account_rate_limit_status($type)
3221 if ($type == "xml") {
3223 'remaining-hits' => '150',
3224 '@attributes' => ["type" => "integer"],
3225 'hourly-limit' => '150',
3226 '@attributes2' => ["type" => "integer"],
3227 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3228 '@attributes3' => ["type" => "datetime"],
3229 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3230 '@attributes4' => ["type" => "integer"],
3234 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3235 'remaining_hits' => '150',
3236 'hourly_limit' => '150',
3237 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3241 return api_format_data('hash', $type, ['hash' => $hash]);
3244 /// @TODO move to top of file or somewhere better
3245 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3248 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3250 * @param string $type Return type (atom, rss, xml, json)
3252 * @return array|string
3254 function api_help_test($type)
3256 if ($type == 'xml') {
3262 return api_format_data('ok', $type, ["ok" => $ok]);
3265 /// @TODO move to top of file or somewhere better
3266 api_register_func('api/help/test', 'api_help_test', false);
3270 * @param string $type Return type (atom, rss, xml, json)
3272 * @return array|string
3274 function api_lists($type)
3277 /// @TODO $ret is not filled here?
3278 return api_format_data('lists', $type, ["lists_list" => $ret]);
3281 /// @TODO move to top of file or somewhere better
3282 api_register_func('api/lists', 'api_lists', true);
3285 * Returns all lists the user subscribes to.
3287 * @param string $type Return type (atom, rss, xml, json)
3289 * @return array|string
3290 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3292 function api_lists_list($type)
3295 /// @TODO $ret is not filled here?
3296 return api_format_data('lists', $type, ["lists_list" => $ret]);
3299 /// @TODO move to top of file or somewhere better
3300 api_register_func('api/lists/list', 'api_lists_list', true);
3303 * Considers friends and followers lists to be private and won't return
3304 * anything if any user_id parameter is passed.
3306 * @brief Returns either the friends of the follower list
3308 * @param string $qtype Either "friends" or "followers"
3309 * @return boolean|array
3310 * @throws ForbiddenException
3312 function api_statuses_f($qtype)
3316 if (api_user() === false) {
3317 throw new ForbiddenException();
3321 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3322 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3326 $start = ($page - 1) * $count;
3328 $user_info = api_get_user($a);
3330 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3331 /* this is to stop Hotot to load friends multiple times
3332 * I'm not sure if I'm missing return something or
3333 * is a bug in hotot. Workaround, meantime
3337 return array('$users' => $ret);*/
3342 if ($qtype == 'friends') {
3343 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3344 } elseif ($qtype == 'followers') {
3345 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3348 // friends and followers only for self
3349 if ($user_info['self'] == 0) {
3350 $sql_extra = " AND false ";
3353 if ($qtype == 'blocks') {
3354 $sql_filter = 'AND `blocked` AND NOT `pending`';
3355 } elseif ($qtype == 'incoming') {
3356 $sql_filter = 'AND `pending`';
3358 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3376 foreach ($r as $cid) {
3377 $user = api_get_user($a, $cid['nurl']);
3378 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3379 unset($user["uid"]);
3380 unset($user["self"]);
3387 return ['user' => $ret];
3392 * Returns the user's friends.
3394 * @brief Returns the list of friends of the provided user
3396 * @deprecated By Twitter API in favor of friends/list
3398 * @param string $type Either "json" or "xml"
3399 * @return boolean|string|array
3401 function api_statuses_friends($type)
3403 $data = api_statuses_f("friends");
3404 if ($data === false) {
3407 return api_format_data("users", $type, $data);
3411 * Returns the user's followers.
3413 * @brief Returns the list of followers of the provided user
3415 * @deprecated By Twitter API in favor of friends/list
3417 * @param string $type Either "json" or "xml"
3418 * @return boolean|string|array
3420 function api_statuses_followers($type)
3422 $data = api_statuses_f("followers");
3423 if ($data === false) {
3426 return api_format_data("users", $type, $data);
3429 /// @TODO move to top of file or somewhere better
3430 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3431 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3434 * Returns the list of blocked users
3436 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3438 * @param string $type Either "json" or "xml"
3440 * @return boolean|string|array
3442 function api_blocks_list($type)
3444 $data = api_statuses_f('blocks');
3445 if ($data === false) {
3448 return api_format_data("users", $type, $data);
3451 /// @TODO move to top of file or somewhere better
3452 api_register_func('api/blocks/list', 'api_blocks_list', true);
3455 * Returns the list of pending users IDs
3457 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3459 * @param string $type Either "json" or "xml"
3461 * @return boolean|string|array
3463 function api_friendships_incoming($type)
3465 $data = api_statuses_f('incoming');
3466 if ($data === false) {
3471 foreach ($data['user'] as $user) {
3472 $ids[] = $user['id'];
3475 return api_format_data("ids", $type, ['id' => $ids]);
3478 /// @TODO move to top of file or somewhere better
3479 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3482 * Returns the instance's configuration information.
3484 * @param string $type Return type (atom, rss, xml, json)
3486 * @return array|string
3488 function api_statusnet_config($type)
3492 $name = $a->config['sitename'];
3493 $server = $a->get_hostname();
3494 $logo = System::baseUrl() . '/images/friendica-64.png';
3495 $email = $a->config['admin_email'];
3496 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3497 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3498 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3499 if ($a->config['api_import_size']) {
3500 $textlimit = (string) $a->config['api_import_size'];
3502 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3503 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3506 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3507 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3508 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3509 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3510 'shorturllength' => '30',
3512 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3513 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3514 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3515 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3520 return api_format_data('config', $type, ['config' => $config]);
3523 /// @TODO move to top of file or somewhere better
3524 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3525 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3529 * @param string $type Return type (atom, rss, xml, json)
3531 * @return array|string
3533 function api_statusnet_version($type)
3536 $fake_statusnet_version = "0.9.7";
3538 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3541 /// @TODO move to top of file or somewhere better
3542 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3543 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3547 * @param string $type Return type (atom, rss, xml, json)
3549 * @todo use api_format_data() to return data
3551 function api_ff_ids($type)
3554 throw new ForbiddenException();
3561 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3564 "SELECT `pcontact`.`id` FROM `contact`
3565 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3566 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3569 if (!DBM::is_result($r)) {
3574 foreach ($r as $rr) {
3575 if ($stringify_ids) {
3578 $ids[] = intval($rr['id']);
3582 return api_format_data("ids", $type, ['id' => $ids]);
3586 * Returns the ID of every user the user is following.
3588 * @param string $type Return type (atom, rss, xml, json)
3590 * @return array|string
3591 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3593 function api_friends_ids($type)
3595 return api_ff_ids($type);
3599 * Returns the ID of every user following the user.
3601 * @param string $type Return type (atom, rss, xml, json)
3603 * @return array|string
3604 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3606 function api_followers_ids($type)
3608 return api_ff_ids($type);
3611 /// @TODO move to top of file or somewhere better
3612 api_register_func('api/friends/ids', 'api_friends_ids', true);
3613 api_register_func('api/followers/ids', 'api_followers_ids', true);
3616 * Sends a new direct message.
3618 * @param string $type Return type (atom, rss, xml, json)
3620 * @return array|string
3621 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3623 function api_direct_messages_new($type)
3628 if (api_user() === false) {
3629 throw new ForbiddenException();
3632 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3636 $sender = api_get_user($a);
3638 if ($_POST['screen_name']) {
3640 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3642 dbesc($_POST['screen_name'])
3645 // Selecting the id by priority, friendica first
3646 api_best_nickname($r);
3648 $recipient = api_get_user($a, $r[0]['nurl']);
3650 $recipient = api_get_user($a, $_POST['user_id']);
3655 if (x($_REQUEST, 'replyto')) {
3657 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3659 intval($_REQUEST['replyto'])
3661 $replyto = $r[0]['parent-uri'];
3662 $sub = $r[0]['title'];
3664 if (x($_REQUEST, 'title')) {
3665 $sub = $_REQUEST['title'];
3667 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3671 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3674 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3675 $ret = api_format_messages($r[0], $recipient, $sender);
3677 $ret = ["error"=>$id];
3680 $data = ['direct_message'=>$ret];
3685 $data = api_rss_extra($a, $data, $sender);
3688 return api_format_data("direct-messages", $type, $data);
3691 /// @TODO move to top of file or somewhere better
3692 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3695 * Destroys a direct message.
3697 * @brief delete a direct_message from mail table through api
3699 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3701 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3703 function api_direct_messages_destroy($type)
3707 if (api_user() === false) {
3708 throw new ForbiddenException();
3712 $user_info = api_get_user($a);
3714 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3716 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3717 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3718 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3720 $uid = $user_info['uid'];
3721 // error if no id or parenturi specified (for clients posting parent-uri as well)
3722 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3723 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3724 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3727 // BadRequestException if no id specified (for clients using Twitter API)
3729 throw new BadRequestException('Message id not specified');
3732 // add parent-uri to sql command if specified by calling app
3733 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3735 // get data of the specified message id
3737 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3742 // error message if specified id is not in database
3743 if (!DBM::is_result($r)) {
3744 if ($verbose == "true") {
3745 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3746 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3748 /// @todo BadRequestException ok for Twitter API clients?
3749 throw new BadRequestException('message id not in database');
3754 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3759 if ($verbose == "true") {
3762 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3763 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3765 $answer = ['result' => 'error', 'message' => 'unknown error'];
3766 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3769 /// @todo return JSON data like Twitter API not yet implemented
3772 /// @TODO move to top of file or somewhere better
3773 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3777 * @param string $type Return type (atom, rss, xml, json)
3778 * @param string $box
3779 * @param string $verbose
3781 * @return array|string
3783 function api_direct_messages_box($type, $box, $verbose)
3787 if (api_user() === false) {
3788 throw new ForbiddenException();
3792 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3793 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3798 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3799 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3801 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3802 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3805 unset($_REQUEST["user_id"]);
3806 unset($_GET["user_id"]);
3808 unset($_REQUEST["screen_name"]);
3809 unset($_GET["screen_name"]);
3811 $user_info = api_get_user($a);
3812 $profile_url = $user_info["url"];
3815 $start = $page * $count;
3820 if ($box=="sentbox") {
3821 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3822 } elseif ($box == "conversation") {
3823 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3824 } elseif ($box == "all") {
3825 $sql_extra = "true";
3826 } elseif ($box == "inbox") {
3827 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3831 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3834 if ($user_id != "") {
3835 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3836 } elseif ($screen_name !="") {
3837 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3841 "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",
3847 if ($verbose == "true" && !DBM::is_result($r)) {
3848 $answer = ['result' => 'error', 'message' => 'no mails available'];
3849 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3853 foreach ($r as $item) {
3854 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3855 $recipient = $user_info;
3856 $sender = api_get_user($a, normalise_link($item['contact-url']));
3857 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3858 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3859 $sender = $user_info;
3862 $ret[] = api_format_messages($item, $recipient, $sender);
3866 $data = ['direct_message' => $ret];
3870 $data = api_rss_extra($a, $data, $user_info);
3873 return api_format_data("direct-messages", $type, $data);
3877 * Returns the most recent direct messages sent by the user.
3879 * @param string $type Return type (atom, rss, xml, json)
3881 * @return array|string
3882 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3884 function api_direct_messages_sentbox($type)
3886 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3887 return api_direct_messages_box($type, "sentbox", $verbose);
3891 * Returns the most recent direct messages sent to the user.
3893 * @param string $type Return type (atom, rss, xml, json)
3895 * @return array|string
3896 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3898 function api_direct_messages_inbox($type)
3900 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3901 return api_direct_messages_box($type, "inbox", $verbose);
3906 * @param string $type Return type (atom, rss, xml, json)
3908 * @return array|string
3910 function api_direct_messages_all($type)
3912 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3913 return api_direct_messages_box($type, "all", $verbose);
3918 * @param string $type Return type (atom, rss, xml, json)
3920 * @return array|string
3922 function api_direct_messages_conversation($type)
3924 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3925 return api_direct_messages_box($type, "conversation", $verbose);
3928 /// @TODO move to top of file or somewhere better
3929 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3930 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3931 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3932 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3935 * Returns an OAuth Request Token.
3937 * @see https://oauth.net/core/1.0/#auth_step1
3939 function api_oauth_request_token()
3941 $oauth1 = new FKOAuth1();
3943 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3944 } catch (Exception $e) {
3945 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3953 * Returns an OAuth Access Token.
3955 * @return array|string
3956 * @see https://oauth.net/core/1.0/#auth_step3
3958 function api_oauth_access_token()
3960 $oauth1 = new FKOAuth1();
3962 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3963 } catch (Exception $e) {
3964 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3971 /// @TODO move to top of file or somewhere better
3972 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3973 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3977 * @brief delete a complete photoalbum with all containing photos from database through api
3979 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3982 function api_fr_photoalbum_delete($type)
3984 if (api_user() === false) {
3985 throw new ForbiddenException();
3988 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3990 // we do not allow calls without album string
3992 throw new BadRequestException("no albumname specified");
3994 // check if album is existing
3996 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4000 if (!DBM::is_result($r)) {
4001 throw new BadRequestException("album not available");
4004 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4005 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4006 foreach ($r as $rr) {
4008 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4009 intval(local_user()),
4010 dbesc($rr['resource-id'])
4013 if (!DBM::is_result($photo_item)) {
4014 throw new InternalServerErrorException("problem with deleting items occured");
4016 Item::deleteById($photo_item[0]['id']);
4019 // now let's delete all photos from the album
4020 $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
4022 // return success of deletion or error message
4024 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4025 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4027 throw new InternalServerErrorException("unknown error - deleting from database failed");
4032 * @brief update the name of the album for all photos of an album
4034 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4037 function api_fr_photoalbum_update($type)
4039 if (api_user() === false) {
4040 throw new ForbiddenException();
4043 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
4044 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
4046 // we do not allow calls without album string
4048 throw new BadRequestException("no albumname specified");
4050 if ($album_new == "") {
4051 throw new BadRequestException("no new albumname specified");
4053 // check if album is existing
4055 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4059 if (!DBM::is_result($r)) {
4060 throw new BadRequestException("album not available");
4062 // now let's update all photos to the albumname
4064 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
4070 // return success of updating or error message
4072 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4073 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4075 throw new InternalServerErrorException("unknown error - updating in database failed");
4081 * @brief list all photos of the authenticated user
4083 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4086 function api_fr_photos_list($type)
4088 if (api_user() === false) {
4089 throw new ForbiddenException();
4092 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4093 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4094 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4095 intval(local_user())
4098 'image/jpeg' => 'jpg',
4099 'image/png' => 'png',
4100 'image/gif' => 'gif'
4102 $data = ['photo'=>[]];
4103 if (DBM::is_result($r)) {
4104 foreach ($r as $rr) {
4106 $photo['id'] = $rr['resource-id'];
4107 $photo['album'] = $rr['album'];
4108 $photo['filename'] = $rr['filename'];
4109 $photo['type'] = $rr['type'];
4110 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4111 $photo['created'] = $rr['created'];
4112 $photo['edited'] = $rr['edited'];
4113 $photo['desc'] = $rr['desc'];
4115 if ($type == "xml") {
4116 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4118 $photo['thumb'] = $thumb;
4119 $data['photo'][] = $photo;
4123 return api_format_data("photos", $type, $data);
4127 * @brief upload a new photo or change an existing photo
4129 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4132 function api_fr_photo_create_update($type)
4134 if (api_user() === false) {
4135 throw new ForbiddenException();
4138 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4139 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4140 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4141 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4142 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4143 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4144 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4145 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4146 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4148 // do several checks on input parameters
4149 // we do not allow calls without album string
4150 if ($album == null) {
4151 throw new BadRequestException("no albumname specified");
4153 // if photo_id == null --> we are uploading a new photo
4154 if ($photo_id == null) {
4157 // error if no media posted in create-mode
4158 if (!x($_FILES, 'media')) {
4160 throw new BadRequestException("no media data submitted");
4163 // album_new will be ignored in create-mode
4168 // check if photo is existing in database
4170 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4175 if (!DBM::is_result($r)) {
4176 throw new BadRequestException("photo not available");
4180 // checks on acl strings provided by clients
4181 $acl_input_error = false;
4182 $acl_input_error |= check_acl_input($allow_cid);
4183 $acl_input_error |= check_acl_input($deny_cid);
4184 $acl_input_error |= check_acl_input($allow_gid);
4185 $acl_input_error |= check_acl_input($deny_gid);
4186 if ($acl_input_error) {
4187 throw new BadRequestException("acl data invalid");
4189 // now let's upload the new media in create-mode
4190 if ($mode == "create") {
4191 $media = $_FILES['media'];
4192 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4194 // return success of updating or error message
4195 if (!is_null($data)) {
4196 return api_format_data("photo_create", $type, $data);
4198 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4202 // now let's do the changes in update-mode
4203 if ($mode == "update") {
4206 if (!is_null($desc)) {
4207 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4210 if (!is_null($album_new)) {
4211 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4214 if (!is_null($allow_cid)) {
4215 $allow_cid = trim($allow_cid);
4216 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4219 if (!is_null($deny_cid)) {
4220 $deny_cid = trim($deny_cid);
4221 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4224 if (!is_null($allow_gid)) {
4225 $allow_gid = trim($allow_gid);
4226 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4229 if (!is_null($deny_gid)) {
4230 $deny_gid = trim($deny_gid);
4231 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4235 if ($sql_extra != "") {
4236 $nothingtodo = false;
4238 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4240 DateTimeFormat::utcNow(), // update edited timestamp
4246 $nothingtodo = true;
4249 if (x($_FILES, 'media')) {
4250 $nothingtodo = false;
4251 $media = $_FILES['media'];
4252 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4253 if (!is_null($data)) {
4254 return api_format_data("photo_update", $type, $data);
4258 // return success of updating or error message
4260 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4261 return api_format_data("photo_update", $type, ['$result' => $answer]);
4264 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4265 return api_format_data("photo_update", $type, ['$result' => $answer]);
4267 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4270 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4275 * @brief delete a single photo from the database through api
4277 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4280 function api_fr_photo_delete($type)
4282 if (api_user() === false) {
4283 throw new ForbiddenException();
4286 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4288 // do several checks on input parameters
4289 // we do not allow calls without photo id
4290 if ($photo_id == null) {
4291 throw new BadRequestException("no photo_id specified");
4293 // check if photo is existing in database
4295 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4299 if (!DBM::is_result($r)) {
4300 throw new BadRequestException("photo not available");
4302 // now we can perform on the deletion of the photo
4303 $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4305 // return success of deletion or error message
4307 // retrieve the id of the parent element (the photo element)
4309 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4310 intval(local_user()),
4314 if (!DBM::is_result($photo_item)) {
4315 throw new InternalServerErrorException("problem with deleting items occured");
4317 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4318 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4319 Item::deleteById($photo_item[0]['id']);
4321 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4322 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4324 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4330 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4332 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4333 * @return string|array
4335 function api_fr_photo_detail($type)
4337 if (api_user() === false) {
4338 throw new ForbiddenException();
4340 if (!x($_REQUEST, 'photo_id')) {
4341 throw new BadRequestException("No photo id.");
4344 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4345 $photo_id = $_REQUEST['photo_id'];
4347 // prepare json/xml output with data from database for the requested photo
4348 $data = prepare_photo_data($type, $scale, $photo_id);
4350 return api_format_data("photo_detail", $type, $data);
4355 * Updates the user’s profile image.
4357 * @brief updates the profile image for the user (either a specified profile or the default profile)
4359 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4362 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4364 function api_account_update_profile_image($type)
4366 if (api_user() === false) {
4367 throw new ForbiddenException();
4370 $profileid = defaults($_REQUEST, 'profile_id', 0);
4372 // error if image data is missing
4373 if (!x($_FILES, 'image')) {
4374 throw new BadRequestException("no media data submitted");
4377 // check if specified profile id is valid
4378 if ($profileid != 0) {
4380 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4384 // error message if specified profile id is not in database
4385 if (!DBM::is_result($r)) {
4386 throw new BadRequestException("profile_id not available");
4388 $is_default_profile = $r['profile'];
4390 $is_default_profile = 1;
4393 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4395 if (x($_FILES, 'image')) {
4396 $media = $_FILES['image'];
4397 } elseif (x($_FILES, 'media')) {
4398 $media = $_FILES['media'];
4400 // save new profile image
4401 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4404 if (is_array($media['type'])) {
4405 $filetype = $media['type'][0];
4407 $filetype = $media['type'];
4409 if ($filetype == "image/jpeg") {
4411 } elseif ($filetype == "image/png") {
4414 // change specified profile or all profiles to the new resource-id
4415 if ($is_default_profile) {
4417 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4418 dbesc($data['photo']['id']),
4419 intval(local_user())
4423 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
4424 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4425 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4426 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4427 intval(local_user())
4431 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4432 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4433 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4434 intval($_REQUEST['profile']),
4435 intval(local_user())
4439 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4440 // so that browsers will do a cache update unconditionally
4443 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4444 dbesc(DateTimeFormat::utcNow()),
4445 intval(local_user())
4448 // Update global directory in background
4449 //$user = api_get_user(get_app());
4450 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4451 if ($url && strlen(Config::get('system', 'directory'))) {
4452 Worker::add(PRIORITY_LOW, "Directory", $url);
4455 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4457 // output for client
4459 return api_account_verify_credentials($type);
4461 // SaveMediaToDatabase failed for some reason
4462 throw new InternalServerErrorException("image upload failed");
4466 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4467 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4468 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4469 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4470 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4471 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4472 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4473 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4474 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4477 * Update user profile
4479 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4481 * @return array|string
4483 function api_account_update_profile($type)
4485 $local_user = api_user();
4486 $api_user = api_get_user(get_app());
4488 if (!empty($_POST['name'])) {
4489 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4490 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4491 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4492 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4495 if (isset($_POST['description'])) {
4496 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4497 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4498 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4501 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4502 // Update global directory in background
4503 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4504 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4507 return api_account_verify_credentials($type);
4510 /// @TODO move to top of file or somewhere better
4511 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4515 * @param string $acl_string
4517 function check_acl_input($acl_string)
4519 if ($acl_string == null || $acl_string == " ") {
4522 $contact_not_found = false;
4524 // split <x><y><z> into array of cid's
4525 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4527 // check for each cid if it is available on server
4528 $cid_array = $array[0];
4529 foreach ($cid_array as $cid) {
4530 $cid = str_replace("<", "", $cid);
4531 $cid = str_replace(">", "", $cid);
4533 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4537 $contact_not_found |= !DBM::is_result($contact);
4539 return $contact_not_found;
4544 * @param string $mediatype
4545 * @param array $media
4546 * @param string $type
4547 * @param string $album
4548 * @param string $allow_cid
4549 * @param string $deny_cid
4550 * @param string $allow_gid
4551 * @param string $deny_gid
4552 * @param string $desc
4553 * @param integer $profile
4554 * @param boolean $visibility
4555 * @param string $photo_id
4557 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)
4565 if (is_array($media)) {
4566 if (is_array($media['tmp_name'])) {
4567 $src = $media['tmp_name'][0];
4569 $src = $media['tmp_name'];
4571 if (is_array($media['name'])) {
4572 $filename = basename($media['name'][0]);
4574 $filename = basename($media['name']);
4576 if (is_array($media['size'])) {
4577 $filesize = intval($media['size'][0]);
4579 $filesize = intval($media['size']);
4581 if (is_array($media['type'])) {
4582 $filetype = $media['type'][0];
4584 $filetype = $media['type'];
4588 if ($filetype == "") {
4589 $filetype=Image::guessType($filename);
4591 $imagedata = getimagesize($src);
4593 $filetype = $imagedata['mime'];
4596 "File upload src: " . $src . " - filename: " . $filename .
4597 " - size: " . $filesize . " - type: " . $filetype,
4601 // check if there was a php upload error
4602 if ($filesize == 0 && $media['error'] == 1) {
4603 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4605 // check against max upload size within Friendica instance
4606 $maximagesize = Config::get('system', 'maximagesize');
4607 if ($maximagesize && ($filesize > $maximagesize)) {
4608 $formattedBytes = formatBytes($maximagesize);
4609 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4612 // create Photo instance with the data of the image
4613 $imagedata = @file_get_contents($src);
4614 $Image = new Image($imagedata, $filetype);
4615 if (! $Image->isValid()) {
4616 throw new InternalServerErrorException("unable to process image data");
4619 // check orientation of image
4620 $Image->orient($src);
4623 // check max length of images on server
4624 $max_length = Config::get('system', 'max_image_length');
4625 if (! $max_length) {
4626 $max_length = MAX_IMAGE_LENGTH;
4628 if ($max_length > 0) {
4629 $Image->scaleDown($max_length);
4630 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4632 $width = $Image->getWidth();
4633 $height = $Image->getHeight();
4635 // create a new resource-id if not already provided
4636 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4638 if ($mediatype == "photo") {
4639 // upload normal image (scales 0, 1, 2)
4640 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4642 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4644 logger("photo upload: image upload with scale 0 (original size) failed");
4646 if ($width > 640 || $height > 640) {
4647 $Image->scaleDown(640);
4648 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4650 logger("photo upload: image upload with scale 1 (640x640) failed");
4654 if ($width > 320 || $height > 320) {
4655 $Image->scaleDown(320);
4656 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4658 logger("photo upload: image upload with scale 2 (320x320) failed");
4661 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4662 } elseif ($mediatype == "profileimage") {
4663 // upload profile image (scales 4, 5, 6)
4664 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4666 if ($width > 175 || $height > 175) {
4667 $Image->scaleDown(175);
4668 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4670 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4674 if ($width > 80 || $height > 80) {
4675 $Image->scaleDown(80);
4676 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4678 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4682 if ($width > 48 || $height > 48) {
4683 $Image->scaleDown(48);
4684 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4686 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4689 $Image->__destruct();
4690 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4694 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4695 if ($photo_id == null && $mediatype == "photo") {
4696 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4698 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4699 return prepare_photo_data($type, false, $hash);
4701 throw new InternalServerErrorException("image upload failed");
4707 * @param string $hash
4708 * @param string $allow_cid
4709 * @param string $deny_cid
4710 * @param string $allow_gid
4711 * @param string $deny_gid
4712 * @param string $filetype
4713 * @param boolean $visibility
4715 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4717 // get data about the api authenticated user
4718 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4719 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4722 $arr['guid'] = get_guid(32);
4723 $arr['uid'] = intval(api_user());
4725 $arr['parent-uri'] = $uri;
4726 $arr['type'] = 'photo';
4728 $arr['resource-id'] = $hash;
4729 $arr['contact-id'] = $owner_record[0]['id'];
4730 $arr['owner-name'] = $owner_record[0]['name'];
4731 $arr['owner-link'] = $owner_record[0]['url'];
4732 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4733 $arr['author-name'] = $owner_record[0]['name'];
4734 $arr['author-link'] = $owner_record[0]['url'];
4735 $arr['author-avatar'] = $owner_record[0]['thumb'];
4737 $arr['allow_cid'] = $allow_cid;
4738 $arr['allow_gid'] = $allow_gid;
4739 $arr['deny_cid'] = $deny_cid;
4740 $arr['deny_gid'] = $deny_gid;
4741 $arr['visible'] = $visibility;
4745 'image/jpeg' => 'jpg',
4746 'image/png' => 'png',
4747 'image/gif' => 'gif'
4750 // adds link to the thumbnail scale photo
4751 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4752 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4755 // do the magic for storing the item in the database and trigger the federation to other contacts
4761 * @param string $type
4763 * @param string $photo_id
4767 function prepare_photo_data($type, $scale, $photo_id)
4769 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4770 $data_sql = ($scale === false ? "" : "data, ");
4772 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4773 // clients needs to convert this in their way for further processing
4775 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4776 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4777 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4778 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4780 intval(local_user()),
4786 'image/jpeg' => 'jpg',
4787 'image/png' => 'png',
4788 'image/gif' => 'gif'
4791 // prepare output data for photo
4792 if (DBM::is_result($r)) {
4793 $data = ['photo' => $r[0]];
4794 $data['photo']['id'] = $data['photo']['resource-id'];
4795 if ($scale !== false) {
4796 $data['photo']['data'] = base64_encode($data['photo']['data']);
4798 unset($data['photo']['datasize']); //needed only with scale param
4800 if ($type == "xml") {
4801 $data['photo']['links'] = [];
4802 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4803 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4805 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4808 $data['photo']['link'] = [];
4809 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4811 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4812 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4816 unset($data['photo']['resource-id']);
4817 unset($data['photo']['minscale']);
4818 unset($data['photo']['maxscale']);
4820 throw new NotFoundException();
4823 // retrieve item element for getting activities (like, dislike etc.) related to photo
4825 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4826 intval(local_user()),
4829 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4831 // retrieve comments on photo
4833 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4834 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4835 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4836 `contact`.`id` AS `cid`
4838 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4839 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4840 WHERE `item`.`parent` = %d AND `item`.`visible`
4841 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4842 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4843 intval($item[0]['parent']),
4845 dbesc(ACTIVITY_POST)
4848 // prepare output of comments
4849 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4851 if ($type == "xml") {
4853 foreach ($commentData as $comment) {
4854 $comments[$k++ . ":comment"] = $comment;
4857 foreach ($commentData as $comment) {
4858 $comments[] = $comment;
4861 $data['photo']['friendica_comments'] = $comments;
4863 // include info if rights on photo and rights on item are mismatching
4864 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4865 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4866 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4867 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4868 $data['photo']['rights_mismatch'] = $rights_mismatch;
4875 * Similar as /mod/redir.php
4876 * redirect to 'url' after dfrn auth
4878 * Why this when there is mod/redir.php already?
4879 * This use api_user() and api_login()
4882 * c_url: url of remote contact to auth to
4883 * url: string, url to redirect after auth
4885 function api_friendica_remoteauth()
4887 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4888 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4890 if ($url === '' || $c_url === '') {
4891 throw new BadRequestException("Wrong parameters.");
4894 $c_url = normalise_link($c_url);
4898 $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4900 if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
4901 throw new BadRequestException("Unknown contact");
4904 $cid = $contact['id'];
4906 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4908 if ($contact['duplex'] && $contact['issued-id']) {
4909 $orig_id = $contact['issued-id'];
4910 $dfrn_id = '1:' . $orig_id;
4912 if ($contact['duplex'] && $contact['dfrn-id']) {
4913 $orig_id = $contact['dfrn-id'];
4914 $dfrn_id = '0:' . $orig_id;
4917 $sec = random_string();
4920 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4921 VALUES( %d, %s, '%s', '%s', %d )",
4929 logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
4930 $dest = ($url ? '&destination_url=' . $url : '');
4932 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4933 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4934 . '&type=profile&sec=' . $sec . $dest
4937 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4940 * @brief Return the item shared, if the item contains only the [share] tag
4942 * @param array $item Sharer item
4943 * @return array|false Shared item or false if not a reshare
4945 function api_share_as_retweet(&$item)
4947 $body = trim($item["body"]);
4949 if (Diaspora::isReshare($body, false)===false) {
4953 /// @TODO "$1" should maybe mean '$1' ?
4954 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4956 * Skip if there is no shared message in there
4957 * we already checked this in diaspora::isReshare()
4958 * but better one more than one less...
4960 if ($body == $attributes) {
4965 // build the fake reshared item
4966 $reshared_item = $item;
4969 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4970 if ($matches[1] != "") {
4971 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4974 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4975 if ($matches[1] != "") {
4976 $author = $matches[1];
4980 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4981 if ($matches[1] != "") {
4982 $profile = $matches[1];
4985 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4986 if ($matches[1] != "") {
4987 $profile = $matches[1];
4991 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4992 if ($matches[1] != "") {
4993 $avatar = $matches[1];
4996 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4997 if ($matches[1] != "") {
4998 $avatar = $matches[1];
5002 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5003 if ($matches[1] != "") {
5004 $link = $matches[1];
5007 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5008 if ($matches[1] != "") {
5009 $link = $matches[1];
5013 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5014 if ($matches[1] != "") {
5015 $posted = $matches[1];
5018 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5019 if ($matches[1] != "") {
5020 $posted = $matches[1];
5023 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5025 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5029 $reshared_item["body"] = $shared_body;
5030 $reshared_item["author-name"] = $author;
5031 $reshared_item["author-link"] = $profile;
5032 $reshared_item["author-avatar"] = $avatar;
5033 $reshared_item["plink"] = $link;
5034 $reshared_item["created"] = $posted;
5035 $reshared_item["edited"] = $posted;
5037 return $reshared_item;
5042 * @param string $profile
5044 * @return string|false
5045 * @todo remove trailing junk from profile url
5046 * @todo pump.io check has to check the website
5048 function api_get_nick($profile)
5053 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5054 dbesc(normalise_link($profile))
5057 if (DBM::is_result($r)) {
5058 $nick = $r[0]["nick"];
5063 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5064 dbesc(normalise_link($profile))
5067 if (DBM::is_result($r)) {
5068 $nick = $r[0]["nick"];
5073 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5074 if ($friendica != $profile) {
5080 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5081 if ($diaspora != $profile) {
5087 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5088 if ($twitter != $profile) {
5095 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5096 if ($StatusnetHost != $profile) {
5097 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5098 if ($StatusnetUser != $profile) {
5099 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5100 $user = json_decode($UserData);
5102 $nick = $user->screen_name;
5108 // To-Do: look at the page if its really a pumpio site
5109 //if (!$nick == "") {
5110 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5111 // if ($pumpio != $profile)
5113 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5126 * @param array $item
5130 function api_in_reply_to($item)
5134 $in_reply_to['status_id'] = null;
5135 $in_reply_to['user_id'] = null;
5136 $in_reply_to['status_id_str'] = null;
5137 $in_reply_to['user_id_str'] = null;
5138 $in_reply_to['screen_name'] = null;
5140 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5142 "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
5143 intval($item['uid']),
5144 dbesc($item['thr-parent'])
5147 if (DBM::is_result($r)) {
5148 $in_reply_to['status_id'] = intval($r[0]['id']);
5150 $in_reply_to['status_id'] = intval($item['parent']);
5153 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5156 "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
5157 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
5158 WHERE `item`.`id` = %d LIMIT 1",
5159 intval($in_reply_to['status_id'])
5162 if (DBM::is_result($r)) {
5163 if ($r[0]['nick'] == "") {
5164 $r[0]['nick'] = api_get_nick($r[0]["url"]);
5167 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
5168 $in_reply_to['user_id'] = intval($r[0]['id']);
5169 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
5172 // There seems to be situation, where both fields are identical:
5173 // https://github.com/friendica/friendica/issues/1010
5174 // This is a bugfix for that.
5175 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5176 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
5177 $in_reply_to['status_id'] = null;
5178 $in_reply_to['user_id'] = null;
5179 $in_reply_to['status_id_str'] = null;
5180 $in_reply_to['user_id_str'] = null;
5181 $in_reply_to['screen_name'] = null;
5185 return $in_reply_to;
5190 * @param string $Text
5194 function api_clean_plain_items($Text)
5196 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5198 $Text = BBCode::cleanPictureLinks($Text);
5199 $URLSearchString = "^\[\]";
5201 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
5203 if ($include_entities == "true") {
5204 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
5207 // Simplify "attachment" element
5208 $Text = api_clean_attachments($Text);
5214 * @brief Removes most sharing information for API text export
5216 * @param string $body The original body
5218 * @return string Cleaned body
5220 function api_clean_attachments($body)
5222 $data = BBCode::getAttachmentData($body);
5229 if (isset($data["text"])) {
5230 $body = $data["text"];
5232 if (($body == "") && isset($data["title"])) {
5233 $body = $data["title"];
5235 if (isset($data["url"])) {
5236 $body .= "\n".$data["url"];
5238 $body .= $data["after"];
5245 * @param array $contacts
5249 function api_best_nickname(&$contacts)
5253 if (count($contacts) == 0) {
5257 foreach ($contacts as $contact) {
5258 if ($contact["network"] == "") {
5259 $contact["network"] = "dfrn";
5260 $best_contact = [$contact];
5264 if (sizeof($best_contact) == 0) {
5265 foreach ($contacts as $contact) {
5266 if ($contact["network"] == "dfrn") {
5267 $best_contact = [$contact];
5272 if (sizeof($best_contact) == 0) {
5273 foreach ($contacts as $contact) {
5274 if ($contact["network"] == "dspr") {
5275 $best_contact = [$contact];
5280 if (sizeof($best_contact) == 0) {
5281 foreach ($contacts as $contact) {
5282 if ($contact["network"] == "stat") {
5283 $best_contact = [$contact];
5288 if (sizeof($best_contact) == 0) {
5289 foreach ($contacts as $contact) {
5290 if ($contact["network"] == "pump") {
5291 $best_contact = [$contact];
5296 if (sizeof($best_contact) == 0) {
5297 foreach ($contacts as $contact) {
5298 if ($contact["network"] == "twit") {
5299 $best_contact = [$contact];
5304 if (sizeof($best_contact) == 1) {
5305 $contacts = $best_contact;
5307 $contacts = [$contacts[0]];
5312 * Return all or a specified group of the user with the containing contacts.
5314 * @param string $type Return type (atom, rss, xml, json)
5316 * @return array|string
5318 function api_friendica_group_show($type)
5322 if (api_user() === false) {
5323 throw new ForbiddenException();
5327 $user_info = api_get_user($a);
5328 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5329 $uid = $user_info['uid'];
5331 // get data of the specified group id or all groups if not specified
5334 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5338 // error message if specified gid is not in database
5339 if (!DBM::is_result($r)) {
5340 throw new BadRequestException("gid not available");
5344 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5349 // loop through all groups and retrieve all members for adding data in the user array
5350 foreach ($r as $rr) {
5351 $members = Contact::getByGroupId($rr['id']);
5354 if ($type == "xml") {
5355 $user_element = "users";
5357 foreach ($members as $member) {
5358 $user = api_get_user($a, $member['nurl']);
5359 $users[$k++.":user"] = $user;
5362 $user_element = "user";
5363 foreach ($members as $member) {
5364 $user = api_get_user($a, $member['nurl']);
5368 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5370 return api_format_data("groups", $type, ['group' => $grps]);
5372 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5376 * Delete the specified group of the user.
5378 * @param string $type Return type (atom, rss, xml, json)
5380 * @return array|string
5382 function api_friendica_group_delete($type)
5386 if (api_user() === false) {
5387 throw new ForbiddenException();
5391 $user_info = api_get_user($a);
5392 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5393 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5394 $uid = $user_info['uid'];
5396 // error if no gid specified
5397 if ($gid == 0 || $name == "") {
5398 throw new BadRequestException('gid or name not specified');
5401 // get data of the specified group id
5403 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5407 // error message if specified gid is not in database
5408 if (!DBM::is_result($r)) {
5409 throw new BadRequestException('gid not available');
5412 // get data of the specified group id and group name
5414 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5419 // error message if specified gid is not in database
5420 if (!DBM::is_result($rname)) {
5421 throw new BadRequestException('wrong group name');
5425 $ret = Group::removeByName($uid, $name);
5428 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5429 return api_format_data("group_delete", $type, ['result' => $success]);
5431 throw new BadRequestException('other API error');
5434 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5438 * Create the specified group with the posted array of contacts.
5440 * @param string $type Return type (atom, rss, xml, json)
5442 * @return array|string
5444 function api_friendica_group_create($type)
5448 if (api_user() === false) {
5449 throw new ForbiddenException();
5453 $user_info = api_get_user($a);
5454 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5455 $uid = $user_info['uid'];
5456 $json = json_decode($_POST['json'], true);
5457 $users = $json['user'];
5459 // error if no name specified
5461 throw new BadRequestException('group name not specified');
5464 // get data of the specified group name
5466 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5470 // error message if specified group name already exists
5471 if (DBM::is_result($rname)) {
5472 throw new BadRequestException('group name already exists');
5475 // check if specified group name is a deleted group
5477 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5481 // error message if specified group name already exists
5482 if (DBM::is_result($rname)) {
5483 $reactivate_group = true;
5487 $ret = Group::create($uid, $name);
5489 $gid = Group::getIdByName($uid, $name);
5491 throw new BadRequestException('other API error');
5495 $erroraddinguser = false;
5497 foreach ($users as $user) {
5498 $cid = $user['cid'];
5499 // check if user really exists as contact
5501 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5505 if (count($contact)) {
5506 Group::addMember($gid, $cid);
5508 $erroraddinguser = true;
5509 $errorusers[] = $cid;
5513 // return success message incl. missing users in array
5514 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
5515 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5516 return api_format_data("group_create", $type, ['result' => $success]);
5518 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5522 * Update the specified group with the posted array of contacts.
5524 * @param string $type Return type (atom, rss, xml, json)
5526 * @return array|string
5528 function api_friendica_group_update($type)
5532 if (api_user() === false) {
5533 throw new ForbiddenException();
5537 $user_info = api_get_user($a);
5538 $uid = $user_info['uid'];
5539 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5540 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5541 $json = json_decode($_POST['json'], true);
5542 $users = $json['user'];
5544 // error if no name specified
5546 throw new BadRequestException('group name not specified');
5549 // error if no gid specified
5551 throw new BadRequestException('gid not specified');
5555 $members = Contact::getByGroupId($gid);
5556 foreach ($members as $member) {
5557 $cid = $member['id'];
5558 foreach ($users as $user) {
5559 $found = ($user['cid'] == $cid ? true : false);
5562 Group::removeMemberByName($uid, $name, $cid);
5567 $erroraddinguser = false;
5569 foreach ($users as $user) {
5570 $cid = $user['cid'];
5571 // check if user really exists as contact
5573 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5578 if (count($contact)) {
5579 Group::addMember($gid, $cid);
5581 $erroraddinguser = true;
5582 $errorusers[] = $cid;
5586 // return success message incl. missing users in array
5587 $status = ($erroraddinguser ? "missing user" : "ok");
5588 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5589 return api_format_data("group_update", $type, ['result' => $success]);
5592 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5596 * @param string $type Return type (atom, rss, xml, json)
5598 * @return array|string
5600 function api_friendica_activity($type)
5604 if (api_user() === false) {
5605 throw new ForbiddenException();
5607 $verb = strtolower($a->argv[3]);
5608 $verb = preg_replace("|\..*$|", "", $verb);
5610 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5612 $res = Item::performLike($id, $verb);
5615 if ($type == "xml") {
5620 return api_format_data('ok', $type, ['ok' => $ok]);
5622 throw new BadRequestException('Error adding activity');
5626 /// @TODO move to top of file or somewhere better
5627 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5628 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5629 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5630 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5631 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5632 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5633 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5634 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5635 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5636 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5639 * @brief Returns notifications
5641 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5644 function api_friendica_notification($type)
5648 if (api_user() === false) {
5649 throw new ForbiddenException();
5652 throw new BadRequestException("Invalid argument count");
5654 $nm = new NotificationsManager();
5656 $notes = $nm->getAll([], "+seen -date", 50);
5658 if ($type == "xml") {
5660 foreach ($notes as $note) {
5661 $xmlnotes[] = ["@attributes" => $note];
5667 return api_format_data("notes", $type, ['note' => $notes]);
5671 * POST request with 'id' param as notification id
5673 * @brief Set notification as seen and returns associated item (if possible)
5675 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5678 function api_friendica_notification_seen($type)
5682 if (api_user() === false) {
5683 throw new ForbiddenException();
5686 throw new BadRequestException("Invalid argument count");
5689 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5691 $nm = new NotificationsManager();
5692 $note = $nm->getByID($id);
5693 if (is_null($note)) {
5694 throw new BadRequestException("Invalid argument");
5697 $nm->setSeen($note);
5698 if ($note['otype']=='item') {
5699 // would be really better with an ItemsManager and $im->getByID() :-P
5701 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5702 intval($note['iid']),
5703 intval(local_user())
5706 // we found the item, return it to the user
5707 $user_info = api_get_user($a);
5708 $ret = api_format_items($r, $user_info, false, $type);
5709 $data = ['status' => $ret];
5710 return api_format_data("status", $type, $data);
5712 // the item can't be found, but we set the note as seen, so we count this as a success
5714 return api_format_data('result', $type, ['result' => "success"]);
5717 /// @TODO move to top of file or somewhere better
5718 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5719 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5722 * @brief update a direct_message to seen state
5724 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5725 * @return string (success result=ok, error result=error with error message)
5727 function api_friendica_direct_messages_setseen($type)
5730 if (api_user() === false) {
5731 throw new ForbiddenException();
5735 $user_info = api_get_user($a);
5736 $uid = $user_info['uid'];
5737 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5739 // return error if id is zero
5741 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5742 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5745 // get data of the specified message id
5747 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5752 // error message if specified id is not in database
5753 if (!DBM::is_result($r)) {
5754 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5755 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5758 // update seen indicator
5760 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5767 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5768 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5770 $answer = ['result' => 'error', 'message' => 'unknown error'];
5771 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5775 /// @TODO move to top of file or somewhere better
5776 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5779 * @brief search for direct_messages containing a searchstring through api
5781 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5782 * @param string $box
5783 * @return string (success: success=true if found and search_result contains found messages,
5784 * success=false if nothing was found, search_result='nothing found',
5785 * error: result=error with error message)
5787 function api_friendica_direct_messages_search($type, $box = "")
5791 if (api_user() === false) {
5792 throw new ForbiddenException();
5796 $user_info = api_get_user($a);
5797 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5798 $uid = $user_info['uid'];
5800 // error if no searchstring specified
5801 if ($searchstring == "") {
5802 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5803 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5806 // get data for the specified searchstring
5808 "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",
5810 dbesc('%'.$searchstring.'%')
5813 $profile_url = $user_info["url"];
5815 // message if nothing was found
5816 if (!DBM::is_result($r)) {
5817 $success = ['success' => false, 'search_results' => 'problem with query'];
5818 } elseif (count($r) == 0) {
5819 $success = ['success' => false, 'search_results' => 'nothing found'];
5822 foreach ($r as $item) {
5823 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5824 $recipient = $user_info;
5825 $sender = api_get_user($a, normalise_link($item['contact-url']));
5826 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5827 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5828 $sender = $user_info;
5831 $ret[] = api_format_messages($item, $recipient, $sender);
5833 $success = ['success' => true, 'search_results' => $ret];
5836 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5839 /// @TODO move to top of file or somewhere better
5840 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5843 * @brief return data of all the profiles a user has to the client
5845 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5848 function api_friendica_profile_show($type)
5852 if (api_user() === false) {
5853 throw new ForbiddenException();
5857 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5859 // retrieve general information about profiles for user
5860 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5861 $directory = Config::get('system', 'directory');
5863 // get data of the specified profile id or all profiles of the user if not specified
5864 if ($profileid != 0) {
5866 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5871 // error message if specified gid is not in database
5872 if (!DBM::is_result($r)) {
5873 throw new BadRequestException("profile_id not available");
5877 "SELECT * FROM `profile` WHERE `uid` = %d",
5881 // loop through all returned profiles and retrieve data and users
5883 foreach ($r as $rr) {
5884 $profile = api_format_items_profiles($rr);
5886 // select all users from contact table, loop and prepare standard return for user data
5889 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5891 intval($rr['profile_id'])
5894 foreach ($r as $rr) {
5895 $user = api_get_user($a, $rr['nurl']);
5896 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5898 $profile['users'] = $users;
5900 // add prepared profile data to array for final return
5901 if ($type == "xml") {
5902 $profiles[$k++ . ":profile"] = $profile;
5904 $profiles[] = $profile;
5908 // return settings, authenticated user and profiles data
5909 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5911 $result = ['multi_profiles' => $multi_profiles ? true : false,
5912 'global_dir' => $directory,
5913 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5914 'profiles' => $profiles];
5915 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5917 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5920 * Returns a list of saved searches.
5922 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5924 * @param string $type Return format: json or xml
5926 * @return string|array
5928 function api_saved_searches_list($type)
5930 $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
5933 while ($term = $terms->fetch()) {
5935 'name' => $term['term'],
5936 'query' => $term['term'],
5937 'id_str' => $term['id'],
5938 'id' => intval($term['id'])
5944 return api_format_data("terms", $type, ['terms' => $result]);
5947 /// @TODO move to top of file or somewhere better
5948 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5951 @TODO Maybe open to implement?
5953 [pagename] => api/1.1/statuses/lookup.json
5954 [id] => 605138389168451584
5955 [include_cards] => true
5956 [cards_platform] => Android-12
5957 [include_entities] => true
5958 [include_my_retweet] => 1
5960 [include_reply_count] => true
5961 [include_descendent_reply_count] => true
5965 Not implemented by now:
5966 statuses/retweets_of_me
5971 account/update_location
5972 account/update_profile_background_image
5975 friendica/profile/update
5976 friendica/profile/create
5977 friendica/profile/delete
5979 Not implemented in status.net:
5980 statuses/retweeted_to_me
5981 statuses/retweeted_by_me
5982 direct_messages/destroy
5984 account/update_delivery_device
5985 notifications/follow