3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
9 use Friendica\Content\ContactSelector;
10 use Friendica\Content\Feature;
11 use Friendica\Content\Text\BBCode;
12 use Friendica\Core\Addon;
13 use Friendica\Core\System;
14 use Friendica\Core\Config;
15 use Friendica\Core\NotificationsManager;
16 use Friendica\Core\L10n;
17 use Friendica\Core\PConfig;
18 use Friendica\Core\Worker;
19 use Friendica\Database\DBM;
20 use Friendica\Model\Contact;
21 use Friendica\Model\Group;
22 use Friendica\Model\Mail;
23 use Friendica\Model\Photo;
24 use Friendica\Model\User;
25 use Friendica\Model\Item;
26 use Friendica\Network\FKOAuth1;
27 use Friendica\Network\HTTPException;
28 use Friendica\Network\HTTPException\BadRequestException;
29 use Friendica\Network\HTTPException\ForbiddenException;
30 use Friendica\Network\HTTPException\InternalServerErrorException;
31 use Friendica\Network\HTTPException\MethodNotAllowedException;
32 use Friendica\Network\HTTPException\NotFoundException;
33 use Friendica\Network\HTTPException\NotImplementedException;
34 use Friendica\Network\HTTPException\UnauthorizedException;
35 use Friendica\Network\HTTPException\TooManyRequestsException;
36 use Friendica\Object\Image;
37 use Friendica\Protocol\Diaspora;
38 use Friendica\Util\Network;
39 use Friendica\Util\XML;
41 require_once 'include/bbcode.php';
42 require_once 'include/datetime.php';
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';
51 require_once 'include/like.php';
53 define('API_METHOD_ANY', '*');
54 define('API_METHOD_GET', 'GET');
55 define('API_METHOD_POST', 'POST,PUT');
56 define('API_METHOD_DELETE', 'POST,DELETE');
62 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
63 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
64 * into a page, and visitors will post something without noticing it).
66 * @brief Auth API user
70 if (x($_SESSION, 'allow_api')) {
78 * Clients can send 'source' parameter to be show in post metadata
79 * as "sent via <source>".
80 * Some clients doesn't send a source param, we support ones we know
83 * @brief Get source name from API client
86 * Client source name, default to "api" if unset/unknown
90 if (requestdata('source')) {
91 return requestdata('source');
94 // Support for known clients that doesn't send a source name
95 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
99 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
105 * @brief Format date for API
107 * @param string $str Source date, as UTC
108 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
110 function api_date($str)
112 // Wed May 23 06:01:13 +0000 2007
113 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y");
117 * Register a function to be the endpoint for defined API path.
119 * @brief Register API endpoint
121 * @param string $path API URL path, relative to System::baseUrl()
122 * @param string $func Function name to call on path request
123 * @param bool $auth API need logged user
124 * @param string $method HTTP method reqiured to call this endpoint.
125 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
126 * Default to API_METHOD_ANY
128 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
138 // Workaround for hotot
139 $path = str_replace("api/", "api/1.1/", $path);
149 * Log in user via OAuth1 or Simple HTTP Auth.
150 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
152 * @brief Login API user
154 * @param object $a App
155 * @hook 'authenticate'
157 * 'username' => username from login form
158 * 'password' => password from login form
159 * 'authenticated' => return status,
160 * 'user_record' => return authenticated user record
162 * array $user logged user record
164 function api_login(App $a)
166 $oauth1 = new FKOAuth1();
169 list($consumer, $token) = $oauth1->verify_request(OAuthRequest::from_request());
170 if (!is_null($token)) {
171 $oauth1->loginUser($token->uid);
172 Addon::callHooks('logged_in', $a->user);
175 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
176 var_dump($consumer, $token);
178 } catch (Exception $e) {
182 // workaround for HTTP-auth in CGI mode
183 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
184 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
185 if (strlen($userpass)) {
186 list($name, $password) = explode(':', $userpass);
187 $_SERVER['PHP_AUTH_USER'] = $name;
188 $_SERVER['PHP_AUTH_PW'] = $password;
192 if (!x($_SERVER, 'PHP_AUTH_USER')) {
193 logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
194 header('WWW-Authenticate: Basic realm="Friendica"');
195 throw new UnauthorizedException("This API requires login");
198 $user = $_SERVER['PHP_AUTH_USER'];
199 $password = $_SERVER['PHP_AUTH_PW'];
201 // allow "user@server" login (but ignore 'server' part)
202 $at = strstr($user, "@", true);
207 // next code from mod/auth.php. needs better solution
211 'username' => trim($user),
212 'password' => trim($password),
213 'authenticated' => 0,
214 'user_record' => null,
218 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
219 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
220 * and later addons should not interfere with an earlier one that succeeded.
222 Addon::callHooks('authenticate', $addon_auth);
224 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
225 $record = $addon_auth['user_record'];
227 $user_id = User::authenticate(trim($user), trim($password));
229 $record = dba::selectFirst('user', [], ['uid' => $user_id]);
233 if (!DBM::is_result($record)) {
234 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
235 header('WWW-Authenticate: Basic realm="Friendica"');
236 //header('HTTP/1.0 401 Unauthorized');
237 //die('This api requires login');
238 throw new UnauthorizedException("This API requires login");
241 authenticate_success($record);
243 $_SESSION["allow_api"] = true;
245 Addon::callHooks('logged_in', $a->user);
249 * API endpoints can define which HTTP method to accept when called.
250 * This function check the current HTTP method agains endpoint
253 * @brief Check HTTP method of called API
255 * @param string $method Required methods, uppercase, separated by comma
258 function api_check_method($method)
260 if ($method == "*") {
263 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
267 * Authenticate user, call registered API function, set HTTP headers
269 * @brief Main API entry point
271 * @param object $a App
272 * @return string API call result
274 function api_call(App $a)
276 global $API, $called_api;
279 if (strpos($a->query_string, ".xml") > 0) {
282 if (strpos($a->query_string, ".json") > 0) {
285 if (strpos($a->query_string, ".rss") > 0) {
288 if (strpos($a->query_string, ".atom") > 0) {
293 foreach ($API as $p => $info) {
294 if (strpos($a->query_string, $p) === 0) {
295 if (!api_check_method($info['method'])) {
296 throw new MethodNotAllowedException();
299 $called_api = explode("/", $p);
300 //unset($_SERVER['PHP_AUTH_USER']);
302 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
303 if ($info['auth'] === true && api_user() === false) {
307 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
308 logger('API parameters: ' . print_r($_REQUEST, true));
310 $stamp = microtime(true);
311 $return = call_user_func($info['func'], $type);
312 $duration = (float) (microtime(true) - $stamp);
313 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
315 if (Config::get("system", "profiler")) {
316 $duration = microtime(true)-$a->performance["start"];
318 /// @TODO round() really everywhere?
320 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
321 "Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
322 round($a->performance["database"] - $a->performance["database_write"], 3),
323 round($a->performance["database_write"], 3),
324 round($a->performance["network"], 2),
325 round($a->performance["file"], 2),
326 round($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
332 if (Config::get("rendertime", "callstack")) {
333 $o = "Database Read:\n";
334 foreach ($a->callstack["database"] as $func => $time) {
335 $time = round($time, 3);
337 $o .= $func . ": " . $time . "\n";
340 $o .= "\nDatabase Write:\n";
341 foreach ($a->callstack["database_write"] as $func => $time) {
342 $time = round($time, 3);
344 $o .= $func . ": " . $time . "\n";
348 $o .= "\nNetwork:\n";
349 foreach ($a->callstack["network"] as $func => $time) {
350 $time = round($time, 3);
352 $o .= $func . ": " . $time . "\n";
355 logger($o, LOGGER_DEBUG);
359 if (false === $return) {
361 * api function returned false withour throw an
362 * exception. This should not happend, throw a 500
364 throw new InternalServerErrorException();
369 header("Content-Type: text/xml");
372 header("Content-Type: application/json");
373 foreach ($return as $rr) {
374 $json = json_encode($rr);
376 if (x($_GET, 'callback')) {
377 $json = $_GET['callback'] . "(" . $json . ")";
382 header("Content-Type: application/rss+xml");
383 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
386 header("Content-Type: application/atom+xml");
387 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
394 logger('API call not implemented: ' . $a->query_string);
395 throw new NotImplementedException();
396 } catch (HTTPException $e) {
397 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
398 return api_error($type, $e);
403 * @brief Format API error string
405 * @param string $type Return type (xml, json, rss, as)
406 * @param object $e HTTPException Error object
407 * @return string error message formatted as $type
409 function api_error($type, $e)
413 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
414 /// @TODO: https://dev.twitter.com/overview/api/response-codes
416 $error = ["error" => $error,
417 "code" => $e->httpcode . " " . $e->httpdesc,
418 "request" => $a->query_string];
420 $return = api_format_data('status', $type, ['status' => $error]);
424 header("Content-Type: text/xml");
427 header("Content-Type: application/json");
428 $return = json_encode($return);
431 header("Content-Type: application/rss+xml");
434 header("Content-Type: application/atom+xml");
442 * @brief Set values for RSS template
445 * @param array $arr Array to be passed to template
446 * @param array $user_info User info
448 * @todo find proper type-hints
450 function api_rss_extra(App $a, $arr, $user_info)
452 if (is_null($user_info)) {
453 $user_info = api_get_user($a);
456 $arr['$user'] = $user_info;
458 'alternate' => $user_info['url'],
459 'self' => System::baseUrl() . "/" . $a->query_string,
460 'base' => System::baseUrl(),
461 'updated' => api_date(null),
462 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
463 'language' => $user_info['language'],
464 'logo' => System::baseUrl() . "/images/friendica-32.png",
472 * @brief Unique contact to contact url.
474 * @param int $id Contact id
475 * @return bool|string
476 * Contact url or False if contact id is unknown
478 function api_unique_id_to_nurl($id)
480 $r = dba::selectFirst('contact', ['nurl'], ['uid' => 0, 'id' => $id]);
482 if (DBM::is_result($r)) {
490 * @brief Get user info array.
492 * @param object $a App
493 * @param int|string $contact_id Contact ID or URL
495 function api_get_user(App $a, $contact_id = null)
503 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
505 // Searching for contact URL
506 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
507 $user = dbesc(normalise_link($contact_id));
509 $extra_query = "AND `contact`.`nurl` = '%s' ";
510 if (api_user() !== false) {
511 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
515 // Searching for contact id with uid = 0
516 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
517 $user = dbesc(api_unique_id_to_nurl($contact_id));
520 throw new BadRequestException("User not found.");
524 $extra_query = "AND `contact`.`nurl` = '%s' ";
525 if (api_user() !== false) {
526 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
530 if (is_null($user) && x($_GET, 'user_id')) {
531 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
534 throw new BadRequestException("User not found.");
538 $extra_query = "AND `contact`.`nurl` = '%s' ";
539 if (api_user() !== false) {
540 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
543 if (is_null($user) && x($_GET, 'screen_name')) {
544 $user = dbesc($_GET['screen_name']);
545 $extra_query = "AND `contact`.`nick` = '%s' ";
546 if (api_user() !== false) {
547 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
551 if (is_null($user) && x($_GET, 'profileurl')) {
552 $user = dbesc(normalise_link($_GET['profileurl']));
553 $extra_query = "AND `contact`.`nurl` = '%s' ";
554 if (api_user() !== false) {
555 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
559 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
560 $argid = count($called_api);
561 list($user, $null) = explode(".", $a->argv[$argid]);
562 if (is_numeric($user)) {
563 $user = dbesc(api_unique_id_to_nurl($user));
570 $extra_query = "AND `contact`.`nurl` = '%s' ";
571 if (api_user() !== false) {
572 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
575 $user = dbesc($user);
576 $extra_query = "AND `contact`.`nick` = '%s' ";
577 if (api_user() !== false) {
578 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
583 logger("api_get_user: user ".$user, LOGGER_DEBUG);
586 if (api_user() === false) {
590 $user = $_SESSION['uid'];
591 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
595 logger('api_user: ' . $extra_query . ', user: ' . $user);
599 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
605 // Selecting the id by priority, friendica first
606 api_best_nickname($uinfo);
608 // if the contact wasn't found, fetch it from the contacts with uid = 0
609 if (!DBM::is_result($uinfo)) {
613 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
616 if (DBM::is_result($r)) {
617 $network_name = ContactSelector::networkToName($r[0]['network'], $r[0]['url']);
619 // If no nick where given, extract it from the address
620 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
621 $r[0]['nick'] = api_get_nick($r[0]["url"]);
626 'id_str' => (string) $r[0]["id"],
627 'name' => $r[0]["name"],
628 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
629 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
630 'description' => $r[0]["about"],
631 'profile_image_url' => $r[0]["micro"],
632 'profile_image_url_https' => $r[0]["micro"],
633 'url' => $r[0]["url"],
634 'protected' => false,
635 'followers_count' => 0,
636 'friends_count' => 0,
638 'created_at' => api_date($r[0]["created"]),
639 'favourites_count' => 0,
641 'time_zone' => 'UTC',
642 'geo_enabled' => false,
644 'statuses_count' => 0,
646 'contributors_enabled' => false,
647 'is_translator' => false,
648 'is_translation_enabled' => false,
649 'following' => false,
650 'follow_request_sent' => false,
651 'statusnet_blocking' => false,
652 'notifications' => false,
653 'statusnet_profile_url' => $r[0]["url"],
655 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
657 'network' => $r[0]["network"],
662 throw new BadRequestException("User not found.");
666 if ($uinfo[0]['self']) {
667 if ($uinfo[0]['network'] == "") {
668 $uinfo[0]['network'] = NETWORK_DFRN;
672 "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
676 "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
680 /// @TODO old-lost code? (twice)
681 // Counting is deactivated by now, due to performance issues
682 // count public wall messages
683 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
684 // intval($uinfo[0]['uid'])
686 //$countitms = $r[0]['count'];
689 // Counting is deactivated by now, due to performance issues
690 //$r = q("SELECT count(*) as `count` FROM `item`
691 // WHERE `contact-id` = %d",
692 // intval($uinfo[0]['id'])
694 //$countitms = $r[0]['count'];
698 /// @TODO old-lost code? (twice)
700 // Counting is deactivated by now, due to performance issues
702 $r = q("SELECT count(*) as `count` FROM `contact`
703 WHERE `uid` = %d AND `rel` IN ( %d, %d )
704 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
705 intval($uinfo[0]['uid']),
706 intval(CONTACT_IS_SHARING),
707 intval(CONTACT_IS_FRIEND)
709 $countfriends = $r[0]['count'];
711 $r = q("SELECT count(*) as `count` FROM `contact`
712 WHERE `uid` = %d AND `rel` IN ( %d, %d )
713 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
714 intval($uinfo[0]['uid']),
715 intval(CONTACT_IS_FOLLOWER),
716 intval(CONTACT_IS_FRIEND)
718 $countfollowers = $r[0]['count'];
720 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
721 intval($uinfo[0]['uid'])
723 $starred = $r[0]['count'];
726 if (! $uinfo[0]['self']) {
736 // Add a nick if it isn't present there
737 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
738 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
741 $network_name = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
743 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
745 if (!empty($profile[0]['about'])) {
746 $description = $profile[0]['about'];
748 $description = $uinfo[0]["about"];
751 if (!empty($usr[0]['default-location'])) {
752 $location = $usr[0]['default-location'];
753 } elseif (!empty($uinfo[0]["location"])) {
754 $location = $uinfo[0]["location"];
756 $location = $network_name;
760 'id' => intval($pcontact_id),
761 'id_str' => (string) intval($pcontact_id),
762 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
763 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
764 'location' => $location,
765 'description' => $description,
766 'profile_image_url' => $uinfo[0]['micro'],
767 'profile_image_url_https' => $uinfo[0]['micro'],
768 'url' => $uinfo[0]['url'],
769 'protected' => false,
770 'followers_count' => intval($countfollowers),
771 'friends_count' => intval($countfriends),
773 'created_at' => api_date($uinfo[0]['created']),
774 'favourites_count' => intval($starred),
776 'time_zone' => 'UTC',
777 'geo_enabled' => false,
779 'statuses_count' => intval($countitms),
781 'contributors_enabled' => false,
782 'is_translator' => false,
783 'is_translation_enabled' => false,
784 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
785 'follow_request_sent' => false,
786 'statusnet_blocking' => false,
787 'notifications' => false,
789 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
790 'statusnet_profile_url' => $uinfo[0]['url'],
791 'uid' => intval($uinfo[0]['uid']),
792 'cid' => intval($uinfo[0]['cid']),
793 'self' => $uinfo[0]['self'],
794 'network' => $uinfo[0]['network'],
797 // If this is a local user and it uses Frio, we can get its color preferences.
799 $theme_info = dba::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
800 if ($theme_info['theme'] === 'frio') {
801 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
802 if ($schema && ($schema != '---')) {
803 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
804 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
805 require_once $schemefile;
808 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
809 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
810 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
816 $link_color = "#6fdbe8";
819 $bgcolor = "#ededed";
822 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
823 $ret['profile_link_color'] = str_replace('#', '', $link_color);
824 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
832 * @brief return api-formatted array for item's author and owner
834 * @param object $a App
835 * @param array $item item from db
836 * @return array(array:author, array:owner)
838 function api_item_get_user(App $a, $item)
840 $status_user = api_get_user($a, $item["author-link"]);
842 $status_user["protected"] = (($item["allow_cid"] != "") ||
843 ($item["allow_gid"] != "") ||
844 ($item["deny_cid"] != "") ||
845 ($item["deny_gid"] != "") ||
848 if ($item['thr-parent'] == $item['uri']) {
849 $owner_user = api_get_user($a, $item["owner-link"]);
851 $owner_user = $status_user;
854 return ([$status_user, $owner_user]);
858 * @brief walks recursively through an array with the possibility to change value and key
860 * @param array $array The array to walk through
861 * @param string $callback The callback function
863 * @return array the transformed array
865 function api_walk_recursive(array &$array, callable $callback)
869 foreach ($array as $k => $v) {
871 if ($callback($v, $k)) {
872 $new_array[$k] = api_walk_recursive($v, $callback);
875 if ($callback($v, $k)) {
886 * @brief Callback function to transform the array in an array that can be transformed in a XML file
888 * @param mixed $item Array item value
889 * @param string $key Array key
891 * @return boolean Should the array item be deleted?
893 function api_reformat_xml(&$item, &$key)
895 if (is_bool($item)) {
896 $item = ($item ? "true" : "false");
899 if (substr($key, 0, 10) == "statusnet_") {
900 $key = "statusnet:".substr($key, 10);
901 } elseif (substr($key, 0, 10) == "friendica_") {
902 $key = "friendica:".substr($key, 10);
904 /// @TODO old-lost code?
906 // $key = "default:".$key;
912 * @brief Creates the XML from a JSON style array
914 * @param array $data JSON style array
915 * @param string $root_element Name of the root element
917 * @return string The XML data
919 function api_create_xml($data, $root_element)
921 $childname = key($data);
922 $data2 = array_pop($data);
925 $namespaces = ["" => "http://api.twitter.com",
926 "statusnet" => "http://status.net/schema/api/1/",
927 "friendica" => "http://friendi.ca/schema/api/1/",
928 "georss" => "http://www.georss.org/georss"];
930 /// @todo Auto detection of needed namespaces
931 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
935 if (is_array($data2)) {
936 api_walk_recursive($data2, "api_reformat_xml");
943 foreach ($data2 as $item) {
944 $data4[$i++.":".$childname] = $item;
950 $data3 = [$root_element => $data2];
952 $ret = XML::fromArray($data3, $xml, false, $namespaces);
957 * @brief Formats the data according to the data type
959 * @param string $root_element Name of the root element
960 * @param string $type Return type (atom, rss, xml, json)
961 * @param array $data JSON style array
963 * @return (string|object|array) XML data or JSON data
965 function api_format_data($root_element, $type, $data)
971 $ret = api_create_xml($data, $root_element);
986 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
987 * returns a 401 status code and an error message if not.
988 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
990 * @param string $type Return type (atom, rss, xml, json)
992 function api_account_verify_credentials($type)
997 if (api_user() === false) {
998 throw new ForbiddenException();
1001 unset($_REQUEST["user_id"]);
1002 unset($_GET["user_id"]);
1004 unset($_REQUEST["screen_name"]);
1005 unset($_GET["screen_name"]);
1007 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
1009 $user_info = api_get_user($a);
1011 // "verified" isn't used here in the standard
1012 unset($user_info["verified"]);
1014 // - Adding last status
1015 if (!$skip_status) {
1016 $user_info["status"] = api_status_show("raw");
1017 if (!count($user_info["status"])) {
1018 unset($user_info["status"]);
1020 unset($user_info["status"]["user"]);
1024 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1025 unset($user_info["uid"]);
1026 unset($user_info["self"]);
1028 return api_format_data("user", $type, ['user' => $user_info]);
1031 /// @TODO move to top of file or somewhere better
1032 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1035 * Get data from $_POST or $_GET
1039 function requestdata($k)
1041 if (x($_POST, $k)) {
1051 * Waitman Gobble Mod
1053 * @param string $type Return type (atom, rss, xml, json)
1055 * @return array|string
1057 function api_statuses_mediap($type)
1061 if (api_user() === false) {
1062 logger('api_statuses_update: no user');
1063 throw new ForbiddenException();
1065 $user_info = api_get_user($a);
1067 $_REQUEST['type'] = 'wall';
1068 $_REQUEST['profile_uid'] = api_user();
1069 $_REQUEST['api_source'] = true;
1070 $txt = requestdata('status');
1071 /// @TODO old-lost code?
1072 //$txt = urldecode(requestdata('status'));
1074 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1075 $txt = html2bb_video($txt);
1076 $config = HTMLPurifier_Config::createDefault();
1077 $config->set('Cache.DefinitionImpl', null);
1078 $purifier = new HTMLPurifier($config);
1079 $txt = $purifier->purify($txt);
1081 $txt = html2bbcode($txt);
1083 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1085 // tell wall_upload function to return img info instead of echo
1086 $_REQUEST['hush'] = 'yeah';
1087 $bebop = wall_upload_post($a);
1089 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1090 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1093 // this should output the last post (the one we just posted).
1094 return api_status_show($type);
1097 /// @TODO move this to top of file or somewhere better!
1098 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1101 * Updates the user’s current status.
1103 * @param string $type Return type (atom, rss, xml, json)
1105 * @return array|string
1106 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1108 function api_statuses_update($type)
1113 if (api_user() === false) {
1114 logger('api_statuses_update: no user');
1115 throw new ForbiddenException();
1120 // convert $_POST array items to the form we use for web posts.
1121 if (requestdata('htmlstatus')) {
1122 $txt = requestdata('htmlstatus');
1123 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1124 $txt = html2bb_video($txt);
1126 $config = HTMLPurifier_Config::createDefault();
1127 $config->set('Cache.DefinitionImpl', null);
1129 $purifier = new HTMLPurifier($config);
1130 $txt = $purifier->purify($txt);
1132 $_REQUEST['body'] = html2bbcode($txt);
1135 $_REQUEST['body'] = requestdata('status');
1138 $_REQUEST['title'] = requestdata('title');
1140 $parent = requestdata('in_reply_to_status_id');
1142 // Twidere sends "-1" if it is no reply ...
1143 if ($parent == -1) {
1147 if (ctype_digit($parent)) {
1148 $_REQUEST['parent'] = $parent;
1150 $_REQUEST['parent_uri'] = $parent;
1153 if (requestdata('lat') && requestdata('long')) {
1154 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1156 $_REQUEST['profile_uid'] = api_user();
1159 $_REQUEST['type'] = 'net-comment';
1161 // Check for throttling (maximum posts per day, week and month)
1162 $throttle_day = Config::get('system', 'throttle_limit_day');
1163 if ($throttle_day > 0) {
1164 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1167 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1168 AND `created` > '%s' AND `id` = `parent`",
1173 if (DBM::is_result($r)) {
1174 $posts_day = $r[0]["posts_day"];
1179 if ($posts_day > $throttle_day) {
1180 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1181 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1182 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));
1186 $throttle_week = Config::get('system', 'throttle_limit_week');
1187 if ($throttle_week > 0) {
1188 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1191 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1192 AND `created` > '%s' AND `id` = `parent`",
1197 if (DBM::is_result($r)) {
1198 $posts_week = $r[0]["posts_week"];
1203 if ($posts_week > $throttle_week) {
1204 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1205 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1206 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));
1210 $throttle_month = Config::get('system', 'throttle_limit_month');
1211 if ($throttle_month > 0) {
1212 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1215 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1216 AND `created` > '%s' AND `id` = `parent`",
1221 if (DBM::is_result($r)) {
1222 $posts_month = $r[0]["posts_month"];
1227 if ($posts_month > $throttle_month) {
1228 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1229 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1230 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));
1234 $_REQUEST['type'] = 'wall';
1237 if (x($_FILES, 'media')) {
1238 // upload the image if we have one
1239 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1240 $media = wall_upload_post($a);
1241 if (strlen($media) > 0) {
1242 $_REQUEST['body'] .= "\n\n" . $media;
1246 // To-Do: Multiple IDs
1247 if (requestdata('media_ids')) {
1249 "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",
1250 intval(requestdata('media_ids')),
1253 if (DBM::is_result($r)) {
1254 $phototypes = Image::supportedTypes();
1255 $ext = $phototypes[$r[0]['type']];
1256 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1257 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1261 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1263 $_REQUEST['api_source'] = true;
1265 if (!x($_REQUEST, "source")) {
1266 $_REQUEST["source"] = api_source();
1269 // call out normal post function
1272 // this should output the last post (the one we just posted).
1273 return api_status_show($type);
1276 /// @TODO move to top of file or somewhere better
1277 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1278 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1281 * Uploads an image to Friendica.
1284 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1286 function api_media_upload()
1290 if (api_user() === false) {
1292 throw new ForbiddenException();
1297 if (!x($_FILES, 'media')) {
1299 throw new BadRequestException("No media.");
1302 $media = wall_upload_post($a, false);
1305 throw new InternalServerErrorException();
1309 $returndata["media_id"] = $media["id"];
1310 $returndata["media_id_string"] = (string)$media["id"];
1311 $returndata["size"] = $media["size"];
1312 $returndata["image"] = ["w" => $media["width"],
1313 "h" => $media["height"],
1314 "image_type" => $media["type"]];
1316 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1318 return ["media" => $returndata];
1321 /// @TODO move to top of file or somewhere better
1322 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1326 * @param string $type Return type (atom, rss, xml, json)
1328 * @return array|string
1330 function api_status_show($type)
1334 $user_info = api_get_user($a);
1336 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1338 if ($type == "raw") {
1339 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1344 // get last public wall message
1348 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1349 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1350 AND `item`.`type` != 'activity' $privacy_sql
1351 ORDER BY `item`.`id` DESC
1353 intval($user_info['cid']),
1355 dbesc($user_info['url']),
1356 dbesc(normalise_link($user_info['url'])),
1357 dbesc($user_info['url']),
1358 dbesc(normalise_link($user_info['url']))
1361 if (DBM::is_result($lastwall)) {
1362 $lastwall = $lastwall[0];
1364 $in_reply_to = api_in_reply_to($lastwall);
1366 $converted = api_convert_item($lastwall);
1368 if ($type == "xml") {
1369 $geo = "georss:point";
1375 'created_at' => api_date($lastwall['created']),
1376 'id' => intval($lastwall['id']),
1377 'id_str' => (string) $lastwall['id'],
1378 'text' => $converted["text"],
1379 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1380 'truncated' => false,
1381 'in_reply_to_status_id' => $in_reply_to['status_id'],
1382 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1383 'in_reply_to_user_id' => $in_reply_to['user_id'],
1384 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1385 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1386 'user' => $user_info,
1388 'coordinates' => "",
1390 'contributors' => "",
1391 'is_quote_status' => false,
1392 'retweet_count' => 0,
1393 'favorite_count' => 0,
1394 'favorited' => $lastwall['starred'] ? true : false,
1395 'retweeted' => false,
1396 'possibly_sensitive' => false,
1398 'statusnet_html' => $converted["html"],
1399 'statusnet_conversation_id' => $lastwall['parent'],
1400 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1403 if (count($converted["attachments"]) > 0) {
1404 $status_info["attachments"] = $converted["attachments"];
1407 if (count($converted["entities"]) > 0) {
1408 $status_info["entities"] = $converted["entities"];
1411 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1412 $status_info["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1413 } elseif (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1414 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['item_network'], $user_info['url']).')');
1417 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1418 unset($status_info["user"]["uid"]);
1419 unset($status_info["user"]["self"]);
1422 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1424 if ($type == "raw") {
1425 return $status_info;
1428 return api_format_data("statuses", $type, ['status' => $status_info]);
1432 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1433 * The author's most recent status will be returned inline.
1435 * @param string $type Return type (atom, rss, xml, json)
1436 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1438 function api_users_show($type)
1442 $user_info = api_get_user($a);
1446 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1447 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1448 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1449 AND `type`!='activity'
1450 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1454 dbesc(ACTIVITY_POST),
1455 intval($user_info['cid']),
1456 dbesc($user_info['url']),
1457 dbesc(normalise_link($user_info['url'])),
1458 dbesc($user_info['url']),
1459 dbesc(normalise_link($user_info['url']))
1462 if (DBM::is_result($lastwall)) {
1463 $lastwall = $lastwall[0];
1465 $in_reply_to = api_in_reply_to($lastwall);
1467 $converted = api_convert_item($lastwall);
1469 if ($type == "xml") {
1470 $geo = "georss:point";
1475 $user_info['status'] = [
1476 'text' => $converted["text"],
1477 'truncated' => false,
1478 'created_at' => api_date($lastwall['created']),
1479 'in_reply_to_status_id' => $in_reply_to['status_id'],
1480 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1481 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1482 'id' => intval($lastwall['contact-id']),
1483 'id_str' => (string) $lastwall['contact-id'],
1484 'in_reply_to_user_id' => $in_reply_to['user_id'],
1485 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1486 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1488 'favorited' => $lastwall['starred'] ? true : false,
1489 'statusnet_html' => $converted["html"],
1490 'statusnet_conversation_id' => $lastwall['parent'],
1491 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1494 if (count($converted["attachments"]) > 0) {
1495 $user_info["status"]["attachments"] = $converted["attachments"];
1498 if (count($converted["entities"]) > 0) {
1499 $user_info["status"]["entities"] = $converted["entities"];
1502 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1503 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1506 if (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1507 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) . ')');
1511 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1512 unset($user_info["uid"]);
1513 unset($user_info["self"]);
1515 return api_format_data("user", $type, ['user' => $user_info]);
1518 /// @TODO move to top of file or somewhere better
1519 api_register_func('api/users/show', 'api_users_show');
1520 api_register_func('api/externalprofile/show', 'api_users_show');
1523 * Search a public user account.
1525 * @param string $type Return type (atom, rss, xml, json)
1527 * @return array|string
1528 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1530 function api_users_search($type)
1536 if (x($_GET, 'q')) {
1537 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1539 if (!DBM::is_result($r)) {
1540 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1543 if (DBM::is_result($r)) {
1545 foreach ($r as $user) {
1546 $user_info = api_get_user($a, $user["id"]);
1548 if ($type == "xml") {
1549 $userlist[$k++.":user"] = $user_info;
1551 $userlist[] = $user_info;
1554 $userlist = ["users" => $userlist];
1556 throw new BadRequestException("User not found.");
1559 throw new BadRequestException("User not found.");
1562 return api_format_data("users", $type, $userlist);
1565 /// @TODO move to top of file or somewhere better
1566 api_register_func('api/users/search', 'api_users_search');
1569 * Return user objects
1571 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1573 * @param string $type Return format: json or xml
1575 * @return array|string
1576 * @throws NotFoundException if the results are empty.
1578 function api_users_lookup($type)
1582 if (x($_REQUEST['user_id'])) {
1583 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1585 $users[] = api_get_user(get_app(), $id);
1590 if (empty($users)) {
1591 throw new NotFoundException;
1594 return api_format_data("users", $type, ['users' => $users]);
1597 /// @TODO move to top of file or somewhere better
1598 api_register_func('api/users/lookup', 'api_users_lookup', true);
1601 * Returns statuses that match a specified query.
1603 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1605 * @param string $type Return format: json, xml, atom, rss
1607 * @return array|string
1608 * @throws BadRequestException if the "q" parameter is missing.
1610 function api_search($type)
1614 if (!x($_REQUEST, 'q')) {
1615 throw new BadRequestException("q parameter is required.");
1618 if (x($_REQUEST, 'rpp')) {
1619 $count = $_REQUEST['rpp'];
1620 } elseif (x($_REQUEST, 'count')) {
1621 $count = $_REQUEST['count'];
1626 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1627 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1628 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1630 $start = $page * $count;
1633 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1637 "SELECT ".item_fieldlists()."
1638 FROM `item` ".item_joins()."
1639 WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1640 AND `item`.`body` LIKE CONCAT('%',?,'%')
1643 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
1649 $data['status'] = api_format_items(dba::inArray($r), api_get_user(get_app()));
1651 return api_format_data("statuses", $type, $data);
1654 /// @TODO move to top of file or somewhere better
1655 api_register_func('api/search/tweets', 'api_search', true);
1656 api_register_func('api/search', 'api_search', true);
1659 * Returns the most recent statuses posted by the user and the users they follow.
1661 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1663 * @param string $type Return type (atom, rss, xml, json)
1665 * @todo Optional parameters
1666 * @todo Add reply info
1668 function api_statuses_home_timeline($type)
1672 if (api_user() === false) {
1673 throw new ForbiddenException();
1676 unset($_REQUEST["user_id"]);
1677 unset($_GET["user_id"]);
1679 unset($_REQUEST["screen_name"]);
1680 unset($_GET["screen_name"]);
1682 $user_info = api_get_user($a);
1683 // get last newtork messages
1686 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1687 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1691 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1692 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1693 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1694 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1695 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1697 $start = $page * $count;
1701 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1703 if ($exclude_replies > 0) {
1704 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1706 if ($conversation_id > 0) {
1707 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1711 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1712 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1713 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1714 `contact`.`id` AS `cid`
1716 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1717 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1718 WHERE `item`.`uid` = %d AND `verb` = '%s'
1719 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1722 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1724 dbesc(ACTIVITY_POST),
1730 $ret = api_format_items($r, $user_info, false, $type);
1732 // Set all posts from the query above to seen
1734 foreach ($r as $item) {
1735 $idarray[] = intval($item["id"]);
1738 $idlist = implode(",", $idarray);
1740 if ($idlist != "") {
1741 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1744 q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1748 $data = ['status' => $ret];
1752 $data = api_rss_extra($a, $data, $user_info);
1756 return api_format_data("statuses", $type, $data);
1759 /// @TODO move to top of file or somewhere better
1760 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1761 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1764 * Returns the most recent statuses from public users.
1766 * @param string $type Return type (atom, rss, xml, json)
1768 * @return array|string
1770 function api_statuses_public_timeline($type)
1774 if (api_user() === false) {
1775 throw new ForbiddenException();
1778 $user_info = api_get_user($a);
1779 // get last newtork messages
1782 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1783 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1787 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1788 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1789 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1790 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1791 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1793 $start = $page * $count;
1795 if ($exclude_replies && !$conversation_id) {
1797 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1801 "SELECT " . item_fieldlists() . "
1803 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1804 " . item_joins() . "
1805 STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1806 AND NOT `user`.`hidewall`
1808 AND NOT `thread`.`private`
1810 AND `thread`.`visible`
1811 AND NOT `thread`.`deleted`
1812 AND NOT `thread`.`moderated`
1813 AND `thread`.`iid` > ?
1815 ORDER BY `thread`.`iid` DESC
1816 LIMIT " . intval($start) . ", " . intval($count),
1821 $r = dba::inArray($r);
1824 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1826 if ($conversation_id > 0) {
1827 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1831 "SELECT " . item_fieldlists() . "
1833 " . item_joins() . "
1834 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1835 AND NOT `user`.`hidewall`
1837 AND NOT `item`.`private`
1839 AND `item`.`visible`
1840 AND NOT `item`.`deleted`
1841 AND NOT `item`.`moderated`
1844 ORDER BY `item`.`id` DESC
1845 LIMIT " . intval($start) . ", " . intval($count),
1850 $r = dba::inArray($r);
1853 $ret = api_format_items($r, $user_info, false, $type);
1855 $data = ['status' => $ret];
1859 $data = api_rss_extra($a, $data, $user_info);
1863 return api_format_data("statuses", $type, $data);
1866 /// @TODO move to top of file or somewhere better
1867 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1870 * Returns the most recent statuses posted by users this node knows about.
1872 * @brief Returns the list of public federated posts this node knows about
1874 * @param string $type Return format: json, xml, atom, rss
1875 * @return array|string
1876 * @throws ForbiddenException
1878 function api_statuses_networkpublic_timeline($type)
1882 if (api_user() === false) {
1883 throw new ForbiddenException();
1886 $user_info = api_get_user($a);
1888 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1889 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1892 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1893 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1897 $start = ($page - 1) * $count;
1901 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1905 "SELECT " . item_fieldlists() . "
1907 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1908 " . item_joins() . "
1909 WHERE `thread`.`uid` = 0
1911 AND NOT `thread`.`private`
1912 AND `thread`.`visible`
1913 AND NOT `thread`.`deleted`
1914 AND NOT `thread`.`moderated`
1915 AND `thread`.`iid` > ?
1917 ORDER BY `thread`.`iid` DESC
1918 LIMIT " . intval($start) . ", " . intval($count),
1923 $r = dba::inArray($r);
1925 $ret = api_format_items($r, $user_info, false, $type);
1927 $data = ['status' => $ret];
1931 $data = api_rss_extra($a, $data, $user_info);
1935 return api_format_data("statuses", $type, $data);
1938 /// @TODO move to top of file or somewhere better
1939 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1942 * Returns a single status.
1944 * @param string $type Return type (atom, rss, xml, json)
1946 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1948 function api_statuses_show($type)
1952 if (api_user() === false) {
1953 throw new ForbiddenException();
1956 $user_info = api_get_user($a);
1959 $id = intval($a->argv[3]);
1962 $id = intval($_REQUEST["id"]);
1967 $id = intval($a->argv[4]);
1970 logger('API: api_statuses_show: ' . $id);
1972 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1975 if ($conversation) {
1976 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1978 $sql_extra .= " AND `item`.`id` = %d";
1982 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1983 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1984 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1985 `contact`.`id` AS `cid`
1987 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1988 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1989 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1990 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1993 dbesc(ACTIVITY_POST),
1997 /// @TODO How about copying this to above methods which don't check $r ?
1998 if (!DBM::is_result($r)) {
1999 throw new BadRequestException("There is no status with this id.");
2002 $ret = api_format_items($r, $user_info, false, $type);
2004 if ($conversation) {
2005 $data = ['status' => $ret];
2006 return api_format_data("statuses", $type, $data);
2008 $data = ['status' => $ret[0]];
2009 return api_format_data("status", $type, $data);
2013 /// @TODO move to top of file or somewhere better
2014 api_register_func('api/statuses/show', 'api_statuses_show', true);
2018 * @param string $type Return type (atom, rss, xml, json)
2020 * @todo nothing to say?
2022 function api_conversation_show($type)
2026 if (api_user() === false) {
2027 throw new ForbiddenException();
2030 $user_info = api_get_user($a);
2033 $id = intval($a->argv[3]);
2034 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2035 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
2039 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2040 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2042 $start = $page*$count;
2045 $id = intval($_REQUEST["id"]);
2050 $id = intval($a->argv[4]);
2053 logger('API: api_conversation_show: '.$id);
2055 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
2056 if (DBM::is_result($r)) {
2057 $id = $r[0]["parent"];
2063 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2066 // Not sure why this query was so complicated. We should keep it here for a while,
2067 // just to make sure that we really don't need it.
2068 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
2069 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
2072 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2073 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2074 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2075 `contact`.`id` AS `cid`
2077 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2078 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2079 WHERE `item`.`parent` = %d AND `item`.`visible`
2080 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2081 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2082 AND `item`.`id`>%d $sql_extra
2083 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2086 dbesc(ACTIVITY_POST),
2092 if (!DBM::is_result($r)) {
2093 throw new BadRequestException("There is no status with this id.");
2096 $ret = api_format_items($r, $user_info, false, $type);
2098 $data = ['status' => $ret];
2099 return api_format_data("statuses", $type, $data);
2102 /// @TODO move to top of file or somewhere better
2103 api_register_func('api/conversation/show', 'api_conversation_show', true);
2104 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2109 * @param string $type Return type (atom, rss, xml, json)
2111 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2113 function api_statuses_repeat($type)
2119 if (api_user() === false) {
2120 throw new ForbiddenException();
2126 $id = intval($a->argv[3]);
2129 $id = intval($_REQUEST["id"]);
2134 $id = intval($a->argv[4]);
2137 logger('API: api_statuses_repeat: '.$id);
2140 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2141 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2142 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2143 `contact`.`id` AS `cid`
2145 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2146 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2147 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2148 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2149 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2151 AND `item`.`id`=%d",
2155 /// @TODO other style than above functions!
2156 if (DBM::is_result($r) && $r[0]['body'] != "") {
2157 if (strpos($r[0]['body'], "[/share]") !== false) {
2158 $pos = strpos($r[0]['body'], "[share");
2159 $post = substr($r[0]['body'], $pos);
2161 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2163 $post .= $r[0]['body'];
2164 $post .= "[/share]";
2166 $_REQUEST['body'] = $post;
2167 $_REQUEST['profile_uid'] = api_user();
2168 $_REQUEST['type'] = 'wall';
2169 $_REQUEST['api_source'] = true;
2171 if (!x($_REQUEST, "source")) {
2172 $_REQUEST["source"] = api_source();
2177 throw new ForbiddenException();
2180 // this should output the last post (the one we just posted).
2182 return api_status_show($type);
2185 /// @TODO move to top of file or somewhere better
2186 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2189 * Destroys a specific status.
2191 * @param string $type Return type (atom, rss, xml, json)
2193 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2195 function api_statuses_destroy($type)
2199 if (api_user() === false) {
2200 throw new ForbiddenException();
2206 $id = intval($a->argv[3]);
2209 $id = intval($_REQUEST["id"]);
2214 $id = intval($a->argv[4]);
2217 logger('API: api_statuses_destroy: '.$id);
2219 $ret = api_statuses_show($type);
2226 /// @TODO move to top of file or somewhere better
2227 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2230 * Returns the most recent mentions.
2232 * @param string $type Return type (atom, rss, xml, json)
2234 * @see http://developer.twitter.com/doc/get/statuses/mentions
2236 function api_statuses_mentions($type)
2240 if (api_user() === false) {
2241 throw new ForbiddenException();
2244 unset($_REQUEST["user_id"]);
2245 unset($_GET["user_id"]);
2247 unset($_REQUEST["screen_name"]);
2248 unset($_GET["screen_name"]);
2250 $user_info = api_get_user($a);
2251 // get last newtork messages
2255 $since_id = defaults($_REQUEST, 'since_id', 0);
2256 $max_id = defaults($_REQUEST, 'max_id' , 0);
2257 $count = defaults($_REQUEST, 'count' , 20);
2258 $page = defaults($_REQUEST, 'page' , 1);
2263 $start = ($page - 1) * $count;
2265 // Ugly code - should be changed
2266 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2267 $myurl = substr($myurl, strpos($myurl, '://') + 3);
2268 $myurl = str_replace('www.', '', $myurl);
2271 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2275 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2276 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2277 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2278 `contact`.`id` AS `cid`
2279 FROM `item` FORCE INDEX (`uid_id`)
2280 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2281 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2282 WHERE `item`.`uid` = %d AND `verb` = '%s'
2283 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2284 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2285 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2288 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2290 dbesc(ACTIVITY_POST),
2291 dbesc(protect_sprintf($myurl)),
2292 dbesc(protect_sprintf($myurl)),
2299 $ret = api_format_items($r, $user_info, false, $type);
2301 $data = ['status' => $ret];
2305 $data = api_rss_extra($a, $data, $user_info);
2309 return api_format_data("statuses", $type, $data);
2312 /// @TODO move to top of file or somewhere better
2313 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2314 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2317 * Returns the most recent statuses posted by the user.
2319 * @brief Returns a user's public timeline
2321 * @param string $type Either "json" or "xml"
2322 * @return string|array
2323 * @throws ForbiddenException
2324 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2326 function api_statuses_user_timeline($type)
2330 if (api_user() === false) {
2331 throw new ForbiddenException();
2334 $user_info = api_get_user($a);
2337 "api_statuses_user_timeline: api_user: ". api_user() .
2338 "\nuser_info: ".print_r($user_info, true) .
2339 "\n_REQUEST: ".print_r($_REQUEST, true),
2343 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2344 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2345 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2346 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2349 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2350 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2354 $start = ($page - 1) * $count;
2357 if ($user_info['self'] == 1) {
2358 $sql_extra .= " AND `item`.`wall` = 1 ";
2361 if ($exclude_replies > 0) {
2362 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2365 if ($conversation_id > 0) {
2366 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2370 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2374 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2375 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2376 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2377 `contact`.`id` AS `cid`
2378 FROM `item` FORCE INDEX (`uid_contactid_id`)
2379 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2380 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2381 WHERE `item`.`uid` = %d AND `verb` = '%s'
2382 AND `item`.`contact-id` = %d
2383 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2385 AND `item`.`id` > %d
2386 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2388 dbesc(ACTIVITY_POST),
2389 intval($user_info['cid']),
2395 $ret = api_format_items($r, $user_info, true, $type);
2397 $data = ['status' => $ret];
2401 $data = api_rss_extra($a, $data, $user_info);
2405 return api_format_data("statuses", $type, $data);
2408 /// @TODO move to top of file or somewhere better
2409 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2412 * Star/unstar an item.
2413 * param: id : id of the item
2415 * @param string $type Return type (atom, rss, xml, json)
2417 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2419 function api_favorites_create_destroy($type)
2423 if (api_user() === false) {
2424 throw new ForbiddenException();
2427 // for versioned api.
2428 /// @TODO We need a better global soluton
2429 $action_argv_id = 2;
2430 if ($a->argv[1] == "1.1") {
2431 $action_argv_id = 3;
2434 if ($a->argc <= $action_argv_id) {
2435 throw new BadRequestException("Invalid request.");
2437 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2438 if ($a->argc == $action_argv_id + 2) {
2439 $itemid = intval($a->argv[$action_argv_id + 1]);
2441 /// @TODO use x() to check if _REQUEST contains 'id'
2442 $itemid = intval($_REQUEST['id']);
2445 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2447 if (!DBM::is_result($item) || count($item) == 0) {
2448 throw new BadRequestException("Invalid item.");
2453 $item[0]['starred'] = 1;
2456 $item[0]['starred'] = 0;
2459 throw new BadRequestException("Invalid action ".$action);
2462 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2464 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2467 throw new InternalServerErrorException("DB error");
2471 $user_info = api_get_user($a);
2472 $rets = api_format_items($item, $user_info, false, $type);
2475 $data = ['status' => $ret];
2479 $data = api_rss_extra($a, $data, $user_info);
2482 return api_format_data("status", $type, $data);
2485 /// @TODO move to top of file or somewhere better
2486 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2487 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2490 * Returns the most recent favorite statuses.
2492 * @param string $type Return type (atom, rss, xml, json)
2494 * @return string|array
2496 function api_favorites($type)
2502 if (api_user() === false) {
2503 throw new ForbiddenException();
2508 $user_info = api_get_user($a);
2510 // in friendica starred item are private
2511 // return favorites only for self
2512 logger('api_favorites: self:' . $user_info['self']);
2514 if ($user_info['self'] == 0) {
2520 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2521 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2522 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2523 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2528 $start = $page*$count;
2531 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2535 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2536 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2537 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2538 `contact`.`id` AS `cid`
2539 FROM `item`, `contact`
2540 WHERE `item`.`uid` = %d
2541 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2542 AND `item`.`starred` = 1
2543 AND `contact`.`id` = `item`.`contact-id`
2544 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2547 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2554 $ret = api_format_items($r, $user_info, false, $type);
2557 $data = ['status' => $ret];
2561 $data = api_rss_extra($a, $data, $user_info);
2564 return api_format_data("statuses", $type, $data);
2567 /// @TODO move to top of file or somewhere better
2568 api_register_func('api/favorites', 'api_favorites', true);
2572 * @param array $item
2573 * @param array $recipient
2574 * @param array $sender
2578 function api_format_messages($item, $recipient, $sender)
2580 // standard meta information
2582 'id' => $item['id'],
2583 'sender_id' => $sender['id'] ,
2585 'recipient_id' => $recipient['id'],
2586 'created_at' => api_date($item['created']),
2587 'sender_screen_name' => $sender['screen_name'],
2588 'recipient_screen_name' => $recipient['screen_name'],
2589 'sender' => $sender,
2590 'recipient' => $recipient,
2592 'friendica_seen' => $item['seen'],
2593 'friendica_parent_uri' => $item['parent-uri'],
2596 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2597 unset($ret["sender"]["uid"]);
2598 unset($ret["sender"]["self"]);
2599 unset($ret["recipient"]["uid"]);
2600 unset($ret["recipient"]["self"]);
2602 //don't send title to regular StatusNET requests to avoid confusing these apps
2603 if (x($_GET, 'getText')) {
2604 $ret['title'] = $item['title'];
2605 if ($_GET['getText'] == 'html') {
2606 $ret['text'] = bbcode($item['body'], false, false);
2607 } elseif ($_GET['getText'] == 'plain') {
2608 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2609 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2612 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2614 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2615 unset($ret['sender']);
2616 unset($ret['recipient']);
2624 * @param array $item
2628 function api_convert_item($item)
2630 $body = $item['body'];
2631 $attachments = api_get_attachments($body);
2633 // Workaround for ostatus messages where the title is identically to the body
2634 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2635 $statusbody = trim(html2plain($html, 0));
2637 // handle data: images
2638 $statusbody = api_format_items_embeded_images($item, $statusbody);
2640 $statustitle = trim($item['title']);
2642 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2643 $statustext = trim($statusbody);
2645 $statustext = trim($statustitle."\n\n".$statusbody);
2648 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2649 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2652 $statushtml = trim(bbcode($body, false, false));
2654 // Workaround for clients with limited HTML parser functionality
2655 $search = ["<br>", "<blockquote>", "</blockquote>",
2656 "<h1>", "</h1>", "<h2>", "</h2>",
2657 "<h3>", "</h3>", "<h4>", "</h4>",
2658 "<h5>", "</h5>", "<h6>", "</h6>"];
2659 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2660 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2661 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2662 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2663 $statushtml = str_replace($search, $replace, $statushtml);
2665 if ($item['title'] != "") {
2666 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2670 $oldtext = $statushtml;
2671 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2672 } while ($oldtext != $statushtml);
2674 if (substr($statushtml, 0, 4) == '<br>') {
2675 $statushtml = substr($statushtml, 4);
2678 if (substr($statushtml, 0, -4) == '<br>') {
2679 $statushtml = substr($statushtml, -4);
2682 // feeds without body should contain the link
2683 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2684 $statushtml .= bbcode($item['plink']);
2687 $entities = api_get_entitities($statustext, $body);
2690 "text" => $statustext,
2691 "html" => $statushtml,
2692 "attachments" => $attachments,
2693 "entities" => $entities
2699 * @param string $body
2701 * @return array|false
2703 function api_get_attachments(&$body)
2706 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2708 $URLSearchString = "^\[\]";
2709 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2717 foreach ($images[1] as $image) {
2718 $imagedata = Image::getInfoFromURL($image);
2721 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2725 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2726 foreach ($images[0] as $orig) {
2727 $body = str_replace($orig, "", $body);
2731 return $attachments;
2736 * @param string $text
2737 * @param string $bbcode
2740 * @todo Links at the first character of the post
2742 function api_get_entitities(&$text, $bbcode)
2744 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2746 if ($include_entities != "true") {
2747 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2749 foreach ($images[1] as $image) {
2750 $replace = proxy_url($image);
2751 $text = str_replace($image, $replace, $text);
2756 $bbcode = bb_CleanPictureLinks($bbcode);
2758 // Change pure links in text to bbcode uris
2759 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2762 $entities["hashtags"] = [];
2763 $entities["symbols"] = [];
2764 $entities["urls"] = [];
2765 $entities["user_mentions"] = [];
2767 $URLSearchString = "^\[\]";
2769 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2771 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2772 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2773 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2775 $bbcode = preg_replace(
2776 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2777 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2780 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2782 $bbcode = preg_replace(
2783 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2784 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2787 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2789 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2791 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2792 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2795 foreach ($urls[1] as $id => $url) {
2796 //$start = strpos($text, $url, $offset);
2797 $start = iconv_strpos($text, $url, 0, "UTF-8");
2798 if (!($start === false)) {
2799 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2803 ksort($ordered_urls);
2806 //foreach ($urls[1] AS $id=>$url) {
2807 foreach ($ordered_urls as $url) {
2808 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2809 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2811 $display_url = $url["title"];
2813 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2814 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2816 if (strlen($display_url) > 26) {
2817 $display_url = substr($display_url, 0, 25)."…";
2821 //$start = strpos($text, $url, $offset);
2822 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2823 if (!($start === false)) {
2824 $entities["urls"][] = ["url" => $url["url"],
2825 "expanded_url" => $url["url"],
2826 "display_url" => $display_url,
2827 "indices" => [$start, $start+strlen($url["url"])]];
2828 $offset = $start + 1;
2832 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2833 $ordered_images = [];
2834 foreach ($images[1] as $image) {
2835 //$start = strpos($text, $url, $offset);
2836 $start = iconv_strpos($text, $image, 0, "UTF-8");
2837 if (!($start === false)) {
2838 $ordered_images[$start] = $image;
2841 //$entities["media"] = array();
2844 foreach ($ordered_images as $url) {
2845 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2846 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2848 if (strlen($display_url) > 26) {
2849 $display_url = substr($display_url, 0, 25)."…";
2852 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2853 if (!($start === false)) {
2854 $image = Image::getInfoFromURL($url);
2856 // If image cache is activated, then use the following sizes:
2857 // thumb (150), small (340), medium (600) and large (1024)
2858 if (!Config::get("system", "proxy_disabled")) {
2859 $media_url = proxy_url($url);
2862 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2863 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2865 if (($image[0] > 150) || ($image[1] > 150)) {
2866 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2867 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2870 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2871 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2873 if (($image[0] > 600) || ($image[1] > 600)) {
2874 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2875 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2879 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2882 $entities["media"][] = [
2884 "id_str" => (string)$start+1,
2885 "indices" => [$start, $start+strlen($url)],
2886 "media_url" => normalise_link($media_url),
2887 "media_url_https" => $media_url,
2889 "display_url" => $display_url,
2890 "expanded_url" => $url,
2894 $offset = $start + 1;
2903 * @param array $item
2904 * @param string $text
2908 function api_format_items_embeded_images($item, $text)
2910 $text = preg_replace_callback(
2911 '|data:image/([^;]+)[^=]+=*|m',
2912 function () use ($item) {
2913 return System::baseUrl() . '/display/' . $item['guid'];
2921 * @brief return <a href='url'>name</a> as array
2923 * @param string $txt text
2928 function api_contactlink_to_array($txt)
2931 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2932 if ($r && count($match)==3) {
2934 'name' => $match[2],
2948 * @brief return likes, dislikes and attend status for item
2950 * @param array $item array
2951 * @param string $type Return type (atom, rss, xml, json)
2954 * likes => int count,
2955 * dislikes => int count
2957 function api_format_items_activities(&$item, $type = "json")
2966 'attendmaybe' => [],
2971 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2972 intval($item['uid']),
2976 foreach ($items as $i) {
2977 // not used as result should be structured like other user data
2978 //builtin_activity_puller($i, $activities);
2980 // get user data and add it to the array of the activity
2981 $user = api_get_user($a, $i['author-link']);
2982 switch ($i['verb']) {
2984 $activities['like'][] = $user;
2986 case ACTIVITY_DISLIKE:
2987 $activities['dislike'][] = $user;
2989 case ACTIVITY_ATTEND:
2990 $activities['attendyes'][] = $user;
2992 case ACTIVITY_ATTENDNO:
2993 $activities['attendno'][] = $user;
2995 case ACTIVITY_ATTENDMAYBE:
2996 $activities['attendmaybe'][] = $user;
3003 if ($type == "xml") {
3004 $xml_activities = [];
3005 foreach ($activities as $k => $v) {
3006 // change xml element from "like" to "friendica:like"
3007 $xml_activities["friendica:".$k] = $v;
3008 // add user data into xml output
3010 foreach ($v as $user) {
3011 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
3014 $activities = $xml_activities;
3022 * @brief return data from profiles
3024 * @param array $profile_row array containing data from db table 'profile'
3027 function api_format_items_profiles($profile_row)
3030 'profile_id' => $profile_row['id'],
3031 'profile_name' => $profile_row['profile-name'],
3032 'is_default' => $profile_row['is-default'] ? true : false,
3033 'hide_friends' => $profile_row['hide-friends'] ? true : false,
3034 'profile_photo' => $profile_row['photo'],
3035 'profile_thumb' => $profile_row['thumb'],
3036 'publish' => $profile_row['publish'] ? true : false,
3037 'net_publish' => $profile_row['net-publish'] ? true : false,
3038 'description' => $profile_row['pdesc'],
3039 'date_of_birth' => $profile_row['dob'],
3040 'address' => $profile_row['address'],
3041 'city' => $profile_row['locality'],
3042 'region' => $profile_row['region'],
3043 'postal_code' => $profile_row['postal-code'],
3044 'country' => $profile_row['country-name'],
3045 'hometown' => $profile_row['hometown'],
3046 'gender' => $profile_row['gender'],
3047 'marital' => $profile_row['marital'],
3048 'marital_with' => $profile_row['with'],
3049 'marital_since' => $profile_row['howlong'],
3050 'sexual' => $profile_row['sexual'],
3051 'politic' => $profile_row['politic'],
3052 'religion' => $profile_row['religion'],
3053 'public_keywords' => $profile_row['pub_keywords'],
3054 'private_keywords' => $profile_row['prv_keywords'],
3055 'likes' => bbcode(api_clean_plain_items($profile_row['likes']) , false, false, 2, false),
3056 'dislikes' => bbcode(api_clean_plain_items($profile_row['dislikes']) , false, false, 2, false),
3057 'about' => bbcode(api_clean_plain_items($profile_row['about']) , false, false, 2, false),
3058 'music' => bbcode(api_clean_plain_items($profile_row['music']) , false, false, 2, false),
3059 'book' => bbcode(api_clean_plain_items($profile_row['book']) , false, false, 2, false),
3060 'tv' => bbcode(api_clean_plain_items($profile_row['tv']) , false, false, 2, false),
3061 'film' => bbcode(api_clean_plain_items($profile_row['film']) , false, false, 2, false),
3062 'interest' => bbcode(api_clean_plain_items($profile_row['interest']) , false, false, 2, false),
3063 'romance' => bbcode(api_clean_plain_items($profile_row['romance']) , false, false, 2, false),
3064 'work' => bbcode(api_clean_plain_items($profile_row['work']) , false, false, 2, false),
3065 'education' => bbcode(api_clean_plain_items($profile_row['education']), false, false, 2, false),
3066 'social_networks' => bbcode(api_clean_plain_items($profile_row['contact']) , false, false, 2, false),
3067 'homepage' => $profile_row['homepage'],
3074 * @brief format items to be returned by api
3076 * @param array $r array of items
3077 * @param array $user_info
3078 * @param bool $filter_user filter items by $user_info
3079 * @param string $type Return type (atom, rss, xml, json)
3081 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
3087 foreach ($r as $item) {
3088 localize_item($item);
3089 list($status_user, $owner_user) = api_item_get_user($a, $item);
3091 // Look if the posts are matching if they should be filtered by user id
3092 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3096 $in_reply_to = api_in_reply_to($item);
3098 $converted = api_convert_item($item);
3100 if ($type == "xml") {
3101 $geo = "georss:point";
3107 'text' => $converted["text"],
3108 'truncated' => false,
3109 'created_at'=> api_date($item['created']),
3110 'in_reply_to_status_id' => $in_reply_to['status_id'],
3111 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3112 'source' => (($item['app']) ? $item['app'] : 'web'),
3113 'id' => intval($item['id']),
3114 'id_str' => (string) intval($item['id']),
3115 'in_reply_to_user_id' => $in_reply_to['user_id'],
3116 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3117 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3119 'favorited' => $item['starred'] ? true : false,
3120 'user' => $status_user ,
3121 'friendica_owner' => $owner_user,
3122 //'entities' => NULL,
3123 'statusnet_html' => $converted["html"],
3124 'statusnet_conversation_id' => $item['parent'],
3125 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3126 'friendica_activities' => api_format_items_activities($item, $type),
3129 if (count($converted["attachments"]) > 0) {
3130 $status["attachments"] = $converted["attachments"];
3133 if (count($converted["entities"]) > 0) {
3134 $status["entities"] = $converted["entities"];
3137 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
3138 $status["source"] = ContactSelector::networkToName($item['item_network'], $user_info['url']);
3139 } elseif (($item['item_network'] != "") && (ContactSelector::networkToName($item['item_network'], $user_info['url']) != $status["source"])) {
3140 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['item_network'], $user_info['url']).')');
3144 // Retweets are only valid for top postings
3145 // It doesn't work reliable with the link if its a feed
3146 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
3148 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
3151 if ($item["id"] == $item["parent"]) {
3152 $retweeted_item = api_share_as_retweet($item);
3153 if ($retweeted_item !== false) {
3154 $retweeted_status = $status;
3156 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
3157 } catch (BadRequestException $e) {
3158 // user not found. should be found?
3159 /// @todo check if the user should be always found
3160 $retweeted_status["user"] = [];
3163 $rt_converted = api_convert_item($retweeted_item);
3165 $retweeted_status['text'] = $rt_converted["text"];
3166 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3167 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3168 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3169 $status['retweeted_status'] = $retweeted_status;
3173 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3174 unset($status["user"]["uid"]);
3175 unset($status["user"]["self"]);
3177 if ($item["coord"] != "") {
3178 $coords = explode(' ', $item["coord"]);
3179 if (count($coords) == 2) {
3180 if ($type == "json") {
3181 $status["geo"] = ['type' => 'Point',
3182 'coordinates' => [(float) $coords[0],
3183 (float) $coords[1]]];
3184 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3185 $status["georss:point"] = $item["coord"];
3195 * Returns the remaining number of API requests available to the user before the API limit is reached.
3197 * @param string $type Return type (atom, rss, xml, json)
3199 * @return array|string
3201 function api_account_rate_limit_status($type)
3203 if ($type == "xml") {
3205 'remaining-hits' => '150',
3206 '@attributes' => ["type" => "integer"],
3207 'hourly-limit' => '150',
3208 '@attributes2' => ["type" => "integer"],
3209 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
3210 '@attributes3' => ["type" => "datetime"],
3211 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3212 '@attributes4' => ["type" => "integer"],
3216 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3217 'remaining_hits' => '150',
3218 'hourly_limit' => '150',
3219 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
3223 return api_format_data('hash', $type, ['hash' => $hash]);
3226 /// @TODO move to top of file or somewhere better
3227 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3230 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3232 * @param string $type Return type (atom, rss, xml, json)
3234 * @return array|string
3236 function api_help_test($type)
3238 if ($type == 'xml') {
3244 return api_format_data('ok', $type, ["ok" => $ok]);
3247 /// @TODO move to top of file or somewhere better
3248 api_register_func('api/help/test', 'api_help_test', false);
3252 * @param string $type Return type (atom, rss, xml, json)
3254 * @return array|string
3256 function api_lists($type)
3259 /// @TODO $ret is not filled here?
3260 return api_format_data('lists', $type, ["lists_list" => $ret]);
3263 /// @TODO move to top of file or somewhere better
3264 api_register_func('api/lists', 'api_lists', true);
3267 * Returns all lists the user subscribes to.
3269 * @param string $type Return type (atom, rss, xml, json)
3271 * @return array|string
3272 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3274 function api_lists_list($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/list', 'api_lists_list', true);
3285 * Considers friends and followers lists to be private and won't return
3286 * anything if any user_id parameter is passed.
3288 * @brief Returns either the friends of the follower list
3290 * @param string $qtype Either "friends" or "followers"
3291 * @return boolean|array
3292 * @throws ForbiddenException
3294 function api_statuses_f($qtype)
3298 if (api_user() === false) {
3299 throw new ForbiddenException();
3303 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3304 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3308 $start = ($page - 1) * $count;
3310 $user_info = api_get_user($a);
3312 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3313 /* this is to stop Hotot to load friends multiple times
3314 * I'm not sure if I'm missing return something or
3315 * is a bug in hotot. Workaround, meantime
3319 return array('$users' => $ret);*/
3324 if ($qtype == 'friends') {
3325 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3326 } elseif ($qtype == 'followers') {
3327 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3330 // friends and followers only for self
3331 if ($user_info['self'] == 0) {
3332 $sql_extra = " AND false ";
3335 if ($qtype == 'blocks') {
3336 $sql_filter = 'AND `blocked` AND NOT `pending`';
3337 } elseif ($qtype == 'incoming') {
3338 $sql_filter = 'AND `pending`';
3340 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3358 foreach ($r as $cid) {
3359 $user = api_get_user($a, $cid['nurl']);
3360 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3361 unset($user["uid"]);
3362 unset($user["self"]);
3369 return ['user' => $ret];
3374 * Returns the user's friends.
3376 * @brief Returns the list of friends of the provided user
3378 * @deprecated By Twitter API in favor of friends/list
3380 * @param string $type Either "json" or "xml"
3381 * @return boolean|string|array
3383 function api_statuses_friends($type)
3385 $data = api_statuses_f("friends");
3386 if ($data === false) {
3389 return api_format_data("users", $type, $data);
3393 * Returns the user's followers.
3395 * @brief Returns the list of followers of the provided user
3397 * @deprecated By Twitter API in favor of friends/list
3399 * @param string $type Either "json" or "xml"
3400 * @return boolean|string|array
3402 function api_statuses_followers($type)
3404 $data = api_statuses_f("followers");
3405 if ($data === false) {
3408 return api_format_data("users", $type, $data);
3411 /// @TODO move to top of file or somewhere better
3412 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3413 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3416 * Returns the list of blocked users
3418 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3420 * @param string $type Either "json" or "xml"
3422 * @return boolean|string|array
3424 function api_blocks_list($type)
3426 $data = api_statuses_f('blocks');
3427 if ($data === false) {
3430 return api_format_data("users", $type, $data);
3433 /// @TODO move to top of file or somewhere better
3434 api_register_func('api/blocks/list', 'api_blocks_list', true);
3437 * Returns the list of pending users IDs
3439 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3441 * @param string $type Either "json" or "xml"
3443 * @return boolean|string|array
3445 function api_friendships_incoming($type)
3447 $data = api_statuses_f('incoming');
3448 if ($data === false) {
3453 foreach ($data['user'] as $user) {
3454 $ids[] = $user['id'];
3457 return api_format_data("ids", $type, ['id' => $ids]);
3460 /// @TODO move to top of file or somewhere better
3461 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3464 * Returns the instance's configuration information.
3466 * @param string $type Return type (atom, rss, xml, json)
3468 * @return array|string
3470 function api_statusnet_config($type)
3474 $name = $a->config['sitename'];
3475 $server = $a->get_hostname();
3476 $logo = System::baseUrl() . '/images/friendica-64.png';
3477 $email = $a->config['admin_email'];
3478 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3479 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3480 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3481 if ($a->config['api_import_size']) {
3482 $textlimit = (string) $a->config['api_import_size'];
3484 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3485 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3488 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3489 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3490 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3491 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3492 'shorturllength' => '30',
3494 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3495 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3496 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3497 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3502 return api_format_data('config', $type, ['config' => $config]);
3505 /// @TODO move to top of file or somewhere better
3506 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3507 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3511 * @param string $type Return type (atom, rss, xml, json)
3513 * @return array|string
3515 function api_statusnet_version($type)
3518 $fake_statusnet_version = "0.9.7";
3520 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3523 /// @TODO move to top of file or somewhere better
3524 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3525 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3529 * @param string $type Return type (atom, rss, xml, json)
3531 * @todo use api_format_data() to return data
3533 function api_ff_ids($type)
3536 throw new ForbiddenException();
3541 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3544 "SELECT `pcontact`.`id` FROM `contact`
3545 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3546 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3549 if (!DBM::is_result($r)) {
3554 foreach ($r as $rr) {
3555 if ($stringify_ids) {
3558 $ids[] = intval($rr['id']);
3562 return api_format_data("ids", $type, ['id' => $ids]);
3566 * Returns the ID of every user the user is following.
3568 * @param string $type Return type (atom, rss, xml, json)
3570 * @return array|string
3571 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3573 function api_friends_ids($type)
3575 return api_ff_ids($type);
3579 * Returns the ID of every user following the user.
3581 * @param string $type Return type (atom, rss, xml, json)
3583 * @return array|string
3584 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3586 function api_followers_ids($type)
3588 return api_ff_ids($type);
3591 /// @TODO move to top of file or somewhere better
3592 api_register_func('api/friends/ids', 'api_friends_ids', true);
3593 api_register_func('api/followers/ids', 'api_followers_ids', true);
3596 * Sends a new direct message.
3598 * @param string $type Return type (atom, rss, xml, json)
3600 * @return array|string
3601 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3603 function api_direct_messages_new($type)
3608 if (api_user() === false) {
3609 throw new ForbiddenException();
3612 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3616 $sender = api_get_user($a);
3618 if ($_POST['screen_name']) {
3620 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3622 dbesc($_POST['screen_name'])
3625 // Selecting the id by priority, friendica first
3626 api_best_nickname($r);
3628 $recipient = api_get_user($a, $r[0]['nurl']);
3630 $recipient = api_get_user($a, $_POST['user_id']);
3635 if (x($_REQUEST, 'replyto')) {
3637 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3639 intval($_REQUEST['replyto'])
3641 $replyto = $r[0]['parent-uri'];
3642 $sub = $r[0]['title'];
3644 if (x($_REQUEST, 'title')) {
3645 $sub = $_REQUEST['title'];
3647 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3651 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3654 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3655 $ret = api_format_messages($r[0], $recipient, $sender);
3657 $ret = ["error"=>$id];
3660 $data = ['direct_message'=>$ret];
3665 $data = api_rss_extra($a, $data, $user_info);
3668 return api_format_data("direct-messages", $type, $data);
3671 /// @TODO move to top of file or somewhere better
3672 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3675 * Destroys a direct message.
3677 * @brief delete a direct_message from mail table through api
3679 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3681 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3683 function api_direct_messages_destroy($type)
3687 if (api_user() === false) {
3688 throw new ForbiddenException();
3692 $user_info = api_get_user($a);
3694 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3696 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3697 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3698 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3700 $uid = $user_info['uid'];
3701 // error if no id or parenturi specified (for clients posting parent-uri as well)
3702 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3703 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3704 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3707 // BadRequestException if no id specified (for clients using Twitter API)
3709 throw new BadRequestException('Message id not specified');
3712 // add parent-uri to sql command if specified by calling app
3713 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3715 // get data of the specified message id
3717 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3722 // error message if specified id is not in database
3723 if (!DBM::is_result($r)) {
3724 if ($verbose == "true") {
3725 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3726 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3728 /// @todo BadRequestException ok for Twitter API clients?
3729 throw new BadRequestException('message id not in database');
3734 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3739 if ($verbose == "true") {
3742 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3743 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3745 $answer = ['result' => 'error', 'message' => 'unknown error'];
3746 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3749 /// @todo return JSON data like Twitter API not yet implemented
3752 /// @TODO move to top of file or somewhere better
3753 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3757 * @param string $type Return type (atom, rss, xml, json)
3758 * @param string $box
3759 * @param string $verbose
3761 * @return array|string
3763 function api_direct_messages_box($type, $box, $verbose)
3767 if (api_user() === false) {
3768 throw new ForbiddenException();
3772 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3773 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3778 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3779 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3781 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3782 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3785 unset($_REQUEST["user_id"]);
3786 unset($_GET["user_id"]);
3788 unset($_REQUEST["screen_name"]);
3789 unset($_GET["screen_name"]);
3791 $user_info = api_get_user($a);
3792 $profile_url = $user_info["url"];
3795 $start = $page * $count;
3798 if ($box=="sentbox") {
3799 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3800 } elseif ($box == "conversation") {
3801 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3802 } elseif ($box == "all") {
3803 $sql_extra = "true";
3804 } elseif ($box == "inbox") {
3805 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3809 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3812 if ($user_id != "") {
3813 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3814 } elseif ($screen_name !="") {
3815 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3819 "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",
3825 if ($verbose == "true" && !DBM::is_result($r)) {
3826 $answer = ['result' => 'error', 'message' => 'no mails available'];
3827 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3831 foreach ($r as $item) {
3832 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3833 $recipient = $user_info;
3834 $sender = api_get_user($a, normalise_link($item['contact-url']));
3835 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3836 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3837 $sender = $user_info;
3840 $ret[] = api_format_messages($item, $recipient, $sender);
3844 $data = ['direct_message' => $ret];
3848 $data = api_rss_extra($a, $data, $user_info);
3851 return api_format_data("direct-messages", $type, $data);
3855 * Returns the most recent direct messages sent by the user.
3857 * @param string $type Return type (atom, rss, xml, json)
3859 * @return array|string
3860 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3862 function api_direct_messages_sentbox($type)
3864 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3865 return api_direct_messages_box($type, "sentbox", $verbose);
3869 * Returns the most recent direct messages sent to the user.
3871 * @param string $type Return type (atom, rss, xml, json)
3873 * @return array|string
3874 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3876 function api_direct_messages_inbox($type)
3878 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3879 return api_direct_messages_box($type, "inbox", $verbose);
3884 * @param string $type Return type (atom, rss, xml, json)
3886 * @return array|string
3888 function api_direct_messages_all($type)
3890 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3891 return api_direct_messages_box($type, "all", $verbose);
3896 * @param string $type Return type (atom, rss, xml, json)
3898 * @return array|string
3900 function api_direct_messages_conversation($type)
3902 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3903 return api_direct_messages_box($type, "conversation", $verbose);
3906 /// @TODO move to top of file or somewhere better
3907 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3908 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3909 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3910 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3913 * Returns an OAuth Request Token.
3915 * @see https://oauth.net/core/1.0/#auth_step1
3917 function api_oauth_request_token()
3919 $oauth1 = new FKOAuth1();
3921 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3922 } catch (Exception $e) {
3923 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3931 * Returns an OAuth Access Token.
3933 * @return array|string
3934 * @see https://oauth.net/core/1.0/#auth_step3
3936 function api_oauth_access_token()
3938 $oauth1 = new FKOAuth1();
3940 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3941 } catch (Exception $e) {
3942 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3949 /// @TODO move to top of file or somewhere better
3950 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3951 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3955 * @brief delete a complete photoalbum with all containing photos from database through api
3957 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3960 function api_fr_photoalbum_delete($type)
3962 if (api_user() === false) {
3963 throw new ForbiddenException();
3966 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3968 // we do not allow calls without album string
3970 throw new BadRequestException("no albumname specified");
3972 // check if album is existing
3974 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3978 if (!DBM::is_result($r)) {
3979 throw new BadRequestException("album not available");
3982 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3983 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3984 foreach ($r as $rr) {
3986 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3987 intval(local_user()),
3988 dbesc($rr['resource-id'])
3991 if (!DBM::is_result($photo_item)) {
3992 throw new InternalServerErrorException("problem with deleting items occured");
3994 Item::delete($photo_item[0]['id']);
3997 // now let's delete all photos from the album
3998 $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
4000 // return success of deletion or error message
4002 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4003 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4005 throw new InternalServerErrorException("unknown error - deleting from database failed");
4010 * @brief update the name of the album for all photos of an album
4012 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4015 function api_fr_photoalbum_update($type)
4017 if (api_user() === false) {
4018 throw new ForbiddenException();
4021 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
4022 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
4024 // we do not allow calls without album string
4026 throw new BadRequestException("no albumname specified");
4028 if ($album_new == "") {
4029 throw new BadRequestException("no new albumname specified");
4031 // check if album is existing
4033 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4037 if (!DBM::is_result($r)) {
4038 throw new BadRequestException("album not available");
4040 // now let's update all photos to the albumname
4042 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
4048 // return success of updating or error message
4050 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4051 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4053 throw new InternalServerErrorException("unknown error - updating in database failed");
4059 * @brief list all photos of the authenticated user
4061 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4064 function api_fr_photos_list($type)
4066 if (api_user() === false) {
4067 throw new ForbiddenException();
4070 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4071 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4072 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4073 intval(local_user())
4076 'image/jpeg' => 'jpg',
4077 'image/png' => 'png',
4078 'image/gif' => 'gif'
4080 $data = ['photo'=>[]];
4081 if (DBM::is_result($r)) {
4082 foreach ($r as $rr) {
4084 $photo['id'] = $rr['resource-id'];
4085 $photo['album'] = $rr['album'];
4086 $photo['filename'] = $rr['filename'];
4087 $photo['type'] = $rr['type'];
4088 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4089 $photo['created'] = $rr['created'];
4090 $photo['edited'] = $rr['edited'];
4091 $photo['desc'] = $rr['desc'];
4093 if ($type == "xml") {
4094 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4096 $photo['thumb'] = $thumb;
4097 $data['photo'][] = $photo;
4101 return api_format_data("photos", $type, $data);
4105 * @brief upload a new photo or change an existing photo
4107 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4110 function api_fr_photo_create_update($type)
4112 if (api_user() === false) {
4113 throw new ForbiddenException();
4116 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4117 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4118 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4119 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4120 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4121 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4122 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4123 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4124 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4126 // do several checks on input parameters
4127 // we do not allow calls without album string
4128 if ($album == null) {
4129 throw new BadRequestException("no albumname specified");
4131 // if photo_id == null --> we are uploading a new photo
4132 if ($photo_id == null) {
4135 // error if no media posted in create-mode
4136 if (!x($_FILES, 'media')) {
4138 throw new BadRequestException("no media data submitted");
4141 // album_new will be ignored in create-mode
4146 // check if photo is existing in database
4148 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4153 if (!DBM::is_result($r)) {
4154 throw new BadRequestException("photo not available");
4158 // checks on acl strings provided by clients
4159 $acl_input_error = false;
4160 $acl_input_error |= check_acl_input($allow_cid);
4161 $acl_input_error |= check_acl_input($deny_cid);
4162 $acl_input_error |= check_acl_input($allow_gid);
4163 $acl_input_error |= check_acl_input($deny_gid);
4164 if ($acl_input_error) {
4165 throw new BadRequestException("acl data invalid");
4167 // now let's upload the new media in create-mode
4168 if ($mode == "create") {
4169 $media = $_FILES['media'];
4170 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4172 // return success of updating or error message
4173 if (!is_null($data)) {
4174 return api_format_data("photo_create", $type, $data);
4176 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4180 // now let's do the changes in update-mode
4181 if ($mode == "update") {
4184 if (!is_null($desc)) {
4185 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4188 if (!is_null($album_new)) {
4189 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4192 if (!is_null($allow_cid)) {
4193 $allow_cid = trim($allow_cid);
4194 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4197 if (!is_null($deny_cid)) {
4198 $deny_cid = trim($deny_cid);
4199 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4202 if (!is_null($allow_gid)) {
4203 $allow_gid = trim($allow_gid);
4204 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4207 if (!is_null($deny_gid)) {
4208 $deny_gid = trim($deny_gid);
4209 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4213 if ($sql_extra != "") {
4214 $nothingtodo = false;
4216 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4218 datetime_convert(), // update edited timestamp
4224 $nothingtodo = true;
4227 if (x($_FILES, 'media')) {
4228 $nothingtodo = false;
4229 $media = $_FILES['media'];
4230 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4231 if (!is_null($data)) {
4232 return api_format_data("photo_update", $type, $data);
4236 // return success of updating or error message
4238 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4239 return api_format_data("photo_update", $type, ['$result' => $answer]);
4242 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4243 return api_format_data("photo_update", $type, ['$result' => $answer]);
4245 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4248 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4253 * @brief delete a single photo from the database through api
4255 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4258 function api_fr_photo_delete($type)
4260 if (api_user() === false) {
4261 throw new ForbiddenException();
4264 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4266 // do several checks on input parameters
4267 // we do not allow calls without photo id
4268 if ($photo_id == null) {
4269 throw new BadRequestException("no photo_id specified");
4271 // check if photo is existing in database
4273 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4277 if (!DBM::is_result($r)) {
4278 throw new BadRequestException("photo not available");
4280 // now we can perform on the deletion of the photo
4281 $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4283 // return success of deletion or error message
4285 // retrieve the id of the parent element (the photo element)
4287 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4288 intval(local_user()),
4292 if (!DBM::is_result($photo_item)) {
4293 throw new InternalServerErrorException("problem with deleting items occured");
4295 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4296 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4297 Item::delete($photo_item[0]['id']);
4299 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4300 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4302 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4308 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4310 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4311 * @return string|array
4313 function api_fr_photo_detail($type)
4315 if (api_user() === false) {
4316 throw new ForbiddenException();
4318 if (!x($_REQUEST, 'photo_id')) {
4319 throw new BadRequestException("No photo id.");
4322 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4323 $photo_id = $_REQUEST['photo_id'];
4325 // prepare json/xml output with data from database for the requested photo
4326 $data = prepare_photo_data($type, $scale, $photo_id);
4328 return api_format_data("photo_detail", $type, $data);
4333 * Updates the user’s profile image.
4335 * @brief updates the profile image for the user (either a specified profile or the default profile)
4337 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4340 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4342 function api_account_update_profile_image($type)
4344 if (api_user() === false) {
4345 throw new ForbiddenException();
4348 $profileid = defaults($_REQUEST, 'profile_id', 0);
4350 // error if image data is missing
4351 if (!x($_FILES, 'image')) {
4352 throw new BadRequestException("no media data submitted");
4355 // check if specified profile id is valid
4356 if ($profileid != 0) {
4358 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4362 // error message if specified profile id is not in database
4363 if (!DBM::is_result($r)) {
4364 throw new BadRequestException("profile_id not available");
4366 $is_default_profile = $r['profile'];
4368 $is_default_profile = 1;
4371 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4373 if (x($_FILES, 'image')) {
4374 $media = $_FILES['image'];
4375 } elseif (x($_FILES, 'media')) {
4376 $media = $_FILES['media'];
4378 // save new profile image
4379 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4382 if (is_array($media['type'])) {
4383 $filetype = $media['type'][0];
4385 $filetype = $media['type'];
4387 if ($filetype == "image/jpeg") {
4389 } elseif ($filetype == "image/png") {
4392 // change specified profile or all profiles to the new resource-id
4393 if ($is_default_profile) {
4395 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4396 dbesc($data['photo']['id']),
4397 intval(local_user())
4401 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
4402 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4403 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4404 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4405 intval(local_user())
4409 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4410 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4411 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4412 intval($_REQUEST['profile']),
4413 intval(local_user())
4417 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4418 // so that browsers will do a cache update unconditionally
4421 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4422 dbesc(datetime_convert()),
4423 intval(local_user())
4426 // Update global directory in background
4427 //$user = api_get_user(get_app());
4428 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4429 if ($url && strlen(Config::get('system', 'directory'))) {
4430 Worker::add(PRIORITY_LOW, "Directory", $url);
4433 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4435 // output for client
4437 return api_account_verify_credentials($type);
4439 // SaveMediaToDatabase failed for some reason
4440 throw new InternalServerErrorException("image upload failed");
4444 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4445 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4446 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4447 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4448 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4449 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4450 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4451 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4452 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4455 * Update user profile
4457 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4459 * @return array|string
4461 function api_account_update_profile($type)
4463 $local_user = api_user();
4464 $api_user = api_get_user(get_app());
4466 if (!empty($_POST['name'])) {
4467 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4468 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4469 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4470 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4473 if (isset($_POST['description'])) {
4474 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4475 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4476 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4479 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4480 // Update global directory in background
4481 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4482 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4485 return api_account_verify_credentials($type);
4488 /// @TODO move to top of file or somewhere better
4489 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4493 * @param string $acl_string
4495 function check_acl_input($acl_string)
4497 if ($acl_string == null || $acl_string == " ") {
4500 $contact_not_found = false;
4502 // split <x><y><z> into array of cid's
4503 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4505 // check for each cid if it is available on server
4506 $cid_array = $array[0];
4507 foreach ($cid_array as $cid) {
4508 $cid = str_replace("<", "", $cid);
4509 $cid = str_replace(">", "", $cid);
4511 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4515 $contact_not_found |= !DBM::is_result($contact);
4517 return $contact_not_found;
4522 * @param string $mediatype
4523 * @param array $media
4524 * @param string $type
4525 * @param string $album
4526 * @param string $allow_cid
4527 * @param string $deny_cid
4528 * @param string $allow_gid
4529 * @param string $deny_gid
4530 * @param string $desc
4531 * @param integer $profile
4532 * @param boolean $visibility
4533 * @param string $photo_id
4535 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)
4543 if (is_array($media)) {
4544 if (is_array($media['tmp_name'])) {
4545 $src = $media['tmp_name'][0];
4547 $src = $media['tmp_name'];
4549 if (is_array($media['name'])) {
4550 $filename = basename($media['name'][0]);
4552 $filename = basename($media['name']);
4554 if (is_array($media['size'])) {
4555 $filesize = intval($media['size'][0]);
4557 $filesize = intval($media['size']);
4559 if (is_array($media['type'])) {
4560 $filetype = $media['type'][0];
4562 $filetype = $media['type'];
4566 if ($filetype == "") {
4567 $filetype=Image::guessType($filename);
4569 $imagedata = getimagesize($src);
4571 $filetype = $imagedata['mime'];
4574 "File upload src: " . $src . " - filename: " . $filename .
4575 " - size: " . $filesize . " - type: " . $filetype,
4579 // check if there was a php upload error
4580 if ($filesize == 0 && $media['error'] == 1) {
4581 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4583 // check against max upload size within Friendica instance
4584 $maximagesize = Config::get('system', 'maximagesize');
4585 if ($maximagesize && ($filesize > $maximagesize)) {
4586 $formattedBytes = formatBytes($maximagesize);
4587 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4590 // create Photo instance with the data of the image
4591 $imagedata = @file_get_contents($src);
4592 $Image = new Image($imagedata, $filetype);
4593 if (! $Image->isValid()) {
4594 throw new InternalServerErrorException("unable to process image data");
4597 // check orientation of image
4598 $Image->orient($src);
4601 // check max length of images on server
4602 $max_length = Config::get('system', 'max_image_length');
4603 if (! $max_length) {
4604 $max_length = MAX_IMAGE_LENGTH;
4606 if ($max_length > 0) {
4607 $Image->scaleDown($max_length);
4608 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4610 $width = $Image->getWidth();
4611 $height = $Image->getHeight();
4613 // create a new resource-id if not already provided
4614 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
4616 if ($mediatype == "photo") {
4617 // upload normal image (scales 0, 1, 2)
4618 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4620 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4622 logger("photo upload: image upload with scale 0 (original size) failed");
4624 if ($width > 640 || $height > 640) {
4625 $Image->scaleDown(640);
4626 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4628 logger("photo upload: image upload with scale 1 (640x640) failed");
4632 if ($width > 320 || $height > 320) {
4633 $Image->scaleDown(320);
4634 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4636 logger("photo upload: image upload with scale 2 (320x320) failed");
4639 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4640 } elseif ($mediatype == "profileimage") {
4641 // upload profile image (scales 4, 5, 6)
4642 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4644 if ($width > 175 || $height > 175) {
4645 $Image->scaleDown(175);
4646 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4648 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4652 if ($width > 80 || $height > 80) {
4653 $Image->scaleDown(80);
4654 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4656 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4660 if ($width > 48 || $height > 48) {
4661 $Image->scaleDown(48);
4662 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4664 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4667 $Image->__destruct();
4668 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4672 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4673 if ($photo_id == null && $mediatype == "photo") {
4674 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4676 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4677 return prepare_photo_data($type, false, $hash);
4679 throw new InternalServerErrorException("image upload failed");
4685 * @param string $hash
4686 * @param string $allow_cid
4687 * @param string $deny_cid
4688 * @param string $allow_gid
4689 * @param string $deny_gid
4690 * @param string $filetype
4691 * @param boolean $visibility
4693 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4695 // get data about the api authenticated user
4696 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4697 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4700 $arr['guid'] = get_guid(32);
4701 $arr['uid'] = intval(api_user());
4703 $arr['parent-uri'] = $uri;
4704 $arr['type'] = 'photo';
4706 $arr['resource-id'] = $hash;
4707 $arr['contact-id'] = $owner_record[0]['id'];
4708 $arr['owner-name'] = $owner_record[0]['name'];
4709 $arr['owner-link'] = $owner_record[0]['url'];
4710 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4711 $arr['author-name'] = $owner_record[0]['name'];
4712 $arr['author-link'] = $owner_record[0]['url'];
4713 $arr['author-avatar'] = $owner_record[0]['thumb'];
4715 $arr['allow_cid'] = $allow_cid;
4716 $arr['allow_gid'] = $allow_gid;
4717 $arr['deny_cid'] = $deny_cid;
4718 $arr['deny_gid'] = $deny_gid;
4719 $arr['visible'] = $visibility;
4723 'image/jpeg' => 'jpg',
4724 'image/png' => 'png',
4725 'image/gif' => 'gif'
4728 // adds link to the thumbnail scale photo
4729 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4730 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4733 // do the magic for storing the item in the database and trigger the federation to other contacts
4739 * @param string $type
4741 * @param string $photo_id
4745 function prepare_photo_data($type, $scale, $photo_id)
4747 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4748 $data_sql = ($scale === false ? "" : "data, ");
4750 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4751 // clients needs to convert this in their way for further processing
4753 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4754 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4755 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4756 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4758 intval(local_user()),
4764 'image/jpeg' => 'jpg',
4765 'image/png' => 'png',
4766 'image/gif' => 'gif'
4769 // prepare output data for photo
4770 if (DBM::is_result($r)) {
4771 $data = ['photo' => $r[0]];
4772 $data['photo']['id'] = $data['photo']['resource-id'];
4773 if ($scale !== false) {
4774 $data['photo']['data'] = base64_encode($data['photo']['data']);
4776 unset($data['photo']['datasize']); //needed only with scale param
4778 if ($type == "xml") {
4779 $data['photo']['links'] = [];
4780 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4781 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4783 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4786 $data['photo']['link'] = [];
4787 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4789 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4790 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4794 unset($data['photo']['resource-id']);
4795 unset($data['photo']['minscale']);
4796 unset($data['photo']['maxscale']);
4798 throw new NotFoundException();
4801 // retrieve item element for getting activities (like, dislike etc.) related to photo
4803 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4804 intval(local_user()),
4807 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4809 // retrieve comments on photo
4811 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4812 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4813 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4814 `contact`.`id` AS `cid`
4816 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4817 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4818 WHERE `item`.`parent` = %d AND `item`.`visible`
4819 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4820 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4821 intval($item[0]['parent']),
4823 dbesc(ACTIVITY_POST)
4826 // prepare output of comments
4827 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4829 if ($type == "xml") {
4831 foreach ($commentData as $comment) {
4832 $comments[$k++ . ":comment"] = $comment;
4835 foreach ($commentData as $comment) {
4836 $comments[] = $comment;
4839 $data['photo']['friendica_comments'] = $comments;
4841 // include info if rights on photo and rights on item are mismatching
4842 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4843 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4844 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4845 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4846 $data['photo']['rights_mismatch'] = $rights_mismatch;
4853 * Similar as /mod/redir.php
4854 * redirect to 'url' after dfrn auth
4856 * Why this when there is mod/redir.php already?
4857 * This use api_user() and api_login()
4860 * c_url: url of remote contact to auth to
4861 * url: string, url to redirect after auth
4863 function api_friendica_remoteauth()
4865 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4866 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4868 if ($url === '' || $c_url === '') {
4869 throw new BadRequestException("Wrong parameters.");
4872 $c_url = normalise_link($c_url);
4876 $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4878 if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
4879 throw new BadRequestException("Unknown contact");
4882 $cid = $contact['id'];
4884 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4886 if ($contact['duplex'] && $contact['issued-id']) {
4887 $orig_id = $contact['issued-id'];
4888 $dfrn_id = '1:' . $orig_id;
4890 if ($contact['duplex'] && $contact['dfrn-id']) {
4891 $orig_id = $contact['dfrn-id'];
4892 $dfrn_id = '0:' . $orig_id;
4895 $sec = random_string();
4898 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4899 VALUES( %d, %s, '%s', '%s', %d )",
4907 logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
4908 $dest = ($url ? '&destination_url=' . $url : '');
4910 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4911 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4912 . '&type=profile&sec=' . $sec . $dest . $quiet
4915 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4918 * @brief Return the item shared, if the item contains only the [share] tag
4920 * @param array $item Sharer item
4921 * @return array|false Shared item or false if not a reshare
4923 function api_share_as_retweet(&$item)
4925 $body = trim($item["body"]);
4927 if (Diaspora::isReshare($body, false)===false) {
4931 /// @TODO "$1" should maybe mean '$1' ?
4932 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4934 * Skip if there is no shared message in there
4935 * we already checked this in diaspora::isReshare()
4936 * but better one more than one less...
4938 if ($body == $attributes) {
4943 // build the fake reshared item
4944 $reshared_item = $item;
4947 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4948 if ($matches[1] != "") {
4949 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4952 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4953 if ($matches[1] != "") {
4954 $author = $matches[1];
4958 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4959 if ($matches[1] != "") {
4960 $profile = $matches[1];
4963 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4964 if ($matches[1] != "") {
4965 $profile = $matches[1];
4969 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4970 if ($matches[1] != "") {
4971 $avatar = $matches[1];
4974 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4975 if ($matches[1] != "") {
4976 $avatar = $matches[1];
4980 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4981 if ($matches[1] != "") {
4982 $link = $matches[1];
4985 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4986 if ($matches[1] != "") {
4987 $link = $matches[1];
4991 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4992 if ($matches[1] != "") {
4993 $posted = $matches[1];
4996 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4997 if ($matches[1] != "") {
4998 $posted = $matches[1];
5001 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5003 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5007 $reshared_item["body"] = $shared_body;
5008 $reshared_item["author-name"] = $author;
5009 $reshared_item["author-link"] = $profile;
5010 $reshared_item["author-avatar"] = $avatar;
5011 $reshared_item["plink"] = $link;
5012 $reshared_item["created"] = $posted;
5013 $reshared_item["edited"] = $posted;
5015 return $reshared_item;
5020 * @param string $profile
5022 * @return string|false
5023 * @todo remove trailing junk from profile url
5024 * @todo pump.io check has to check the website
5026 function api_get_nick($profile)
5031 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5032 dbesc(normalise_link($profile))
5035 if (DBM::is_result($r)) {
5036 $nick = $r[0]["nick"];
5041 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5042 dbesc(normalise_link($profile))
5045 if (DBM::is_result($r)) {
5046 $nick = $r[0]["nick"];
5051 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5052 if ($friendica != $profile) {
5058 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5059 if ($diaspora != $profile) {
5065 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5066 if ($twitter != $profile) {
5073 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5074 if ($StatusnetHost != $profile) {
5075 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5076 if ($StatusnetUser != $profile) {
5077 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5078 $user = json_decode($UserData);
5080 $nick = $user->screen_name;
5086 // To-Do: look at the page if its really a pumpio site
5087 //if (!$nick == "") {
5088 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5089 // if ($pumpio != $profile)
5091 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5104 * @param array $item
5108 function api_in_reply_to($item)
5112 $in_reply_to['status_id'] = null;
5113 $in_reply_to['user_id'] = null;
5114 $in_reply_to['status_id_str'] = null;
5115 $in_reply_to['user_id_str'] = null;
5116 $in_reply_to['screen_name'] = null;
5118 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5120 "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
5121 intval($item['uid']),
5122 dbesc($item['thr-parent'])
5125 if (DBM::is_result($r)) {
5126 $in_reply_to['status_id'] = intval($r[0]['id']);
5128 $in_reply_to['status_id'] = intval($item['parent']);
5131 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5134 "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
5135 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
5136 WHERE `item`.`id` = %d LIMIT 1",
5137 intval($in_reply_to['status_id'])
5140 if (DBM::is_result($r)) {
5141 if ($r[0]['nick'] == "") {
5142 $r[0]['nick'] = api_get_nick($r[0]["url"]);
5145 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
5146 $in_reply_to['user_id'] = intval($r[0]['id']);
5147 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
5150 // There seems to be situation, where both fields are identical:
5151 // https://github.com/friendica/friendica/issues/1010
5152 // This is a bugfix for that.
5153 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5154 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
5155 $in_reply_to['status_id'] = null;
5156 $in_reply_to['user_id'] = null;
5157 $in_reply_to['status_id_str'] = null;
5158 $in_reply_to['user_id_str'] = null;
5159 $in_reply_to['screen_name'] = null;
5163 return $in_reply_to;
5168 * @param string $Text
5172 function api_clean_plain_items($Text)
5174 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5176 $Text = bb_CleanPictureLinks($Text);
5177 $URLSearchString = "^\[\]";
5179 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
5181 if ($include_entities == "true") {
5182 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
5185 // Simplify "attachment" element
5186 $Text = api_clean_attachments($Text);
5192 * @brief Removes most sharing information for API text export
5194 * @param string $body The original body
5196 * @return string Cleaned body
5198 function api_clean_attachments($body)
5200 $data = BBCode::getAttachmentData($body);
5207 if (isset($data["text"])) {
5208 $body = $data["text"];
5210 if (($body == "") && isset($data["title"])) {
5211 $body = $data["title"];
5213 if (isset($data["url"])) {
5214 $body .= "\n".$data["url"];
5216 $body .= $data["after"];
5223 * @param array $contacts
5227 function api_best_nickname(&$contacts)
5231 if (count($contact) == 0) {
5235 foreach ($contacts as $contact) {
5236 if ($contact["network"] == "") {
5237 $contact["network"] = "dfrn";
5238 $best_contact = [$contact];
5242 if (sizeof($best_contact) == 0) {
5243 foreach ($contacts as $contact) {
5244 if ($contact["network"] == "dfrn") {
5245 $best_contact = [$contact];
5250 if (sizeof($best_contact) == 0) {
5251 foreach ($contacts as $contact) {
5252 if ($contact["network"] == "dspr") {
5253 $best_contact = [$contact];
5258 if (sizeof($best_contact) == 0) {
5259 foreach ($contacts as $contact) {
5260 if ($contact["network"] == "stat") {
5261 $best_contact = [$contact];
5266 if (sizeof($best_contact) == 0) {
5267 foreach ($contacts as $contact) {
5268 if ($contact["network"] == "pump") {
5269 $best_contact = [$contact];
5274 if (sizeof($best_contact) == 0) {
5275 foreach ($contacts as $contact) {
5276 if ($contact["network"] == "twit") {
5277 $best_contact = [$contact];
5282 if (sizeof($best_contact) == 1) {
5283 $contacts = $best_contact;
5285 $contacts = [$contacts[0]];
5290 * Return all or a specified group of the user with the containing contacts.
5292 * @param string $type Return type (atom, rss, xml, json)
5294 * @return array|string
5296 function api_friendica_group_show($type)
5300 if (api_user() === false) {
5301 throw new ForbiddenException();
5305 $user_info = api_get_user($a);
5306 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5307 $uid = $user_info['uid'];
5309 // get data of the specified group id or all groups if not specified
5312 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5316 // error message if specified gid is not in database
5317 if (!DBM::is_result($r)) {
5318 throw new BadRequestException("gid not available");
5322 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5327 // loop through all groups and retrieve all members for adding data in the user array
5328 foreach ($r as $rr) {
5329 $members = Contact::getByGroupId($rr['id']);
5332 if ($type == "xml") {
5333 $user_element = "users";
5335 foreach ($members as $member) {
5336 $user = api_get_user($a, $member['nurl']);
5337 $users[$k++.":user"] = $user;
5340 $user_element = "user";
5341 foreach ($members as $member) {
5342 $user = api_get_user($a, $member['nurl']);
5346 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5348 return api_format_data("groups", $type, ['group' => $grps]);
5350 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5354 * Delete the specified group of the user.
5356 * @param string $type Return type (atom, rss, xml, json)
5358 * @return array|string
5360 function api_friendica_group_delete($type)
5364 if (api_user() === false) {
5365 throw new ForbiddenException();
5369 $user_info = api_get_user($a);
5370 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5371 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5372 $uid = $user_info['uid'];
5374 // error if no gid specified
5375 if ($gid == 0 || $name == "") {
5376 throw new BadRequestException('gid or name not specified');
5379 // get data of the specified group id
5381 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5385 // error message if specified gid is not in database
5386 if (!DBM::is_result($r)) {
5387 throw new BadRequestException('gid not available');
5390 // get data of the specified group id and group name
5392 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5397 // error message if specified gid is not in database
5398 if (!DBM::is_result($rname)) {
5399 throw new BadRequestException('wrong group name');
5403 $ret = Group::removeByName($uid, $name);
5406 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5407 return api_format_data("group_delete", $type, ['result' => $success]);
5409 throw new BadRequestException('other API error');
5412 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5416 * Create the specified group with the posted array of contacts.
5418 * @param string $type Return type (atom, rss, xml, json)
5420 * @return array|string
5422 function api_friendica_group_create($type)
5426 if (api_user() === false) {
5427 throw new ForbiddenException();
5431 $user_info = api_get_user($a);
5432 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5433 $uid = $user_info['uid'];
5434 $json = json_decode($_POST['json'], true);
5435 $users = $json['user'];
5437 // error if no name specified
5439 throw new BadRequestException('group name not specified');
5442 // get data of the specified group name
5444 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5448 // error message if specified group name already exists
5449 if (DBM::is_result($rname)) {
5450 throw new BadRequestException('group name already exists');
5453 // check if specified group name is a deleted group
5455 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5459 // error message if specified group name already exists
5460 if (DBM::is_result($rname)) {
5461 $reactivate_group = true;
5465 $ret = Group::create($uid, $name);
5467 $gid = Group::getIdByName($uid, $name);
5469 throw new BadRequestException('other API error');
5473 $erroraddinguser = false;
5475 foreach ($users as $user) {
5476 $cid = $user['cid'];
5477 // check if user really exists as contact
5479 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5483 if (count($contact)) {
5484 Group::addMember($gid, $cid);
5486 $erroraddinguser = true;
5487 $errorusers[] = $cid;
5491 // return success message incl. missing users in array
5492 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
5493 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5494 return api_format_data("group_create", $type, ['result' => $success]);
5496 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5500 * Update the specified group with the posted array of contacts.
5502 * @param string $type Return type (atom, rss, xml, json)
5504 * @return array|string
5506 function api_friendica_group_update($type)
5510 if (api_user() === false) {
5511 throw new ForbiddenException();
5515 $user_info = api_get_user($a);
5516 $uid = $user_info['uid'];
5517 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5518 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5519 $json = json_decode($_POST['json'], true);
5520 $users = $json['user'];
5522 // error if no name specified
5524 throw new BadRequestException('group name not specified');
5527 // error if no gid specified
5529 throw new BadRequestException('gid not specified');
5533 $members = Contact::getByGroupId($gid);
5534 foreach ($members as $member) {
5535 $cid = $member['id'];
5536 foreach ($users as $user) {
5537 $found = ($user['cid'] == $cid ? true : false);
5540 Group::removeMemberByName($uid, $name, $cid);
5545 $erroraddinguser = false;
5547 foreach ($users as $user) {
5548 $cid = $user['cid'];
5549 // check if user really exists as contact
5551 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5556 if (count($contact)) {
5557 Group::addMember($gid, $cid);
5559 $erroraddinguser = true;
5560 $errorusers[] = $cid;
5564 // return success message incl. missing users in array
5565 $status = ($erroraddinguser ? "missing user" : "ok");
5566 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5567 return api_format_data("group_update", $type, ['result' => $success]);
5570 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5574 * @param string $type Return type (atom, rss, xml, json)
5576 * @return array|string
5578 function api_friendica_activity($type)
5582 if (api_user() === false) {
5583 throw new ForbiddenException();
5585 $verb = strtolower($a->argv[3]);
5586 $verb = preg_replace("|\..*$|", "", $verb);
5588 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5590 $res = do_like($id, $verb);
5593 if ($type == "xml") {
5598 return api_format_data('ok', $type, ['ok' => $ok]);
5600 throw new BadRequestException('Error adding activity');
5604 /// @TODO move to top of file or somewhere better
5605 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5606 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5607 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5608 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5609 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5610 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5611 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5612 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5613 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5614 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5617 * @brief Returns notifications
5619 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5622 function api_friendica_notification($type)
5626 if (api_user() === false) {
5627 throw new ForbiddenException();
5630 throw new BadRequestException("Invalid argument count");
5632 $nm = new NotificationsManager();
5634 $notes = $nm->getAll([], "+seen -date", 50);
5636 if ($type == "xml") {
5638 foreach ($notes as $note) {
5639 $xmlnotes[] = ["@attributes" => $note];
5645 return api_format_data("notes", $type, ['note' => $notes]);
5649 * POST request with 'id' param as notification id
5651 * @brief Set notification as seen and returns associated item (if possible)
5653 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5656 function api_friendica_notification_seen($type)
5660 if (api_user() === false) {
5661 throw new ForbiddenException();
5664 throw new BadRequestException("Invalid argument count");
5667 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5669 $nm = new NotificationsManager();
5670 $note = $nm->getByID($id);
5671 if (is_null($note)) {
5672 throw new BadRequestException("Invalid argument");
5675 $nm->setSeen($note);
5676 if ($note['otype']=='item') {
5677 // would be really better with an ItemsManager and $im->getByID() :-P
5679 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5680 intval($note['iid']),
5681 intval(local_user())
5684 // we found the item, return it to the user
5685 $user_info = api_get_user($a);
5686 $ret = api_format_items($r, $user_info, false, $type);
5687 $data = ['status' => $ret];
5688 return api_format_data("status", $type, $data);
5690 // the item can't be found, but we set the note as seen, so we count this as a success
5692 return api_format_data('result', $type, ['result' => "success"]);
5695 /// @TODO move to top of file or somewhere better
5696 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5697 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5700 * @brief update a direct_message to seen state
5702 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5703 * @return string (success result=ok, error result=error with error message)
5705 function api_friendica_direct_messages_setseen($type)
5708 if (api_user() === false) {
5709 throw new ForbiddenException();
5713 $user_info = api_get_user($a);
5714 $uid = $user_info['uid'];
5715 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5717 // return error if id is zero
5719 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5720 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5723 // get data of the specified message id
5725 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5730 // error message if specified id is not in database
5731 if (!DBM::is_result($r)) {
5732 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5733 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5736 // update seen indicator
5738 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5745 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5746 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5748 $answer = ['result' => 'error', 'message' => 'unknown error'];
5749 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5753 /// @TODO move to top of file or somewhere better
5754 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5757 * @brief search for direct_messages containing a searchstring through api
5759 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5760 * @return string (success: success=true if found and search_result contains found messages,
5761 * success=false if nothing was found, search_result='nothing found',
5762 * error: result=error with error message)
5764 function api_friendica_direct_messages_search($type)
5768 if (api_user() === false) {
5769 throw new ForbiddenException();
5773 $user_info = api_get_user($a);
5774 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5775 $uid = $user_info['uid'];
5777 // error if no searchstring specified
5778 if ($searchstring == "") {
5779 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5780 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5783 // get data for the specified searchstring
5785 "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",
5787 dbesc('%'.$searchstring.'%')
5790 $profile_url = $user_info["url"];
5792 // message if nothing was found
5793 if (!DBM::is_result($r)) {
5794 $success = ['success' => false, 'search_results' => 'problem with query'];
5795 } elseif (count($r) == 0) {
5796 $success = ['success' => false, 'search_results' => 'nothing found'];
5799 foreach ($r as $item) {
5800 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5801 $recipient = $user_info;
5802 $sender = api_get_user($a, normalise_link($item['contact-url']));
5803 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5804 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5805 $sender = $user_info;
5808 $ret[] = api_format_messages($item, $recipient, $sender);
5810 $success = ['success' => true, 'search_results' => $ret];
5813 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5816 /// @TODO move to top of file or somewhere better
5817 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5820 * @brief return data of all the profiles a user has to the client
5822 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5825 function api_friendica_profile_show($type)
5829 if (api_user() === false) {
5830 throw new ForbiddenException();
5834 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5836 // retrieve general information about profiles for user
5837 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5838 $directory = Config::get('system', 'directory');
5840 // get data of the specified profile id or all profiles of the user if not specified
5841 if ($profileid != 0) {
5843 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5848 // error message if specified gid is not in database
5849 if (!DBM::is_result($r)) {
5850 throw new BadRequestException("profile_id not available");
5854 "SELECT * FROM `profile` WHERE `uid` = %d",
5858 // loop through all returned profiles and retrieve data and users
5860 foreach ($r as $rr) {
5861 $profile = api_format_items_profiles($rr);
5863 // select all users from contact table, loop and prepare standard return for user data
5866 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5868 intval($rr['profile_id'])
5871 foreach ($r as $rr) {
5872 $user = api_get_user($a, $rr['nurl']);
5873 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5875 $profile['users'] = $users;
5877 // add prepared profile data to array for final return
5878 if ($type == "xml") {
5879 $profiles[$k++ . ":profile"] = $profile;
5881 $profiles[] = $profile;
5885 // return settings, authenticated user and profiles data
5886 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5888 $result = ['multi_profiles' => $multi_profiles ? true : false,
5889 'global_dir' => $directory,
5890 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5891 'profiles' => $profiles];
5892 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5894 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5897 * Returns a list of saved searches.
5899 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5901 * @param string $type Return format: json or xml
5903 * @return string|array
5905 function api_saved_searches_list($type)
5907 $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
5910 while ($term = $terms->fetch()) {
5912 'name' => $term['term'],
5913 'query' => $term['term'],
5914 'id_str' => $term['id'],
5915 'id' => intval($term['id'])
5921 return api_format_data("terms", $type, ['terms' => $result]);
5924 /// @TODO move to top of file or somewhere better
5925 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5928 @TODO Maybe open to implement?
5930 [pagename] => api/1.1/statuses/lookup.json
5931 [id] => 605138389168451584
5932 [include_cards] => true
5933 [cards_platform] => Android-12
5934 [include_entities] => true
5935 [include_my_retweet] => 1
5937 [include_reply_count] => true
5938 [include_descendent_reply_count] => true
5942 Not implemented by now:
5943 statuses/retweets_of_me
5948 account/update_location
5949 account/update_profile_background_image
5952 friendica/profile/update
5953 friendica/profile/create
5954 friendica/profile/delete
5956 Not implemented in status.net:
5957 statuses/retweeted_to_me
5958 statuses/retweeted_by_me
5959 direct_messages/destroy
5961 account/update_delivery_device
5962 notifications/follow