3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\Content\ContactSelector;
11 use Friendica\Content\Feature;
12 use Friendica\Content\Text\BBCode;
13 use Friendica\Core\Addon;
14 use Friendica\Core\Config;
15 use Friendica\Core\L10n;
16 use Friendica\Core\NotificationsManager;
17 use Friendica\Core\PConfig;
18 use Friendica\Core\System;
19 use Friendica\Core\Worker;
20 use Friendica\Database\DBM;
21 use Friendica\Model\Contact;
22 use Friendica\Model\Group;
23 use Friendica\Model\Item;
24 use Friendica\Model\Mail;
25 use Friendica\Model\Photo;
26 use Friendica\Model\User;
27 use Friendica\Network\FKOAuth1;
28 use Friendica\Network\HTTPException;
29 use Friendica\Network\HTTPException\BadRequestException;
30 use Friendica\Network\HTTPException\ForbiddenException;
31 use Friendica\Network\HTTPException\InternalServerErrorException;
32 use Friendica\Network\HTTPException\MethodNotAllowedException;
33 use Friendica\Network\HTTPException\NotFoundException;
34 use Friendica\Network\HTTPException\NotImplementedException;
35 use Friendica\Network\HTTPException\TooManyRequestsException;
36 use Friendica\Network\HTTPException\UnauthorizedException;
37 use Friendica\Object\Image;
38 use Friendica\Protocol\Diaspora;
39 use Friendica\Util\DateTimeFormat;
40 use Friendica\Util\Network;
41 use Friendica\Util\XML;
43 require_once 'include/bbcode.php';
44 require_once 'include/conversation.php';
45 require_once 'include/html2plain.php';
46 require_once 'mod/share.php';
47 require_once 'mod/item.php';
48 require_once 'include/security.php';
49 require_once 'include/html2bbcode.php';
50 require_once 'mod/wall_upload.php';
51 require_once 'mod/proxy.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 DateTimeFormat::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' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
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(DateTimeFormat::MYSQL, 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(DateTimeFormat::MYSQL, 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(DateTimeFormat::MYSQL, 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);
2221 Item::deleteById($id);
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 Item::update(['starred' => $item[0]['starred']], ['id' => $itemid]);
2465 throw new InternalServerErrorException("DB error");
2469 $user_info = api_get_user($a);
2470 $rets = api_format_items($item, $user_info, false, $type);
2473 $data = ['status' => $ret];
2477 $data = api_rss_extra($a, $data, $user_info);
2480 return api_format_data("status", $type, $data);
2483 /// @TODO move to top of file or somewhere better
2484 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2485 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2488 * Returns the most recent favorite statuses.
2490 * @param string $type Return type (atom, rss, xml, json)
2492 * @return string|array
2494 function api_favorites($type)
2500 if (api_user() === false) {
2501 throw new ForbiddenException();
2506 $user_info = api_get_user($a);
2508 // in friendica starred item are private
2509 // return favorites only for self
2510 logger('api_favorites: self:' . $user_info['self']);
2512 if ($user_info['self'] == 0) {
2518 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2519 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2520 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2521 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2526 $start = $page*$count;
2529 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2533 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2534 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2535 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2536 `contact`.`id` AS `cid`
2537 FROM `item`, `contact`
2538 WHERE `item`.`uid` = %d
2539 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2540 AND `item`.`starred` = 1
2541 AND `contact`.`id` = `item`.`contact-id`
2542 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2545 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2552 $ret = api_format_items($r, $user_info, false, $type);
2555 $data = ['status' => $ret];
2559 $data = api_rss_extra($a, $data, $user_info);
2562 return api_format_data("statuses", $type, $data);
2565 /// @TODO move to top of file or somewhere better
2566 api_register_func('api/favorites', 'api_favorites', true);
2570 * @param array $item
2571 * @param array $recipient
2572 * @param array $sender
2576 function api_format_messages($item, $recipient, $sender)
2578 // standard meta information
2580 'id' => $item['id'],
2581 'sender_id' => $sender['id'] ,
2583 'recipient_id' => $recipient['id'],
2584 'created_at' => api_date($item['created']),
2585 'sender_screen_name' => $sender['screen_name'],
2586 'recipient_screen_name' => $recipient['screen_name'],
2587 'sender' => $sender,
2588 'recipient' => $recipient,
2590 'friendica_seen' => $item['seen'],
2591 'friendica_parent_uri' => $item['parent-uri'],
2594 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2595 unset($ret["sender"]["uid"]);
2596 unset($ret["sender"]["self"]);
2597 unset($ret["recipient"]["uid"]);
2598 unset($ret["recipient"]["self"]);
2600 //don't send title to regular StatusNET requests to avoid confusing these apps
2601 if (x($_GET, 'getText')) {
2602 $ret['title'] = $item['title'];
2603 if ($_GET['getText'] == 'html') {
2604 $ret['text'] = bbcode($item['body'], false, false);
2605 } elseif ($_GET['getText'] == 'plain') {
2606 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2607 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2610 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2612 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2613 unset($ret['sender']);
2614 unset($ret['recipient']);
2622 * @param array $item
2626 function api_convert_item($item)
2628 $body = $item['body'];
2629 $attachments = api_get_attachments($body);
2631 // Workaround for ostatus messages where the title is identically to the body
2632 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2633 $statusbody = trim(html2plain($html, 0));
2635 // handle data: images
2636 $statusbody = api_format_items_embeded_images($item, $statusbody);
2638 $statustitle = trim($item['title']);
2640 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2641 $statustext = trim($statusbody);
2643 $statustext = trim($statustitle."\n\n".$statusbody);
2646 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2647 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2650 $statushtml = trim(bbcode($body, false, false));
2652 // Workaround for clients with limited HTML parser functionality
2653 $search = ["<br>", "<blockquote>", "</blockquote>",
2654 "<h1>", "</h1>", "<h2>", "</h2>",
2655 "<h3>", "</h3>", "<h4>", "</h4>",
2656 "<h5>", "</h5>", "<h6>", "</h6>"];
2657 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2658 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2659 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2660 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2661 $statushtml = str_replace($search, $replace, $statushtml);
2663 if ($item['title'] != "") {
2664 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2668 $oldtext = $statushtml;
2669 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2670 } while ($oldtext != $statushtml);
2672 if (substr($statushtml, 0, 4) == '<br>') {
2673 $statushtml = substr($statushtml, 4);
2676 if (substr($statushtml, 0, -4) == '<br>') {
2677 $statushtml = substr($statushtml, -4);
2680 // feeds without body should contain the link
2681 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2682 $statushtml .= bbcode($item['plink']);
2685 $entities = api_get_entitities($statustext, $body);
2688 "text" => $statustext,
2689 "html" => $statushtml,
2690 "attachments" => $attachments,
2691 "entities" => $entities
2697 * @param string $body
2699 * @return array|false
2701 function api_get_attachments(&$body)
2704 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2706 $URLSearchString = "^\[\]";
2707 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2715 foreach ($images[1] as $image) {
2716 $imagedata = Image::getInfoFromURL($image);
2719 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2723 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2724 foreach ($images[0] as $orig) {
2725 $body = str_replace($orig, "", $body);
2729 return $attachments;
2734 * @param string $text
2735 * @param string $bbcode
2738 * @todo Links at the first character of the post
2740 function api_get_entitities(&$text, $bbcode)
2742 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2744 if ($include_entities != "true") {
2745 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2747 foreach ($images[1] as $image) {
2748 $replace = proxy_url($image);
2749 $text = str_replace($image, $replace, $text);
2754 $bbcode = BBCode::cleanPictureLinks($bbcode);
2756 // Change pure links in text to bbcode uris
2757 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2760 $entities["hashtags"] = [];
2761 $entities["symbols"] = [];
2762 $entities["urls"] = [];
2763 $entities["user_mentions"] = [];
2765 $URLSearchString = "^\[\]";
2767 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2769 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2770 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2771 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2773 $bbcode = preg_replace(
2774 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2775 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2778 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2780 $bbcode = preg_replace(
2781 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2782 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2785 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2787 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2789 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2790 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2793 foreach ($urls[1] as $id => $url) {
2794 //$start = strpos($text, $url, $offset);
2795 $start = iconv_strpos($text, $url, 0, "UTF-8");
2796 if (!($start === false)) {
2797 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2801 ksort($ordered_urls);
2804 //foreach ($urls[1] AS $id=>$url) {
2805 foreach ($ordered_urls as $url) {
2806 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2807 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2809 $display_url = $url["title"];
2811 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2812 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2814 if (strlen($display_url) > 26) {
2815 $display_url = substr($display_url, 0, 25)."…";
2819 //$start = strpos($text, $url, $offset);
2820 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2821 if (!($start === false)) {
2822 $entities["urls"][] = ["url" => $url["url"],
2823 "expanded_url" => $url["url"],
2824 "display_url" => $display_url,
2825 "indices" => [$start, $start+strlen($url["url"])]];
2826 $offset = $start + 1;
2830 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2831 $ordered_images = [];
2832 foreach ($images[1] as $image) {
2833 //$start = strpos($text, $url, $offset);
2834 $start = iconv_strpos($text, $image, 0, "UTF-8");
2835 if (!($start === false)) {
2836 $ordered_images[$start] = $image;
2839 //$entities["media"] = array();
2842 foreach ($ordered_images as $url) {
2843 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2844 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2846 if (strlen($display_url) > 26) {
2847 $display_url = substr($display_url, 0, 25)."…";
2850 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2851 if (!($start === false)) {
2852 $image = Image::getInfoFromURL($url);
2854 // If image cache is activated, then use the following sizes:
2855 // thumb (150), small (340), medium (600) and large (1024)
2856 if (!Config::get("system", "proxy_disabled")) {
2857 $media_url = proxy_url($url);
2860 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2861 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2863 if (($image[0] > 150) || ($image[1] > 150)) {
2864 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2865 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2868 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2869 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2871 if (($image[0] > 600) || ($image[1] > 600)) {
2872 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2873 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2877 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2880 $entities["media"][] = [
2882 "id_str" => (string)$start+1,
2883 "indices" => [$start, $start+strlen($url)],
2884 "media_url" => normalise_link($media_url),
2885 "media_url_https" => $media_url,
2887 "display_url" => $display_url,
2888 "expanded_url" => $url,
2892 $offset = $start + 1;
2901 * @param array $item
2902 * @param string $text
2906 function api_format_items_embeded_images($item, $text)
2908 $text = preg_replace_callback(
2909 '|data:image/([^;]+)[^=]+=*|m',
2910 function () use ($item) {
2911 return System::baseUrl() . '/display/' . $item['guid'];
2919 * @brief return <a href='url'>name</a> as array
2921 * @param string $txt text
2926 function api_contactlink_to_array($txt)
2929 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2930 if ($r && count($match)==3) {
2932 'name' => $match[2],
2946 * @brief return likes, dislikes and attend status for item
2948 * @param array $item array
2949 * @param string $type Return type (atom, rss, xml, json)
2952 * likes => int count,
2953 * dislikes => int count
2955 function api_format_items_activities(&$item, $type = "json")
2964 'attendmaybe' => [],
2969 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2970 intval($item['uid']),
2974 foreach ($items as $i) {
2975 // not used as result should be structured like other user data
2976 //builtin_activity_puller($i, $activities);
2978 // get user data and add it to the array of the activity
2979 $user = api_get_user($a, $i['author-link']);
2980 switch ($i['verb']) {
2982 $activities['like'][] = $user;
2984 case ACTIVITY_DISLIKE:
2985 $activities['dislike'][] = $user;
2987 case ACTIVITY_ATTEND:
2988 $activities['attendyes'][] = $user;
2990 case ACTIVITY_ATTENDNO:
2991 $activities['attendno'][] = $user;
2993 case ACTIVITY_ATTENDMAYBE:
2994 $activities['attendmaybe'][] = $user;
3001 if ($type == "xml") {
3002 $xml_activities = [];
3003 foreach ($activities as $k => $v) {
3004 // change xml element from "like" to "friendica:like"
3005 $xml_activities["friendica:".$k] = $v;
3006 // add user data into xml output
3008 foreach ($v as $user) {
3009 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
3012 $activities = $xml_activities;
3020 * @brief return data from profiles
3022 * @param array $profile_row array containing data from db table 'profile'
3025 function api_format_items_profiles($profile_row)
3028 'profile_id' => $profile_row['id'],
3029 'profile_name' => $profile_row['profile-name'],
3030 'is_default' => $profile_row['is-default'] ? true : false,
3031 'hide_friends' => $profile_row['hide-friends'] ? true : false,
3032 'profile_photo' => $profile_row['photo'],
3033 'profile_thumb' => $profile_row['thumb'],
3034 'publish' => $profile_row['publish'] ? true : false,
3035 'net_publish' => $profile_row['net-publish'] ? true : false,
3036 'description' => $profile_row['pdesc'],
3037 'date_of_birth' => $profile_row['dob'],
3038 'address' => $profile_row['address'],
3039 'city' => $profile_row['locality'],
3040 'region' => $profile_row['region'],
3041 'postal_code' => $profile_row['postal-code'],
3042 'country' => $profile_row['country-name'],
3043 'hometown' => $profile_row['hometown'],
3044 'gender' => $profile_row['gender'],
3045 'marital' => $profile_row['marital'],
3046 'marital_with' => $profile_row['with'],
3047 'marital_since' => $profile_row['howlong'],
3048 'sexual' => $profile_row['sexual'],
3049 'politic' => $profile_row['politic'],
3050 'religion' => $profile_row['religion'],
3051 'public_keywords' => $profile_row['pub_keywords'],
3052 'private_keywords' => $profile_row['prv_keywords'],
3053 'likes' => bbcode(api_clean_plain_items($profile_row['likes']) , false, false, 2, false),
3054 'dislikes' => bbcode(api_clean_plain_items($profile_row['dislikes']) , false, false, 2, false),
3055 'about' => bbcode(api_clean_plain_items($profile_row['about']) , false, false, 2, false),
3056 'music' => bbcode(api_clean_plain_items($profile_row['music']) , false, false, 2, false),
3057 'book' => bbcode(api_clean_plain_items($profile_row['book']) , false, false, 2, false),
3058 'tv' => bbcode(api_clean_plain_items($profile_row['tv']) , false, false, 2, false),
3059 'film' => bbcode(api_clean_plain_items($profile_row['film']) , false, false, 2, false),
3060 'interest' => bbcode(api_clean_plain_items($profile_row['interest']) , false, false, 2, false),
3061 'romance' => bbcode(api_clean_plain_items($profile_row['romance']) , false, false, 2, false),
3062 'work' => bbcode(api_clean_plain_items($profile_row['work']) , false, false, 2, false),
3063 'education' => bbcode(api_clean_plain_items($profile_row['education']), false, false, 2, false),
3064 'social_networks' => bbcode(api_clean_plain_items($profile_row['contact']) , false, false, 2, false),
3065 'homepage' => $profile_row['homepage'],
3072 * @brief format items to be returned by api
3074 * @param array $r array of items
3075 * @param array $user_info
3076 * @param bool $filter_user filter items by $user_info
3077 * @param string $type Return type (atom, rss, xml, json)
3079 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
3085 foreach ($r as $item) {
3086 localize_item($item);
3087 list($status_user, $owner_user) = api_item_get_user($a, $item);
3089 // Look if the posts are matching if they should be filtered by user id
3090 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3094 $in_reply_to = api_in_reply_to($item);
3096 $converted = api_convert_item($item);
3098 if ($type == "xml") {
3099 $geo = "georss:point";
3105 'text' => $converted["text"],
3106 'truncated' => false,
3107 'created_at'=> api_date($item['created']),
3108 'in_reply_to_status_id' => $in_reply_to['status_id'],
3109 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3110 'source' => (($item['app']) ? $item['app'] : 'web'),
3111 'id' => intval($item['id']),
3112 'id_str' => (string) intval($item['id']),
3113 'in_reply_to_user_id' => $in_reply_to['user_id'],
3114 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3115 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3117 'favorited' => $item['starred'] ? true : false,
3118 'user' => $status_user ,
3119 'friendica_owner' => $owner_user,
3120 //'entities' => NULL,
3121 'statusnet_html' => $converted["html"],
3122 'statusnet_conversation_id' => $item['parent'],
3123 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3124 'friendica_activities' => api_format_items_activities($item, $type),
3127 if (count($converted["attachments"]) > 0) {
3128 $status["attachments"] = $converted["attachments"];
3131 if (count($converted["entities"]) > 0) {
3132 $status["entities"] = $converted["entities"];
3135 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
3136 $status["source"] = ContactSelector::networkToName($item['item_network'], $user_info['url']);
3137 } elseif (($item['item_network'] != "") && (ContactSelector::networkToName($item['item_network'], $user_info['url']) != $status["source"])) {
3138 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['item_network'], $user_info['url']).')');
3142 // Retweets are only valid for top postings
3143 // It doesn't work reliable with the link if its a feed
3144 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
3146 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
3149 if ($item["id"] == $item["parent"]) {
3150 $retweeted_item = api_share_as_retweet($item);
3151 if ($retweeted_item !== false) {
3152 $retweeted_status = $status;
3154 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
3155 } catch (BadRequestException $e) {
3156 // user not found. should be found?
3157 /// @todo check if the user should be always found
3158 $retweeted_status["user"] = [];
3161 $rt_converted = api_convert_item($retweeted_item);
3163 $retweeted_status['text'] = $rt_converted["text"];
3164 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3165 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3166 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3167 $status['retweeted_status'] = $retweeted_status;
3171 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3172 unset($status["user"]["uid"]);
3173 unset($status["user"]["self"]);
3175 if ($item["coord"] != "") {
3176 $coords = explode(' ', $item["coord"]);
3177 if (count($coords) == 2) {
3178 if ($type == "json") {
3179 $status["geo"] = ['type' => 'Point',
3180 'coordinates' => [(float) $coords[0],
3181 (float) $coords[1]]];
3182 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3183 $status["georss:point"] = $item["coord"];
3193 * Returns the remaining number of API requests available to the user before the API limit is reached.
3195 * @param string $type Return type (atom, rss, xml, json)
3197 * @return array|string
3199 function api_account_rate_limit_status($type)
3201 if ($type == "xml") {
3203 'remaining-hits' => '150',
3204 '@attributes' => ["type" => "integer"],
3205 'hourly-limit' => '150',
3206 '@attributes2' => ["type" => "integer"],
3207 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3208 '@attributes3' => ["type" => "datetime"],
3209 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3210 '@attributes4' => ["type" => "integer"],
3214 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3215 'remaining_hits' => '150',
3216 'hourly_limit' => '150',
3217 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3221 return api_format_data('hash', $type, ['hash' => $hash]);
3224 /// @TODO move to top of file or somewhere better
3225 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3228 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3230 * @param string $type Return type (atom, rss, xml, json)
3232 * @return array|string
3234 function api_help_test($type)
3236 if ($type == 'xml') {
3242 return api_format_data('ok', $type, ["ok" => $ok]);
3245 /// @TODO move to top of file or somewhere better
3246 api_register_func('api/help/test', 'api_help_test', false);
3250 * @param string $type Return type (atom, rss, xml, json)
3252 * @return array|string
3254 function api_lists($type)
3257 /// @TODO $ret is not filled here?
3258 return api_format_data('lists', $type, ["lists_list" => $ret]);
3261 /// @TODO move to top of file or somewhere better
3262 api_register_func('api/lists', 'api_lists', true);
3265 * Returns all lists the user subscribes to.
3267 * @param string $type Return type (atom, rss, xml, json)
3269 * @return array|string
3270 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3272 function api_lists_list($type)
3275 /// @TODO $ret is not filled here?
3276 return api_format_data('lists', $type, ["lists_list" => $ret]);
3279 /// @TODO move to top of file or somewhere better
3280 api_register_func('api/lists/list', 'api_lists_list', true);
3283 * Considers friends and followers lists to be private and won't return
3284 * anything if any user_id parameter is passed.
3286 * @brief Returns either the friends of the follower list
3288 * @param string $qtype Either "friends" or "followers"
3289 * @return boolean|array
3290 * @throws ForbiddenException
3292 function api_statuses_f($qtype)
3296 if (api_user() === false) {
3297 throw new ForbiddenException();
3301 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3302 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3306 $start = ($page - 1) * $count;
3308 $user_info = api_get_user($a);
3310 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3311 /* this is to stop Hotot to load friends multiple times
3312 * I'm not sure if I'm missing return something or
3313 * is a bug in hotot. Workaround, meantime
3317 return array('$users' => $ret);*/
3322 if ($qtype == 'friends') {
3323 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3324 } elseif ($qtype == 'followers') {
3325 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3328 // friends and followers only for self
3329 if ($user_info['self'] == 0) {
3330 $sql_extra = " AND false ";
3333 if ($qtype == 'blocks') {
3334 $sql_filter = 'AND `blocked` AND NOT `pending`';
3335 } elseif ($qtype == 'incoming') {
3336 $sql_filter = 'AND `pending`';
3338 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3356 foreach ($r as $cid) {
3357 $user = api_get_user($a, $cid['nurl']);
3358 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3359 unset($user["uid"]);
3360 unset($user["self"]);
3367 return ['user' => $ret];
3372 * Returns the user's friends.
3374 * @brief Returns the list of friends of the provided user
3376 * @deprecated By Twitter API in favor of friends/list
3378 * @param string $type Either "json" or "xml"
3379 * @return boolean|string|array
3381 function api_statuses_friends($type)
3383 $data = api_statuses_f("friends");
3384 if ($data === false) {
3387 return api_format_data("users", $type, $data);
3391 * Returns the user's followers.
3393 * @brief Returns the list of followers of the provided user
3395 * @deprecated By Twitter API in favor of friends/list
3397 * @param string $type Either "json" or "xml"
3398 * @return boolean|string|array
3400 function api_statuses_followers($type)
3402 $data = api_statuses_f("followers");
3403 if ($data === false) {
3406 return api_format_data("users", $type, $data);
3409 /// @TODO move to top of file or somewhere better
3410 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3411 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3414 * Returns the list of blocked users
3416 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3418 * @param string $type Either "json" or "xml"
3420 * @return boolean|string|array
3422 function api_blocks_list($type)
3424 $data = api_statuses_f('blocks');
3425 if ($data === false) {
3428 return api_format_data("users", $type, $data);
3431 /// @TODO move to top of file or somewhere better
3432 api_register_func('api/blocks/list', 'api_blocks_list', true);
3435 * Returns the list of pending users IDs
3437 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3439 * @param string $type Either "json" or "xml"
3441 * @return boolean|string|array
3443 function api_friendships_incoming($type)
3445 $data = api_statuses_f('incoming');
3446 if ($data === false) {
3451 foreach ($data['user'] as $user) {
3452 $ids[] = $user['id'];
3455 return api_format_data("ids", $type, ['id' => $ids]);
3458 /// @TODO move to top of file or somewhere better
3459 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3462 * Returns the instance's configuration information.
3464 * @param string $type Return type (atom, rss, xml, json)
3466 * @return array|string
3468 function api_statusnet_config($type)
3472 $name = $a->config['sitename'];
3473 $server = $a->get_hostname();
3474 $logo = System::baseUrl() . '/images/friendica-64.png';
3475 $email = $a->config['admin_email'];
3476 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3477 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3478 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3479 if ($a->config['api_import_size']) {
3480 $textlimit = (string) $a->config['api_import_size'];
3482 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3483 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3486 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3487 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3488 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3489 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3490 'shorturllength' => '30',
3492 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3493 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3494 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3495 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3500 return api_format_data('config', $type, ['config' => $config]);
3503 /// @TODO move to top of file or somewhere better
3504 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3505 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3509 * @param string $type Return type (atom, rss, xml, json)
3511 * @return array|string
3513 function api_statusnet_version($type)
3516 $fake_statusnet_version = "0.9.7";
3518 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3521 /// @TODO move to top of file or somewhere better
3522 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3523 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3527 * @param string $type Return type (atom, rss, xml, json)
3529 * @todo use api_format_data() to return data
3531 function api_ff_ids($type)
3534 throw new ForbiddenException();
3539 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3542 "SELECT `pcontact`.`id` FROM `contact`
3543 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3544 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3547 if (!DBM::is_result($r)) {
3552 foreach ($r as $rr) {
3553 if ($stringify_ids) {
3556 $ids[] = intval($rr['id']);
3560 return api_format_data("ids", $type, ['id' => $ids]);
3564 * Returns the ID of every user the user is following.
3566 * @param string $type Return type (atom, rss, xml, json)
3568 * @return array|string
3569 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3571 function api_friends_ids($type)
3573 return api_ff_ids($type);
3577 * Returns the ID of every user following the user.
3579 * @param string $type Return type (atom, rss, xml, json)
3581 * @return array|string
3582 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3584 function api_followers_ids($type)
3586 return api_ff_ids($type);
3589 /// @TODO move to top of file or somewhere better
3590 api_register_func('api/friends/ids', 'api_friends_ids', true);
3591 api_register_func('api/followers/ids', 'api_followers_ids', true);
3594 * Sends a new direct message.
3596 * @param string $type Return type (atom, rss, xml, json)
3598 * @return array|string
3599 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3601 function api_direct_messages_new($type)
3606 if (api_user() === false) {
3607 throw new ForbiddenException();
3610 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3614 $sender = api_get_user($a);
3616 if ($_POST['screen_name']) {
3618 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3620 dbesc($_POST['screen_name'])
3623 // Selecting the id by priority, friendica first
3624 api_best_nickname($r);
3626 $recipient = api_get_user($a, $r[0]['nurl']);
3628 $recipient = api_get_user($a, $_POST['user_id']);
3633 if (x($_REQUEST, 'replyto')) {
3635 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3637 intval($_REQUEST['replyto'])
3639 $replyto = $r[0]['parent-uri'];
3640 $sub = $r[0]['title'];
3642 if (x($_REQUEST, 'title')) {
3643 $sub = $_REQUEST['title'];
3645 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3649 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3652 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3653 $ret = api_format_messages($r[0], $recipient, $sender);
3655 $ret = ["error"=>$id];
3658 $data = ['direct_message'=>$ret];
3663 $data = api_rss_extra($a, $data, $user_info);
3666 return api_format_data("direct-messages", $type, $data);
3669 /// @TODO move to top of file or somewhere better
3670 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3673 * Destroys a direct message.
3675 * @brief delete a direct_message from mail table through api
3677 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3679 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3681 function api_direct_messages_destroy($type)
3685 if (api_user() === false) {
3686 throw new ForbiddenException();
3690 $user_info = api_get_user($a);
3692 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3694 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3695 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3696 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3698 $uid = $user_info['uid'];
3699 // error if no id or parenturi specified (for clients posting parent-uri as well)
3700 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3701 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3702 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3705 // BadRequestException if no id specified (for clients using Twitter API)
3707 throw new BadRequestException('Message id not specified');
3710 // add parent-uri to sql command if specified by calling app
3711 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3713 // get data of the specified message id
3715 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3720 // error message if specified id is not in database
3721 if (!DBM::is_result($r)) {
3722 if ($verbose == "true") {
3723 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3724 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3726 /// @todo BadRequestException ok for Twitter API clients?
3727 throw new BadRequestException('message id not in database');
3732 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3737 if ($verbose == "true") {
3740 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3741 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3743 $answer = ['result' => 'error', 'message' => 'unknown error'];
3744 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3747 /// @todo return JSON data like Twitter API not yet implemented
3750 /// @TODO move to top of file or somewhere better
3751 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3755 * @param string $type Return type (atom, rss, xml, json)
3756 * @param string $box
3757 * @param string $verbose
3759 * @return array|string
3761 function api_direct_messages_box($type, $box, $verbose)
3765 if (api_user() === false) {
3766 throw new ForbiddenException();
3770 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3771 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3776 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3777 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3779 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3780 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3783 unset($_REQUEST["user_id"]);
3784 unset($_GET["user_id"]);
3786 unset($_REQUEST["screen_name"]);
3787 unset($_GET["screen_name"]);
3789 $user_info = api_get_user($a);
3790 $profile_url = $user_info["url"];
3793 $start = $page * $count;
3796 if ($box=="sentbox") {
3797 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3798 } elseif ($box == "conversation") {
3799 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3800 } elseif ($box == "all") {
3801 $sql_extra = "true";
3802 } elseif ($box == "inbox") {
3803 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3807 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3810 if ($user_id != "") {
3811 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3812 } elseif ($screen_name !="") {
3813 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3817 "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",
3823 if ($verbose == "true" && !DBM::is_result($r)) {
3824 $answer = ['result' => 'error', 'message' => 'no mails available'];
3825 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3829 foreach ($r as $item) {
3830 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3831 $recipient = $user_info;
3832 $sender = api_get_user($a, normalise_link($item['contact-url']));
3833 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3834 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3835 $sender = $user_info;
3838 $ret[] = api_format_messages($item, $recipient, $sender);
3842 $data = ['direct_message' => $ret];
3846 $data = api_rss_extra($a, $data, $user_info);
3849 return api_format_data("direct-messages", $type, $data);
3853 * Returns the most recent direct messages sent by the user.
3855 * @param string $type Return type (atom, rss, xml, json)
3857 * @return array|string
3858 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3860 function api_direct_messages_sentbox($type)
3862 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3863 return api_direct_messages_box($type, "sentbox", $verbose);
3867 * Returns the most recent direct messages sent to the user.
3869 * @param string $type Return type (atom, rss, xml, json)
3871 * @return array|string
3872 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3874 function api_direct_messages_inbox($type)
3876 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3877 return api_direct_messages_box($type, "inbox", $verbose);
3882 * @param string $type Return type (atom, rss, xml, json)
3884 * @return array|string
3886 function api_direct_messages_all($type)
3888 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3889 return api_direct_messages_box($type, "all", $verbose);
3894 * @param string $type Return type (atom, rss, xml, json)
3896 * @return array|string
3898 function api_direct_messages_conversation($type)
3900 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3901 return api_direct_messages_box($type, "conversation", $verbose);
3904 /// @TODO move to top of file or somewhere better
3905 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3906 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3907 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3908 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3911 * Returns an OAuth Request Token.
3913 * @see https://oauth.net/core/1.0/#auth_step1
3915 function api_oauth_request_token()
3917 $oauth1 = new FKOAuth1();
3919 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3920 } catch (Exception $e) {
3921 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3929 * Returns an OAuth Access Token.
3931 * @return array|string
3932 * @see https://oauth.net/core/1.0/#auth_step3
3934 function api_oauth_access_token()
3936 $oauth1 = new FKOAuth1();
3938 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3939 } catch (Exception $e) {
3940 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3947 /// @TODO move to top of file or somewhere better
3948 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3949 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3953 * @brief delete a complete photoalbum with all containing photos from database through api
3955 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3958 function api_fr_photoalbum_delete($type)
3960 if (api_user() === false) {
3961 throw new ForbiddenException();
3964 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3966 // we do not allow calls without album string
3968 throw new BadRequestException("no albumname specified");
3970 // check if album is existing
3972 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3976 if (!DBM::is_result($r)) {
3977 throw new BadRequestException("album not available");
3980 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3981 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3982 foreach ($r as $rr) {
3984 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3985 intval(local_user()),
3986 dbesc($rr['resource-id'])
3989 if (!DBM::is_result($photo_item)) {
3990 throw new InternalServerErrorException("problem with deleting items occured");
3992 Item::deleteById($photo_item[0]['id']);
3995 // now let's delete all photos from the album
3996 $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
3998 // return success of deletion or error message
4000 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4001 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4003 throw new InternalServerErrorException("unknown error - deleting from database failed");
4008 * @brief update the name of the album for all photos of an album
4010 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4013 function api_fr_photoalbum_update($type)
4015 if (api_user() === false) {
4016 throw new ForbiddenException();
4019 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
4020 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
4022 // we do not allow calls without album string
4024 throw new BadRequestException("no albumname specified");
4026 if ($album_new == "") {
4027 throw new BadRequestException("no new albumname specified");
4029 // check if album is existing
4031 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4035 if (!DBM::is_result($r)) {
4036 throw new BadRequestException("album not available");
4038 // now let's update all photos to the albumname
4040 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
4046 // return success of updating or error message
4048 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4049 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4051 throw new InternalServerErrorException("unknown error - updating in database failed");
4057 * @brief list all photos of the authenticated user
4059 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4062 function api_fr_photos_list($type)
4064 if (api_user() === false) {
4065 throw new ForbiddenException();
4068 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4069 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4070 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4071 intval(local_user())
4074 'image/jpeg' => 'jpg',
4075 'image/png' => 'png',
4076 'image/gif' => 'gif'
4078 $data = ['photo'=>[]];
4079 if (DBM::is_result($r)) {
4080 foreach ($r as $rr) {
4082 $photo['id'] = $rr['resource-id'];
4083 $photo['album'] = $rr['album'];
4084 $photo['filename'] = $rr['filename'];
4085 $photo['type'] = $rr['type'];
4086 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4087 $photo['created'] = $rr['created'];
4088 $photo['edited'] = $rr['edited'];
4089 $photo['desc'] = $rr['desc'];
4091 if ($type == "xml") {
4092 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4094 $photo['thumb'] = $thumb;
4095 $data['photo'][] = $photo;
4099 return api_format_data("photos", $type, $data);
4103 * @brief upload a new photo or change an existing photo
4105 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4108 function api_fr_photo_create_update($type)
4110 if (api_user() === false) {
4111 throw new ForbiddenException();
4114 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4115 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4116 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4117 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4118 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4119 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4120 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4121 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4122 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4124 // do several checks on input parameters
4125 // we do not allow calls without album string
4126 if ($album == null) {
4127 throw new BadRequestException("no albumname specified");
4129 // if photo_id == null --> we are uploading a new photo
4130 if ($photo_id == null) {
4133 // error if no media posted in create-mode
4134 if (!x($_FILES, 'media')) {
4136 throw new BadRequestException("no media data submitted");
4139 // album_new will be ignored in create-mode
4144 // check if photo is existing in database
4146 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4151 if (!DBM::is_result($r)) {
4152 throw new BadRequestException("photo not available");
4156 // checks on acl strings provided by clients
4157 $acl_input_error = false;
4158 $acl_input_error |= check_acl_input($allow_cid);
4159 $acl_input_error |= check_acl_input($deny_cid);
4160 $acl_input_error |= check_acl_input($allow_gid);
4161 $acl_input_error |= check_acl_input($deny_gid);
4162 if ($acl_input_error) {
4163 throw new BadRequestException("acl data invalid");
4165 // now let's upload the new media in create-mode
4166 if ($mode == "create") {
4167 $media = $_FILES['media'];
4168 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4170 // return success of updating or error message
4171 if (!is_null($data)) {
4172 return api_format_data("photo_create", $type, $data);
4174 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4178 // now let's do the changes in update-mode
4179 if ($mode == "update") {
4182 if (!is_null($desc)) {
4183 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4186 if (!is_null($album_new)) {
4187 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4190 if (!is_null($allow_cid)) {
4191 $allow_cid = trim($allow_cid);
4192 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4195 if (!is_null($deny_cid)) {
4196 $deny_cid = trim($deny_cid);
4197 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4200 if (!is_null($allow_gid)) {
4201 $allow_gid = trim($allow_gid);
4202 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4205 if (!is_null($deny_gid)) {
4206 $deny_gid = trim($deny_gid);
4207 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4211 if ($sql_extra != "") {
4212 $nothingtodo = false;
4214 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4216 DateTimeFormat::utcNow(), // update edited timestamp
4222 $nothingtodo = true;
4225 if (x($_FILES, 'media')) {
4226 $nothingtodo = false;
4227 $media = $_FILES['media'];
4228 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4229 if (!is_null($data)) {
4230 return api_format_data("photo_update", $type, $data);
4234 // return success of updating or error message
4236 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4237 return api_format_data("photo_update", $type, ['$result' => $answer]);
4240 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4241 return api_format_data("photo_update", $type, ['$result' => $answer]);
4243 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4246 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4251 * @brief delete a single photo from the database through api
4253 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4256 function api_fr_photo_delete($type)
4258 if (api_user() === false) {
4259 throw new ForbiddenException();
4262 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4264 // do several checks on input parameters
4265 // we do not allow calls without photo id
4266 if ($photo_id == null) {
4267 throw new BadRequestException("no photo_id specified");
4269 // check if photo is existing in database
4271 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4275 if (!DBM::is_result($r)) {
4276 throw new BadRequestException("photo not available");
4278 // now we can perform on the deletion of the photo
4279 $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4281 // return success of deletion or error message
4283 // retrieve the id of the parent element (the photo element)
4285 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4286 intval(local_user()),
4290 if (!DBM::is_result($photo_item)) {
4291 throw new InternalServerErrorException("problem with deleting items occured");
4293 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4294 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4295 Item::deleteById($photo_item[0]['id']);
4297 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4298 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4300 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4306 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4308 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4309 * @return string|array
4311 function api_fr_photo_detail($type)
4313 if (api_user() === false) {
4314 throw new ForbiddenException();
4316 if (!x($_REQUEST, 'photo_id')) {
4317 throw new BadRequestException("No photo id.");
4320 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4321 $photo_id = $_REQUEST['photo_id'];
4323 // prepare json/xml output with data from database for the requested photo
4324 $data = prepare_photo_data($type, $scale, $photo_id);
4326 return api_format_data("photo_detail", $type, $data);
4331 * Updates the user’s profile image.
4333 * @brief updates the profile image for the user (either a specified profile or the default profile)
4335 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4338 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4340 function api_account_update_profile_image($type)
4342 if (api_user() === false) {
4343 throw new ForbiddenException();
4346 $profileid = defaults($_REQUEST, 'profile_id', 0);
4348 // error if image data is missing
4349 if (!x($_FILES, 'image')) {
4350 throw new BadRequestException("no media data submitted");
4353 // check if specified profile id is valid
4354 if ($profileid != 0) {
4356 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4360 // error message if specified profile id is not in database
4361 if (!DBM::is_result($r)) {
4362 throw new BadRequestException("profile_id not available");
4364 $is_default_profile = $r['profile'];
4366 $is_default_profile = 1;
4369 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4371 if (x($_FILES, 'image')) {
4372 $media = $_FILES['image'];
4373 } elseif (x($_FILES, 'media')) {
4374 $media = $_FILES['media'];
4376 // save new profile image
4377 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4380 if (is_array($media['type'])) {
4381 $filetype = $media['type'][0];
4383 $filetype = $media['type'];
4385 if ($filetype == "image/jpeg") {
4387 } elseif ($filetype == "image/png") {
4390 // change specified profile or all profiles to the new resource-id
4391 if ($is_default_profile) {
4393 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4394 dbesc($data['photo']['id']),
4395 intval(local_user())
4399 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
4400 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4401 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4402 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4403 intval(local_user())
4407 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4408 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4409 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4410 intval($_REQUEST['profile']),
4411 intval(local_user())
4415 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4416 // so that browsers will do a cache update unconditionally
4419 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4420 dbesc(DateTimeFormat::utcNow()),
4421 intval(local_user())
4424 // Update global directory in background
4425 //$user = api_get_user(get_app());
4426 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4427 if ($url && strlen(Config::get('system', 'directory'))) {
4428 Worker::add(PRIORITY_LOW, "Directory", $url);
4431 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4433 // output for client
4435 return api_account_verify_credentials($type);
4437 // SaveMediaToDatabase failed for some reason
4438 throw new InternalServerErrorException("image upload failed");
4442 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4443 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4444 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4445 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4446 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4447 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4448 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4449 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4450 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4453 * Update user profile
4455 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4457 * @return array|string
4459 function api_account_update_profile($type)
4461 $local_user = api_user();
4462 $api_user = api_get_user(get_app());
4464 if (!empty($_POST['name'])) {
4465 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4466 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4467 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4468 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4471 if (isset($_POST['description'])) {
4472 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4473 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4474 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4477 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4478 // Update global directory in background
4479 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4480 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4483 return api_account_verify_credentials($type);
4486 /// @TODO move to top of file or somewhere better
4487 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4491 * @param string $acl_string
4493 function check_acl_input($acl_string)
4495 if ($acl_string == null || $acl_string == " ") {
4498 $contact_not_found = false;
4500 // split <x><y><z> into array of cid's
4501 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4503 // check for each cid if it is available on server
4504 $cid_array = $array[0];
4505 foreach ($cid_array as $cid) {
4506 $cid = str_replace("<", "", $cid);
4507 $cid = str_replace(">", "", $cid);
4509 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4513 $contact_not_found |= !DBM::is_result($contact);
4515 return $contact_not_found;
4520 * @param string $mediatype
4521 * @param array $media
4522 * @param string $type
4523 * @param string $album
4524 * @param string $allow_cid
4525 * @param string $deny_cid
4526 * @param string $allow_gid
4527 * @param string $deny_gid
4528 * @param string $desc
4529 * @param integer $profile
4530 * @param boolean $visibility
4531 * @param string $photo_id
4533 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)
4541 if (is_array($media)) {
4542 if (is_array($media['tmp_name'])) {
4543 $src = $media['tmp_name'][0];
4545 $src = $media['tmp_name'];
4547 if (is_array($media['name'])) {
4548 $filename = basename($media['name'][0]);
4550 $filename = basename($media['name']);
4552 if (is_array($media['size'])) {
4553 $filesize = intval($media['size'][0]);
4555 $filesize = intval($media['size']);
4557 if (is_array($media['type'])) {
4558 $filetype = $media['type'][0];
4560 $filetype = $media['type'];
4564 if ($filetype == "") {
4565 $filetype=Image::guessType($filename);
4567 $imagedata = getimagesize($src);
4569 $filetype = $imagedata['mime'];
4572 "File upload src: " . $src . " - filename: " . $filename .
4573 " - size: " . $filesize . " - type: " . $filetype,
4577 // check if there was a php upload error
4578 if ($filesize == 0 && $media['error'] == 1) {
4579 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4581 // check against max upload size within Friendica instance
4582 $maximagesize = Config::get('system', 'maximagesize');
4583 if ($maximagesize && ($filesize > $maximagesize)) {
4584 $formattedBytes = formatBytes($maximagesize);
4585 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4588 // create Photo instance with the data of the image
4589 $imagedata = @file_get_contents($src);
4590 $Image = new Image($imagedata, $filetype);
4591 if (! $Image->isValid()) {
4592 throw new InternalServerErrorException("unable to process image data");
4595 // check orientation of image
4596 $Image->orient($src);
4599 // check max length of images on server
4600 $max_length = Config::get('system', 'max_image_length');
4601 if (! $max_length) {
4602 $max_length = MAX_IMAGE_LENGTH;
4604 if ($max_length > 0) {
4605 $Image->scaleDown($max_length);
4606 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4608 $width = $Image->getWidth();
4609 $height = $Image->getHeight();
4611 // create a new resource-id if not already provided
4612 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
4614 if ($mediatype == "photo") {
4615 // upload normal image (scales 0, 1, 2)
4616 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4618 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4620 logger("photo upload: image upload with scale 0 (original size) failed");
4622 if ($width > 640 || $height > 640) {
4623 $Image->scaleDown(640);
4624 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4626 logger("photo upload: image upload with scale 1 (640x640) failed");
4630 if ($width > 320 || $height > 320) {
4631 $Image->scaleDown(320);
4632 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4634 logger("photo upload: image upload with scale 2 (320x320) failed");
4637 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4638 } elseif ($mediatype == "profileimage") {
4639 // upload profile image (scales 4, 5, 6)
4640 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4642 if ($width > 175 || $height > 175) {
4643 $Image->scaleDown(175);
4644 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4646 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4650 if ($width > 80 || $height > 80) {
4651 $Image->scaleDown(80);
4652 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4654 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4658 if ($width > 48 || $height > 48) {
4659 $Image->scaleDown(48);
4660 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4662 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4665 $Image->__destruct();
4666 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4670 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4671 if ($photo_id == null && $mediatype == "photo") {
4672 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4674 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4675 return prepare_photo_data($type, false, $hash);
4677 throw new InternalServerErrorException("image upload failed");
4683 * @param string $hash
4684 * @param string $allow_cid
4685 * @param string $deny_cid
4686 * @param string $allow_gid
4687 * @param string $deny_gid
4688 * @param string $filetype
4689 * @param boolean $visibility
4691 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4693 // get data about the api authenticated user
4694 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4695 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4698 $arr['guid'] = get_guid(32);
4699 $arr['uid'] = intval(api_user());
4701 $arr['parent-uri'] = $uri;
4702 $arr['type'] = 'photo';
4704 $arr['resource-id'] = $hash;
4705 $arr['contact-id'] = $owner_record[0]['id'];
4706 $arr['owner-name'] = $owner_record[0]['name'];
4707 $arr['owner-link'] = $owner_record[0]['url'];
4708 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4709 $arr['author-name'] = $owner_record[0]['name'];
4710 $arr['author-link'] = $owner_record[0]['url'];
4711 $arr['author-avatar'] = $owner_record[0]['thumb'];
4713 $arr['allow_cid'] = $allow_cid;
4714 $arr['allow_gid'] = $allow_gid;
4715 $arr['deny_cid'] = $deny_cid;
4716 $arr['deny_gid'] = $deny_gid;
4717 $arr['visible'] = $visibility;
4721 'image/jpeg' => 'jpg',
4722 'image/png' => 'png',
4723 'image/gif' => 'gif'
4726 // adds link to the thumbnail scale photo
4727 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4728 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4731 // do the magic for storing the item in the database and trigger the federation to other contacts
4737 * @param string $type
4739 * @param string $photo_id
4743 function prepare_photo_data($type, $scale, $photo_id)
4745 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4746 $data_sql = ($scale === false ? "" : "data, ");
4748 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4749 // clients needs to convert this in their way for further processing
4751 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4752 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4753 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4754 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4756 intval(local_user()),
4762 'image/jpeg' => 'jpg',
4763 'image/png' => 'png',
4764 'image/gif' => 'gif'
4767 // prepare output data for photo
4768 if (DBM::is_result($r)) {
4769 $data = ['photo' => $r[0]];
4770 $data['photo']['id'] = $data['photo']['resource-id'];
4771 if ($scale !== false) {
4772 $data['photo']['data'] = base64_encode($data['photo']['data']);
4774 unset($data['photo']['datasize']); //needed only with scale param
4776 if ($type == "xml") {
4777 $data['photo']['links'] = [];
4778 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4779 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4781 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4784 $data['photo']['link'] = [];
4785 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4787 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4788 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4792 unset($data['photo']['resource-id']);
4793 unset($data['photo']['minscale']);
4794 unset($data['photo']['maxscale']);
4796 throw new NotFoundException();
4799 // retrieve item element for getting activities (like, dislike etc.) related to photo
4801 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4802 intval(local_user()),
4805 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4807 // retrieve comments on photo
4809 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4810 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4811 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4812 `contact`.`id` AS `cid`
4814 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4815 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4816 WHERE `item`.`parent` = %d AND `item`.`visible`
4817 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4818 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4819 intval($item[0]['parent']),
4821 dbesc(ACTIVITY_POST)
4824 // prepare output of comments
4825 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4827 if ($type == "xml") {
4829 foreach ($commentData as $comment) {
4830 $comments[$k++ . ":comment"] = $comment;
4833 foreach ($commentData as $comment) {
4834 $comments[] = $comment;
4837 $data['photo']['friendica_comments'] = $comments;
4839 // include info if rights on photo and rights on item are mismatching
4840 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4841 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4842 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4843 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4844 $data['photo']['rights_mismatch'] = $rights_mismatch;
4851 * Similar as /mod/redir.php
4852 * redirect to 'url' after dfrn auth
4854 * Why this when there is mod/redir.php already?
4855 * This use api_user() and api_login()
4858 * c_url: url of remote contact to auth to
4859 * url: string, url to redirect after auth
4861 function api_friendica_remoteauth()
4863 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4864 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4866 if ($url === '' || $c_url === '') {
4867 throw new BadRequestException("Wrong parameters.");
4870 $c_url = normalise_link($c_url);
4874 $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4876 if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
4877 throw new BadRequestException("Unknown contact");
4880 $cid = $contact['id'];
4882 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4884 if ($contact['duplex'] && $contact['issued-id']) {
4885 $orig_id = $contact['issued-id'];
4886 $dfrn_id = '1:' . $orig_id;
4888 if ($contact['duplex'] && $contact['dfrn-id']) {
4889 $orig_id = $contact['dfrn-id'];
4890 $dfrn_id = '0:' . $orig_id;
4893 $sec = random_string();
4896 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4897 VALUES( %d, %s, '%s', '%s', %d )",
4905 logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
4906 $dest = ($url ? '&destination_url=' . $url : '');
4908 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4909 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4910 . '&type=profile&sec=' . $sec . $dest . $quiet
4913 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4916 * @brief Return the item shared, if the item contains only the [share] tag
4918 * @param array $item Sharer item
4919 * @return array|false Shared item or false if not a reshare
4921 function api_share_as_retweet(&$item)
4923 $body = trim($item["body"]);
4925 if (Diaspora::isReshare($body, false)===false) {
4929 /// @TODO "$1" should maybe mean '$1' ?
4930 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4932 * Skip if there is no shared message in there
4933 * we already checked this in diaspora::isReshare()
4934 * but better one more than one less...
4936 if ($body == $attributes) {
4941 // build the fake reshared item
4942 $reshared_item = $item;
4945 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4946 if ($matches[1] != "") {
4947 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4950 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4951 if ($matches[1] != "") {
4952 $author = $matches[1];
4956 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4957 if ($matches[1] != "") {
4958 $profile = $matches[1];
4961 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4962 if ($matches[1] != "") {
4963 $profile = $matches[1];
4967 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4968 if ($matches[1] != "") {
4969 $avatar = $matches[1];
4972 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4973 if ($matches[1] != "") {
4974 $avatar = $matches[1];
4978 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4979 if ($matches[1] != "") {
4980 $link = $matches[1];
4983 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4984 if ($matches[1] != "") {
4985 $link = $matches[1];
4989 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4990 if ($matches[1] != "") {
4991 $posted = $matches[1];
4994 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4995 if ($matches[1] != "") {
4996 $posted = $matches[1];
4999 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5001 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5005 $reshared_item["body"] = $shared_body;
5006 $reshared_item["author-name"] = $author;
5007 $reshared_item["author-link"] = $profile;
5008 $reshared_item["author-avatar"] = $avatar;
5009 $reshared_item["plink"] = $link;
5010 $reshared_item["created"] = $posted;
5011 $reshared_item["edited"] = $posted;
5013 return $reshared_item;
5018 * @param string $profile
5020 * @return string|false
5021 * @todo remove trailing junk from profile url
5022 * @todo pump.io check has to check the website
5024 function api_get_nick($profile)
5029 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5030 dbesc(normalise_link($profile))
5033 if (DBM::is_result($r)) {
5034 $nick = $r[0]["nick"];
5039 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5040 dbesc(normalise_link($profile))
5043 if (DBM::is_result($r)) {
5044 $nick = $r[0]["nick"];
5049 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5050 if ($friendica != $profile) {
5056 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5057 if ($diaspora != $profile) {
5063 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5064 if ($twitter != $profile) {
5071 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5072 if ($StatusnetHost != $profile) {
5073 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5074 if ($StatusnetUser != $profile) {
5075 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5076 $user = json_decode($UserData);
5078 $nick = $user->screen_name;
5084 // To-Do: look at the page if its really a pumpio site
5085 //if (!$nick == "") {
5086 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5087 // if ($pumpio != $profile)
5089 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5102 * @param array $item
5106 function api_in_reply_to($item)
5110 $in_reply_to['status_id'] = null;
5111 $in_reply_to['user_id'] = null;
5112 $in_reply_to['status_id_str'] = null;
5113 $in_reply_to['user_id_str'] = null;
5114 $in_reply_to['screen_name'] = null;
5116 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5118 "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
5119 intval($item['uid']),
5120 dbesc($item['thr-parent'])
5123 if (DBM::is_result($r)) {
5124 $in_reply_to['status_id'] = intval($r[0]['id']);
5126 $in_reply_to['status_id'] = intval($item['parent']);
5129 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5132 "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
5133 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
5134 WHERE `item`.`id` = %d LIMIT 1",
5135 intval($in_reply_to['status_id'])
5138 if (DBM::is_result($r)) {
5139 if ($r[0]['nick'] == "") {
5140 $r[0]['nick'] = api_get_nick($r[0]["url"]);
5143 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
5144 $in_reply_to['user_id'] = intval($r[0]['id']);
5145 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
5148 // There seems to be situation, where both fields are identical:
5149 // https://github.com/friendica/friendica/issues/1010
5150 // This is a bugfix for that.
5151 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5152 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
5153 $in_reply_to['status_id'] = null;
5154 $in_reply_to['user_id'] = null;
5155 $in_reply_to['status_id_str'] = null;
5156 $in_reply_to['user_id_str'] = null;
5157 $in_reply_to['screen_name'] = null;
5161 return $in_reply_to;
5166 * @param string $Text
5170 function api_clean_plain_items($Text)
5172 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5174 $Text = BBCode::cleanPictureLinks($Text);
5175 $URLSearchString = "^\[\]";
5177 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
5179 if ($include_entities == "true") {
5180 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
5183 // Simplify "attachment" element
5184 $Text = api_clean_attachments($Text);
5190 * @brief Removes most sharing information for API text export
5192 * @param string $body The original body
5194 * @return string Cleaned body
5196 function api_clean_attachments($body)
5198 $data = BBCode::getAttachmentData($body);
5205 if (isset($data["text"])) {
5206 $body = $data["text"];
5208 if (($body == "") && isset($data["title"])) {
5209 $body = $data["title"];
5211 if (isset($data["url"])) {
5212 $body .= "\n".$data["url"];
5214 $body .= $data["after"];
5221 * @param array $contacts
5225 function api_best_nickname(&$contacts)
5229 if (count($contact) == 0) {
5233 foreach ($contacts as $contact) {
5234 if ($contact["network"] == "") {
5235 $contact["network"] = "dfrn";
5236 $best_contact = [$contact];
5240 if (sizeof($best_contact) == 0) {
5241 foreach ($contacts as $contact) {
5242 if ($contact["network"] == "dfrn") {
5243 $best_contact = [$contact];
5248 if (sizeof($best_contact) == 0) {
5249 foreach ($contacts as $contact) {
5250 if ($contact["network"] == "dspr") {
5251 $best_contact = [$contact];
5256 if (sizeof($best_contact) == 0) {
5257 foreach ($contacts as $contact) {
5258 if ($contact["network"] == "stat") {
5259 $best_contact = [$contact];
5264 if (sizeof($best_contact) == 0) {
5265 foreach ($contacts as $contact) {
5266 if ($contact["network"] == "pump") {
5267 $best_contact = [$contact];
5272 if (sizeof($best_contact) == 0) {
5273 foreach ($contacts as $contact) {
5274 if ($contact["network"] == "twit") {
5275 $best_contact = [$contact];
5280 if (sizeof($best_contact) == 1) {
5281 $contacts = $best_contact;
5283 $contacts = [$contacts[0]];
5288 * Return all or a specified group of the user with the containing contacts.
5290 * @param string $type Return type (atom, rss, xml, json)
5292 * @return array|string
5294 function api_friendica_group_show($type)
5298 if (api_user() === false) {
5299 throw new ForbiddenException();
5303 $user_info = api_get_user($a);
5304 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5305 $uid = $user_info['uid'];
5307 // get data of the specified group id or all groups if not specified
5310 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5314 // error message if specified gid is not in database
5315 if (!DBM::is_result($r)) {
5316 throw new BadRequestException("gid not available");
5320 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5325 // loop through all groups and retrieve all members for adding data in the user array
5326 foreach ($r as $rr) {
5327 $members = Contact::getByGroupId($rr['id']);
5330 if ($type == "xml") {
5331 $user_element = "users";
5333 foreach ($members as $member) {
5334 $user = api_get_user($a, $member['nurl']);
5335 $users[$k++.":user"] = $user;
5338 $user_element = "user";
5339 foreach ($members as $member) {
5340 $user = api_get_user($a, $member['nurl']);
5344 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5346 return api_format_data("groups", $type, ['group' => $grps]);
5348 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5352 * Delete the specified group of the user.
5354 * @param string $type Return type (atom, rss, xml, json)
5356 * @return array|string
5358 function api_friendica_group_delete($type)
5362 if (api_user() === false) {
5363 throw new ForbiddenException();
5367 $user_info = api_get_user($a);
5368 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5369 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5370 $uid = $user_info['uid'];
5372 // error if no gid specified
5373 if ($gid == 0 || $name == "") {
5374 throw new BadRequestException('gid or name not specified');
5377 // get data of the specified group id
5379 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5383 // error message if specified gid is not in database
5384 if (!DBM::is_result($r)) {
5385 throw new BadRequestException('gid not available');
5388 // get data of the specified group id and group name
5390 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5395 // error message if specified gid is not in database
5396 if (!DBM::is_result($rname)) {
5397 throw new BadRequestException('wrong group name');
5401 $ret = Group::removeByName($uid, $name);
5404 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5405 return api_format_data("group_delete", $type, ['result' => $success]);
5407 throw new BadRequestException('other API error');
5410 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5414 * Create the specified group with the posted array of contacts.
5416 * @param string $type Return type (atom, rss, xml, json)
5418 * @return array|string
5420 function api_friendica_group_create($type)
5424 if (api_user() === false) {
5425 throw new ForbiddenException();
5429 $user_info = api_get_user($a);
5430 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5431 $uid = $user_info['uid'];
5432 $json = json_decode($_POST['json'], true);
5433 $users = $json['user'];
5435 // error if no name specified
5437 throw new BadRequestException('group name not specified');
5440 // get data of the specified group name
5442 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5446 // error message if specified group name already exists
5447 if (DBM::is_result($rname)) {
5448 throw new BadRequestException('group name already exists');
5451 // check if specified group name is a deleted group
5453 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5457 // error message if specified group name already exists
5458 if (DBM::is_result($rname)) {
5459 $reactivate_group = true;
5463 $ret = Group::create($uid, $name);
5465 $gid = Group::getIdByName($uid, $name);
5467 throw new BadRequestException('other API error');
5471 $erroraddinguser = false;
5473 foreach ($users as $user) {
5474 $cid = $user['cid'];
5475 // check if user really exists as contact
5477 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5481 if (count($contact)) {
5482 Group::addMember($gid, $cid);
5484 $erroraddinguser = true;
5485 $errorusers[] = $cid;
5489 // return success message incl. missing users in array
5490 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
5491 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5492 return api_format_data("group_create", $type, ['result' => $success]);
5494 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5498 * Update the specified group with the posted array of contacts.
5500 * @param string $type Return type (atom, rss, xml, json)
5502 * @return array|string
5504 function api_friendica_group_update($type)
5508 if (api_user() === false) {
5509 throw new ForbiddenException();
5513 $user_info = api_get_user($a);
5514 $uid = $user_info['uid'];
5515 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5516 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5517 $json = json_decode($_POST['json'], true);
5518 $users = $json['user'];
5520 // error if no name specified
5522 throw new BadRequestException('group name not specified');
5525 // error if no gid specified
5527 throw new BadRequestException('gid not specified');
5531 $members = Contact::getByGroupId($gid);
5532 foreach ($members as $member) {
5533 $cid = $member['id'];
5534 foreach ($users as $user) {
5535 $found = ($user['cid'] == $cid ? true : false);
5538 Group::removeMemberByName($uid, $name, $cid);
5543 $erroraddinguser = false;
5545 foreach ($users as $user) {
5546 $cid = $user['cid'];
5547 // check if user really exists as contact
5549 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5554 if (count($contact)) {
5555 Group::addMember($gid, $cid);
5557 $erroraddinguser = true;
5558 $errorusers[] = $cid;
5562 // return success message incl. missing users in array
5563 $status = ($erroraddinguser ? "missing user" : "ok");
5564 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5565 return api_format_data("group_update", $type, ['result' => $success]);
5568 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5572 * @param string $type Return type (atom, rss, xml, json)
5574 * @return array|string
5576 function api_friendica_activity($type)
5580 if (api_user() === false) {
5581 throw new ForbiddenException();
5583 $verb = strtolower($a->argv[3]);
5584 $verb = preg_replace("|\..*$|", "", $verb);
5586 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5588 $res = Item::performLike($id, $verb);
5591 if ($type == "xml") {
5596 return api_format_data('ok', $type, ['ok' => $ok]);
5598 throw new BadRequestException('Error adding activity');
5602 /// @TODO move to top of file or somewhere better
5603 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5604 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5605 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5606 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5607 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5608 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5609 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5610 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5611 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5612 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5615 * @brief Returns notifications
5617 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5620 function api_friendica_notification($type)
5624 if (api_user() === false) {
5625 throw new ForbiddenException();
5628 throw new BadRequestException("Invalid argument count");
5630 $nm = new NotificationsManager();
5632 $notes = $nm->getAll([], "+seen -date", 50);
5634 if ($type == "xml") {
5636 foreach ($notes as $note) {
5637 $xmlnotes[] = ["@attributes" => $note];
5643 return api_format_data("notes", $type, ['note' => $notes]);
5647 * POST request with 'id' param as notification id
5649 * @brief Set notification as seen and returns associated item (if possible)
5651 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5654 function api_friendica_notification_seen($type)
5658 if (api_user() === false) {
5659 throw new ForbiddenException();
5662 throw new BadRequestException("Invalid argument count");
5665 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5667 $nm = new NotificationsManager();
5668 $note = $nm->getByID($id);
5669 if (is_null($note)) {
5670 throw new BadRequestException("Invalid argument");
5673 $nm->setSeen($note);
5674 if ($note['otype']=='item') {
5675 // would be really better with an ItemsManager and $im->getByID() :-P
5677 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5678 intval($note['iid']),
5679 intval(local_user())
5682 // we found the item, return it to the user
5683 $user_info = api_get_user($a);
5684 $ret = api_format_items($r, $user_info, false, $type);
5685 $data = ['status' => $ret];
5686 return api_format_data("status", $type, $data);
5688 // the item can't be found, but we set the note as seen, so we count this as a success
5690 return api_format_data('result', $type, ['result' => "success"]);
5693 /// @TODO move to top of file or somewhere better
5694 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5695 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5698 * @brief update a direct_message to seen state
5700 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5701 * @return string (success result=ok, error result=error with error message)
5703 function api_friendica_direct_messages_setseen($type)
5706 if (api_user() === false) {
5707 throw new ForbiddenException();
5711 $user_info = api_get_user($a);
5712 $uid = $user_info['uid'];
5713 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5715 // return error if id is zero
5717 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5718 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5721 // get data of the specified message id
5723 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5728 // error message if specified id is not in database
5729 if (!DBM::is_result($r)) {
5730 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5731 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5734 // update seen indicator
5736 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5743 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5744 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5746 $answer = ['result' => 'error', 'message' => 'unknown error'];
5747 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5751 /// @TODO move to top of file or somewhere better
5752 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5755 * @brief search for direct_messages containing a searchstring through api
5757 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5758 * @return string (success: success=true if found and search_result contains found messages,
5759 * success=false if nothing was found, search_result='nothing found',
5760 * error: result=error with error message)
5762 function api_friendica_direct_messages_search($type)
5766 if (api_user() === false) {
5767 throw new ForbiddenException();
5771 $user_info = api_get_user($a);
5772 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5773 $uid = $user_info['uid'];
5775 // error if no searchstring specified
5776 if ($searchstring == "") {
5777 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5778 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5781 // get data for the specified searchstring
5783 "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",
5785 dbesc('%'.$searchstring.'%')
5788 $profile_url = $user_info["url"];
5790 // message if nothing was found
5791 if (!DBM::is_result($r)) {
5792 $success = ['success' => false, 'search_results' => 'problem with query'];
5793 } elseif (count($r) == 0) {
5794 $success = ['success' => false, 'search_results' => 'nothing found'];
5797 foreach ($r as $item) {
5798 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5799 $recipient = $user_info;
5800 $sender = api_get_user($a, normalise_link($item['contact-url']));
5801 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5802 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5803 $sender = $user_info;
5806 $ret[] = api_format_messages($item, $recipient, $sender);
5808 $success = ['success' => true, 'search_results' => $ret];
5811 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5814 /// @TODO move to top of file or somewhere better
5815 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5818 * @brief return data of all the profiles a user has to the client
5820 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5823 function api_friendica_profile_show($type)
5827 if (api_user() === false) {
5828 throw new ForbiddenException();
5832 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5834 // retrieve general information about profiles for user
5835 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5836 $directory = Config::get('system', 'directory');
5838 // get data of the specified profile id or all profiles of the user if not specified
5839 if ($profileid != 0) {
5841 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5846 // error message if specified gid is not in database
5847 if (!DBM::is_result($r)) {
5848 throw new BadRequestException("profile_id not available");
5852 "SELECT * FROM `profile` WHERE `uid` = %d",
5856 // loop through all returned profiles and retrieve data and users
5858 foreach ($r as $rr) {
5859 $profile = api_format_items_profiles($rr);
5861 // select all users from contact table, loop and prepare standard return for user data
5864 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5866 intval($rr['profile_id'])
5869 foreach ($r as $rr) {
5870 $user = api_get_user($a, $rr['nurl']);
5871 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5873 $profile['users'] = $users;
5875 // add prepared profile data to array for final return
5876 if ($type == "xml") {
5877 $profiles[$k++ . ":profile"] = $profile;
5879 $profiles[] = $profile;
5883 // return settings, authenticated user and profiles data
5884 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5886 $result = ['multi_profiles' => $multi_profiles ? true : false,
5887 'global_dir' => $directory,
5888 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5889 'profiles' => $profiles];
5890 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5892 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5895 * Returns a list of saved searches.
5897 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5899 * @param string $type Return format: json or xml
5901 * @return string|array
5903 function api_saved_searches_list($type)
5905 $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
5908 while ($term = $terms->fetch()) {
5910 'name' => $term['term'],
5911 'query' => $term['term'],
5912 'id_str' => $term['id'],
5913 'id' => intval($term['id'])
5919 return api_format_data("terms", $type, ['terms' => $result]);
5922 /// @TODO move to top of file or somewhere better
5923 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5926 @TODO Maybe open to implement?
5928 [pagename] => api/1.1/statuses/lookup.json
5929 [id] => 605138389168451584
5930 [include_cards] => true
5931 [cards_platform] => Android-12
5932 [include_entities] => true
5933 [include_my_retweet] => 1
5935 [include_reply_count] => true
5936 [include_descendent_reply_count] => true
5940 Not implemented by now:
5941 statuses/retweets_of_me
5946 account/update_location
5947 account/update_profile_background_image
5950 friendica/profile/update
5951 friendica/profile/create
5952 friendica/profile/delete
5954 Not implemented in status.net:
5955 statuses/retweeted_to_me
5956 statuses/retweeted_by_me
5957 direct_messages/destroy
5959 account/update_delivery_device
5960 notifications/follow