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\Content\Text\HTML;
14 use Friendica\Core\Addon;
15 use Friendica\Core\Config;
16 use Friendica\Core\L10n;
17 use Friendica\Core\NotificationsManager;
18 use Friendica\Core\PConfig;
19 use Friendica\Core\System;
20 use Friendica\Core\Worker;
21 use Friendica\Database\DBM;
22 use Friendica\Model\Contact;
23 use Friendica\Model\Group;
24 use Friendica\Model\Item;
25 use Friendica\Model\Mail;
26 use Friendica\Model\Photo;
27 use Friendica\Model\User;
28 use Friendica\Network\FKOAuth1;
29 use Friendica\Network\HTTPException;
30 use Friendica\Network\HTTPException\BadRequestException;
31 use Friendica\Network\HTTPException\ForbiddenException;
32 use Friendica\Network\HTTPException\InternalServerErrorException;
33 use Friendica\Network\HTTPException\MethodNotAllowedException;
34 use Friendica\Network\HTTPException\NotFoundException;
35 use Friendica\Network\HTTPException\NotImplementedException;
36 use Friendica\Network\HTTPException\TooManyRequestsException;
37 use Friendica\Network\HTTPException\UnauthorizedException;
38 use Friendica\Object\Image;
39 use Friendica\Protocol\Diaspora;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Network;
42 use Friendica\Util\XML;
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, Cache %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["cache"], 3),
325 round($a->performance["cache_write"], 3),
326 round($a->performance["network"], 2),
327 round($a->performance["file"], 2),
328 round($duration - ($a->performance["database"]
329 + $a->performance["cache"] + $a->performance["cache_write"]
330 + $a->performance["network"] + $a->performance["file"]), 2),
336 if (Config::get("rendertime", "callstack")) {
337 $o = "Database Read:\n";
338 foreach ($a->callstack["database"] as $func => $time) {
339 $time = round($time, 3);
341 $o .= $func . ": " . $time . "\n";
344 $o .= "\nDatabase Write:\n";
345 foreach ($a->callstack["database_write"] as $func => $time) {
346 $time = round($time, 3);
348 $o .= $func . ": " . $time . "\n";
352 $o = "Cache Read:\n";
353 foreach ($a->callstack["cache"] as $func => $time) {
354 $time = round($time, 3);
356 $o .= $func . ": " . $time . "\n";
359 $o .= "\nCache Write:\n";
360 foreach ($a->callstack["cache_write"] as $func => $time) {
361 $time = round($time, 3);
363 $o .= $func . ": " . $time . "\n";
367 $o .= "\nNetwork:\n";
368 foreach ($a->callstack["network"] as $func => $time) {
369 $time = round($time, 3);
371 $o .= $func . ": " . $time . "\n";
374 logger($o, LOGGER_DEBUG);
378 if (false === $return) {
380 * api function returned false withour throw an
381 * exception. This should not happend, throw a 500
383 throw new InternalServerErrorException();
388 header("Content-Type: text/xml");
391 header("Content-Type: application/json");
392 foreach ($return as $rr) {
393 $json = json_encode($rr);
395 if (x($_GET, 'callback')) {
396 $json = $_GET['callback'] . "(" . $json . ")";
401 header("Content-Type: application/rss+xml");
402 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
405 header("Content-Type: application/atom+xml");
406 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
413 logger('API call not implemented: ' . $a->query_string);
414 throw new NotImplementedException();
415 } catch (HTTPException $e) {
416 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
417 return api_error($type, $e);
422 * @brief Format API error string
424 * @param string $type Return type (xml, json, rss, as)
425 * @param object $e HTTPException Error object
426 * @return string error message formatted as $type
428 function api_error($type, $e)
432 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
433 /// @TODO: https://dev.twitter.com/overview/api/response-codes
435 $error = ["error" => $error,
436 "code" => $e->httpcode . " " . $e->httpdesc,
437 "request" => $a->query_string];
439 $return = api_format_data('status', $type, ['status' => $error]);
443 header("Content-Type: text/xml");
446 header("Content-Type: application/json");
447 $return = json_encode($return);
450 header("Content-Type: application/rss+xml");
453 header("Content-Type: application/atom+xml");
461 * @brief Set values for RSS template
464 * @param array $arr Array to be passed to template
465 * @param array $user_info User info
467 * @todo find proper type-hints
469 function api_rss_extra(App $a, $arr, $user_info)
471 if (is_null($user_info)) {
472 $user_info = api_get_user($a);
475 $arr['$user'] = $user_info;
477 'alternate' => $user_info['url'],
478 'self' => System::baseUrl() . "/" . $a->query_string,
479 'base' => System::baseUrl(),
480 'updated' => api_date(null),
481 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
482 'language' => $user_info['language'],
483 'logo' => System::baseUrl() . "/images/friendica-32.png",
491 * @brief Unique contact to contact url.
493 * @param int $id Contact id
494 * @return bool|string
495 * Contact url or False if contact id is unknown
497 function api_unique_id_to_nurl($id)
499 $r = dba::selectFirst('contact', ['nurl'], ['uid' => 0, 'id' => $id]);
501 if (DBM::is_result($r)) {
509 * @brief Get user info array.
511 * @param object $a App
512 * @param int|string $contact_id Contact ID or URL
514 function api_get_user(App $a, $contact_id = null)
522 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
524 // Searching for contact URL
525 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
526 $user = dbesc(normalise_link($contact_id));
528 $extra_query = "AND `contact`.`nurl` = '%s' ";
529 if (api_user() !== false) {
530 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
534 // Searching for contact id with uid = 0
535 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
536 $user = dbesc(api_unique_id_to_nurl($contact_id));
539 throw new BadRequestException("User not found.");
543 $extra_query = "AND `contact`.`nurl` = '%s' ";
544 if (api_user() !== false) {
545 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
549 if (is_null($user) && x($_GET, 'user_id')) {
550 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
553 throw new BadRequestException("User not found.");
557 $extra_query = "AND `contact`.`nurl` = '%s' ";
558 if (api_user() !== false) {
559 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
562 if (is_null($user) && x($_GET, 'screen_name')) {
563 $user = dbesc($_GET['screen_name']);
564 $extra_query = "AND `contact`.`nick` = '%s' ";
565 if (api_user() !== false) {
566 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
570 if (is_null($user) && x($_GET, 'profileurl')) {
571 $user = dbesc(normalise_link($_GET['profileurl']));
572 $extra_query = "AND `contact`.`nurl` = '%s' ";
573 if (api_user() !== false) {
574 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
578 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
579 $argid = count($called_api);
580 list($user, $null) = explode(".", $a->argv[$argid]);
581 if (is_numeric($user)) {
582 $user = dbesc(api_unique_id_to_nurl($user));
589 $extra_query = "AND `contact`.`nurl` = '%s' ";
590 if (api_user() !== false) {
591 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
594 $user = dbesc($user);
595 $extra_query = "AND `contact`.`nick` = '%s' ";
596 if (api_user() !== false) {
597 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
602 logger("api_get_user: user ".$user, LOGGER_DEBUG);
605 if (api_user() === false) {
609 $user = $_SESSION['uid'];
610 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
614 logger('api_user: ' . $extra_query . ', user: ' . $user);
618 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
624 // Selecting the id by priority, friendica first
625 api_best_nickname($uinfo);
627 // if the contact wasn't found, fetch it from the contacts with uid = 0
628 if (!DBM::is_result($uinfo)) {
632 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
635 if (DBM::is_result($r)) {
636 $network_name = ContactSelector::networkToName($r[0]['network'], $r[0]['url']);
638 // If no nick where given, extract it from the address
639 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
640 $r[0]['nick'] = api_get_nick($r[0]["url"]);
645 'id_str' => (string) $r[0]["id"],
646 'name' => $r[0]["name"],
647 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
648 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
649 'description' => $r[0]["about"],
650 'profile_image_url' => $r[0]["micro"],
651 'profile_image_url_https' => $r[0]["micro"],
652 'url' => $r[0]["url"],
653 'protected' => false,
654 'followers_count' => 0,
655 'friends_count' => 0,
657 'created_at' => api_date($r[0]["created"]),
658 'favourites_count' => 0,
660 'time_zone' => 'UTC',
661 'geo_enabled' => false,
663 'statuses_count' => 0,
665 'contributors_enabled' => false,
666 'is_translator' => false,
667 'is_translation_enabled' => false,
668 'following' => false,
669 'follow_request_sent' => false,
670 'statusnet_blocking' => false,
671 'notifications' => false,
672 'statusnet_profile_url' => $r[0]["url"],
674 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
676 'network' => $r[0]["network"],
681 throw new BadRequestException("User not found.");
685 if ($uinfo[0]['self']) {
686 if ($uinfo[0]['network'] == "") {
687 $uinfo[0]['network'] = NETWORK_DFRN;
691 "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
695 "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
699 /// @TODO old-lost code? (twice)
700 // Counting is deactivated by now, due to performance issues
701 // count public wall messages
702 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
703 // intval($uinfo[0]['uid'])
705 //$countitms = $r[0]['count'];
708 // Counting is deactivated by now, due to performance issues
709 //$r = q("SELECT count(*) as `count` FROM `item`
710 // WHERE `contact-id` = %d",
711 // intval($uinfo[0]['id'])
713 //$countitms = $r[0]['count'];
717 /// @TODO old-lost code? (twice)
719 // Counting is deactivated by now, due to performance issues
721 $r = q("SELECT count(*) as `count` FROM `contact`
722 WHERE `uid` = %d AND `rel` IN ( %d, %d )
723 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
724 intval($uinfo[0]['uid']),
725 intval(CONTACT_IS_SHARING),
726 intval(CONTACT_IS_FRIEND)
728 $countfriends = $r[0]['count'];
730 $r = q("SELECT count(*) as `count` FROM `contact`
731 WHERE `uid` = %d AND `rel` IN ( %d, %d )
732 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
733 intval($uinfo[0]['uid']),
734 intval(CONTACT_IS_FOLLOWER),
735 intval(CONTACT_IS_FRIEND)
737 $countfollowers = $r[0]['count'];
739 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
740 intval($uinfo[0]['uid'])
742 $starred = $r[0]['count'];
745 if (! $uinfo[0]['self']) {
755 // Add a nick if it isn't present there
756 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
757 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
760 $network_name = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
762 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
764 if (!empty($profile[0]['about'])) {
765 $description = $profile[0]['about'];
767 $description = $uinfo[0]["about"];
770 if (!empty($usr[0]['default-location'])) {
771 $location = $usr[0]['default-location'];
772 } elseif (!empty($uinfo[0]["location"])) {
773 $location = $uinfo[0]["location"];
775 $location = $network_name;
779 'id' => intval($pcontact_id),
780 'id_str' => (string) intval($pcontact_id),
781 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
782 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
783 'location' => $location,
784 'description' => $description,
785 'profile_image_url' => $uinfo[0]['micro'],
786 'profile_image_url_https' => $uinfo[0]['micro'],
787 'url' => $uinfo[0]['url'],
788 'protected' => false,
789 'followers_count' => intval($countfollowers),
790 'friends_count' => intval($countfriends),
792 'created_at' => api_date($uinfo[0]['created']),
793 'favourites_count' => intval($starred),
795 'time_zone' => 'UTC',
796 'geo_enabled' => false,
798 'statuses_count' => intval($countitms),
800 'contributors_enabled' => false,
801 'is_translator' => false,
802 'is_translation_enabled' => false,
803 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
804 'follow_request_sent' => false,
805 'statusnet_blocking' => false,
806 'notifications' => false,
808 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
809 'statusnet_profile_url' => $uinfo[0]['url'],
810 'uid' => intval($uinfo[0]['uid']),
811 'cid' => intval($uinfo[0]['cid']),
812 'self' => $uinfo[0]['self'],
813 'network' => $uinfo[0]['network'],
816 // If this is a local user and it uses Frio, we can get its color preferences.
818 $theme_info = dba::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
819 if ($theme_info['theme'] === 'frio') {
820 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
821 if ($schema && ($schema != '---')) {
822 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
823 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
824 require_once $schemefile;
827 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
828 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
829 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
835 $link_color = "#6fdbe8";
838 $bgcolor = "#ededed";
841 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
842 $ret['profile_link_color'] = str_replace('#', '', $link_color);
843 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
851 * @brief return api-formatted array for item's author and owner
853 * @param object $a App
854 * @param array $item item from db
855 * @return array(array:author, array:owner)
857 function api_item_get_user(App $a, $item)
859 $status_user = api_get_user($a, $item["author-link"]);
861 $status_user["protected"] = (($item["allow_cid"] != "") ||
862 ($item["allow_gid"] != "") ||
863 ($item["deny_cid"] != "") ||
864 ($item["deny_gid"] != "") ||
867 if ($item['thr-parent'] == $item['uri']) {
868 $owner_user = api_get_user($a, $item["owner-link"]);
870 $owner_user = $status_user;
873 return ([$status_user, $owner_user]);
877 * @brief walks recursively through an array with the possibility to change value and key
879 * @param array $array The array to walk through
880 * @param string $callback The callback function
882 * @return array the transformed array
884 function api_walk_recursive(array &$array, callable $callback)
888 foreach ($array as $k => $v) {
890 if ($callback($v, $k)) {
891 $new_array[$k] = api_walk_recursive($v, $callback);
894 if ($callback($v, $k)) {
905 * @brief Callback function to transform the array in an array that can be transformed in a XML file
907 * @param mixed $item Array item value
908 * @param string $key Array key
910 * @return boolean Should the array item be deleted?
912 function api_reformat_xml(&$item, &$key)
914 if (is_bool($item)) {
915 $item = ($item ? "true" : "false");
918 if (substr($key, 0, 10) == "statusnet_") {
919 $key = "statusnet:".substr($key, 10);
920 } elseif (substr($key, 0, 10) == "friendica_") {
921 $key = "friendica:".substr($key, 10);
923 /// @TODO old-lost code?
925 // $key = "default:".$key;
931 * @brief Creates the XML from a JSON style array
933 * @param array $data JSON style array
934 * @param string $root_element Name of the root element
936 * @return string The XML data
938 function api_create_xml($data, $root_element)
940 $childname = key($data);
941 $data2 = array_pop($data);
944 $namespaces = ["" => "http://api.twitter.com",
945 "statusnet" => "http://status.net/schema/api/1/",
946 "friendica" => "http://friendi.ca/schema/api/1/",
947 "georss" => "http://www.georss.org/georss"];
949 /// @todo Auto detection of needed namespaces
950 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
954 if (is_array($data2)) {
955 api_walk_recursive($data2, "api_reformat_xml");
962 foreach ($data2 as $item) {
963 $data4[$i++.":".$childname] = $item;
969 $data3 = [$root_element => $data2];
971 $ret = XML::fromArray($data3, $xml, false, $namespaces);
976 * @brief Formats the data according to the data type
978 * @param string $root_element Name of the root element
979 * @param string $type Return type (atom, rss, xml, json)
980 * @param array $data JSON style array
982 * @return (string|object|array) XML data or JSON data
984 function api_format_data($root_element, $type, $data)
990 $ret = api_create_xml($data, $root_element);
1005 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
1006 * returns a 401 status code and an error message if not.
1007 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
1009 * @param string $type Return type (atom, rss, xml, json)
1011 function api_account_verify_credentials($type)
1016 if (api_user() === false) {
1017 throw new ForbiddenException();
1020 unset($_REQUEST["user_id"]);
1021 unset($_GET["user_id"]);
1023 unset($_REQUEST["screen_name"]);
1024 unset($_GET["screen_name"]);
1026 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
1028 $user_info = api_get_user($a);
1030 // "verified" isn't used here in the standard
1031 unset($user_info["verified"]);
1033 // - Adding last status
1034 if (!$skip_status) {
1035 $user_info["status"] = api_status_show("raw");
1036 if (!count($user_info["status"])) {
1037 unset($user_info["status"]);
1039 unset($user_info["status"]["user"]);
1043 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1044 unset($user_info["uid"]);
1045 unset($user_info["self"]);
1047 return api_format_data("user", $type, ['user' => $user_info]);
1050 /// @TODO move to top of file or somewhere better
1051 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1054 * Get data from $_POST or $_GET
1058 function requestdata($k)
1060 if (x($_POST, $k)) {
1070 * Waitman Gobble Mod
1072 * @param string $type Return type (atom, rss, xml, json)
1074 * @return array|string
1076 function api_statuses_mediap($type)
1080 if (api_user() === false) {
1081 logger('api_statuses_update: no user');
1082 throw new ForbiddenException();
1084 $user_info = api_get_user($a);
1086 $_REQUEST['type'] = 'wall';
1087 $_REQUEST['profile_uid'] = api_user();
1088 $_REQUEST['api_source'] = true;
1089 $txt = requestdata('status');
1090 /// @TODO old-lost code?
1091 //$txt = urldecode(requestdata('status'));
1093 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1094 $txt = html2bb_video($txt);
1095 $config = HTMLPurifier_Config::createDefault();
1096 $config->set('Cache.DefinitionImpl', null);
1097 $purifier = new HTMLPurifier($config);
1098 $txt = $purifier->purify($txt);
1100 $txt = HTML::toBBCode($txt);
1102 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1104 // tell wall_upload function to return img info instead of echo
1105 $_REQUEST['hush'] = 'yeah';
1106 $bebop = wall_upload_post($a);
1108 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1109 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1112 // this should output the last post (the one we just posted).
1113 return api_status_show($type);
1116 /// @TODO move this to top of file or somewhere better!
1117 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1120 * Updates the user’s current status.
1122 * @param string $type Return type (atom, rss, xml, json)
1124 * @return array|string
1125 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1127 function api_statuses_update($type)
1132 if (api_user() === false) {
1133 logger('api_statuses_update: no user');
1134 throw new ForbiddenException();
1139 // convert $_POST array items to the form we use for web posts.
1140 if (requestdata('htmlstatus')) {
1141 $txt = requestdata('htmlstatus');
1142 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1143 $txt = html2bb_video($txt);
1145 $config = HTMLPurifier_Config::createDefault();
1146 $config->set('Cache.DefinitionImpl', null);
1148 $purifier = new HTMLPurifier($config);
1149 $txt = $purifier->purify($txt);
1151 $_REQUEST['body'] = HTML::toBBCode($txt);
1154 $_REQUEST['body'] = requestdata('status');
1157 $_REQUEST['title'] = requestdata('title');
1159 $parent = requestdata('in_reply_to_status_id');
1161 // Twidere sends "-1" if it is no reply ...
1162 if ($parent == -1) {
1166 if (ctype_digit($parent)) {
1167 $_REQUEST['parent'] = $parent;
1169 $_REQUEST['parent_uri'] = $parent;
1172 if (requestdata('lat') && requestdata('long')) {
1173 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1175 $_REQUEST['profile_uid'] = api_user();
1178 $_REQUEST['type'] = 'net-comment';
1180 // Check for throttling (maximum posts per day, week and month)
1181 $throttle_day = Config::get('system', 'throttle_limit_day');
1182 if ($throttle_day > 0) {
1183 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1186 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1187 AND `created` > '%s' AND `id` = `parent`",
1192 if (DBM::is_result($r)) {
1193 $posts_day = $r[0]["posts_day"];
1198 if ($posts_day > $throttle_day) {
1199 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1200 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1201 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));
1205 $throttle_week = Config::get('system', 'throttle_limit_week');
1206 if ($throttle_week > 0) {
1207 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1210 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1211 AND `created` > '%s' AND `id` = `parent`",
1216 if (DBM::is_result($r)) {
1217 $posts_week = $r[0]["posts_week"];
1222 if ($posts_week > $throttle_week) {
1223 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1224 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1225 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));
1229 $throttle_month = Config::get('system', 'throttle_limit_month');
1230 if ($throttle_month > 0) {
1231 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1234 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1235 AND `created` > '%s' AND `id` = `parent`",
1240 if (DBM::is_result($r)) {
1241 $posts_month = $r[0]["posts_month"];
1246 if ($posts_month > $throttle_month) {
1247 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1248 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1249 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));
1253 $_REQUEST['type'] = 'wall';
1256 if (x($_FILES, 'media')) {
1257 // upload the image if we have one
1258 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1259 $media = wall_upload_post($a);
1260 if (strlen($media) > 0) {
1261 $_REQUEST['body'] .= "\n\n" . $media;
1265 // To-Do: Multiple IDs
1266 if (requestdata('media_ids')) {
1268 "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",
1269 intval(requestdata('media_ids')),
1272 if (DBM::is_result($r)) {
1273 $phototypes = Image::supportedTypes();
1274 $ext = $phototypes[$r[0]['type']];
1275 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1276 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1280 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1282 $_REQUEST['api_source'] = true;
1284 if (!x($_REQUEST, "source")) {
1285 $_REQUEST["source"] = api_source();
1288 // call out normal post function
1291 // this should output the last post (the one we just posted).
1292 return api_status_show($type);
1295 /// @TODO move to top of file or somewhere better
1296 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1297 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1300 * Uploads an image to Friendica.
1303 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1305 function api_media_upload()
1309 if (api_user() === false) {
1311 throw new ForbiddenException();
1316 if (!x($_FILES, 'media')) {
1318 throw new BadRequestException("No media.");
1321 $media = wall_upload_post($a, false);
1324 throw new InternalServerErrorException();
1328 $returndata["media_id"] = $media["id"];
1329 $returndata["media_id_string"] = (string)$media["id"];
1330 $returndata["size"] = $media["size"];
1331 $returndata["image"] = ["w" => $media["width"],
1332 "h" => $media["height"],
1333 "image_type" => $media["type"]];
1335 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1337 return ["media" => $returndata];
1340 /// @TODO move to top of file or somewhere better
1341 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1345 * @param string $type Return type (atom, rss, xml, json)
1347 * @return array|string
1349 function api_status_show($type)
1353 $user_info = api_get_user($a);
1355 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1357 if ($type == "raw") {
1358 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1363 // get last public wall message
1367 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1368 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1369 AND `item`.`type` != 'activity' $privacy_sql
1370 ORDER BY `item`.`id` DESC
1372 intval($user_info['cid']),
1374 dbesc($user_info['url']),
1375 dbesc(normalise_link($user_info['url'])),
1376 dbesc($user_info['url']),
1377 dbesc(normalise_link($user_info['url']))
1380 if (DBM::is_result($lastwall)) {
1381 $lastwall = $lastwall[0];
1383 $in_reply_to = api_in_reply_to($lastwall);
1385 $converted = api_convert_item($lastwall);
1387 if ($type == "xml") {
1388 $geo = "georss:point";
1394 'created_at' => api_date($lastwall['created']),
1395 'id' => intval($lastwall['id']),
1396 'id_str' => (string) $lastwall['id'],
1397 'text' => $converted["text"],
1398 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1399 'truncated' => false,
1400 'in_reply_to_status_id' => $in_reply_to['status_id'],
1401 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1402 'in_reply_to_user_id' => $in_reply_to['user_id'],
1403 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1404 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1405 'user' => $user_info,
1407 'coordinates' => "",
1409 'contributors' => "",
1410 'is_quote_status' => false,
1411 'retweet_count' => 0,
1412 'favorite_count' => 0,
1413 'favorited' => $lastwall['starred'] ? true : false,
1414 'retweeted' => false,
1415 'possibly_sensitive' => false,
1417 'statusnet_html' => $converted["html"],
1418 'statusnet_conversation_id' => $lastwall['parent'],
1419 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1422 if (count($converted["attachments"]) > 0) {
1423 $status_info["attachments"] = $converted["attachments"];
1426 if (count($converted["entities"]) > 0) {
1427 $status_info["entities"] = $converted["entities"];
1430 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1431 $status_info["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1432 } elseif (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1433 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['item_network'], $user_info['url']).')');
1436 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1437 unset($status_info["user"]["uid"]);
1438 unset($status_info["user"]["self"]);
1441 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1443 if ($type == "raw") {
1444 return $status_info;
1447 return api_format_data("statuses", $type, ['status' => $status_info]);
1451 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1452 * The author's most recent status will be returned inline.
1454 * @param string $type Return type (atom, rss, xml, json)
1455 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1457 function api_users_show($type)
1461 $user_info = api_get_user($a);
1465 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1466 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1467 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1468 AND `type`!='activity'
1469 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1473 dbesc(ACTIVITY_POST),
1474 intval($user_info['cid']),
1475 dbesc($user_info['url']),
1476 dbesc(normalise_link($user_info['url'])),
1477 dbesc($user_info['url']),
1478 dbesc(normalise_link($user_info['url']))
1481 if (DBM::is_result($lastwall)) {
1482 $lastwall = $lastwall[0];
1484 $in_reply_to = api_in_reply_to($lastwall);
1486 $converted = api_convert_item($lastwall);
1488 if ($type == "xml") {
1489 $geo = "georss:point";
1494 $user_info['status'] = [
1495 'text' => $converted["text"],
1496 'truncated' => false,
1497 'created_at' => api_date($lastwall['created']),
1498 'in_reply_to_status_id' => $in_reply_to['status_id'],
1499 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1500 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1501 'id' => intval($lastwall['contact-id']),
1502 'id_str' => (string) $lastwall['contact-id'],
1503 'in_reply_to_user_id' => $in_reply_to['user_id'],
1504 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1505 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1507 'favorited' => $lastwall['starred'] ? true : false,
1508 'statusnet_html' => $converted["html"],
1509 'statusnet_conversation_id' => $lastwall['parent'],
1510 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1513 if (count($converted["attachments"]) > 0) {
1514 $user_info["status"]["attachments"] = $converted["attachments"];
1517 if (count($converted["entities"]) > 0) {
1518 $user_info["status"]["entities"] = $converted["entities"];
1521 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1522 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1525 if (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1526 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) . ')');
1530 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1531 unset($user_info["uid"]);
1532 unset($user_info["self"]);
1534 return api_format_data("user", $type, ['user' => $user_info]);
1537 /// @TODO move to top of file or somewhere better
1538 api_register_func('api/users/show', 'api_users_show');
1539 api_register_func('api/externalprofile/show', 'api_users_show');
1542 * Search a public user account.
1544 * @param string $type Return type (atom, rss, xml, json)
1546 * @return array|string
1547 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1549 function api_users_search($type)
1555 if (x($_GET, 'q')) {
1556 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1558 if (!DBM::is_result($r)) {
1559 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1562 if (DBM::is_result($r)) {
1564 foreach ($r as $user) {
1565 $user_info = api_get_user($a, $user["id"]);
1567 if ($type == "xml") {
1568 $userlist[$k++.":user"] = $user_info;
1570 $userlist[] = $user_info;
1573 $userlist = ["users" => $userlist];
1575 throw new BadRequestException("User not found.");
1578 throw new BadRequestException("User not found.");
1581 return api_format_data("users", $type, $userlist);
1584 /// @TODO move to top of file or somewhere better
1585 api_register_func('api/users/search', 'api_users_search');
1588 * Return user objects
1590 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1592 * @param string $type Return format: json or xml
1594 * @return array|string
1595 * @throws NotFoundException if the results are empty.
1597 function api_users_lookup($type)
1601 if (x($_REQUEST['user_id'])) {
1602 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1604 $users[] = api_get_user(get_app(), $id);
1609 if (empty($users)) {
1610 throw new NotFoundException;
1613 return api_format_data("users", $type, ['users' => $users]);
1616 /// @TODO move to top of file or somewhere better
1617 api_register_func('api/users/lookup', 'api_users_lookup', true);
1620 * Returns statuses that match a specified query.
1622 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1624 * @param string $type Return format: json, xml, atom, rss
1626 * @return array|string
1627 * @throws BadRequestException if the "q" parameter is missing.
1629 function api_search($type)
1634 if (!x($_REQUEST, 'q')) {
1635 throw new BadRequestException("q parameter is required.");
1638 if (x($_REQUEST, 'rpp')) {
1639 $count = $_REQUEST['rpp'];
1640 } elseif (x($_REQUEST, 'count')) {
1641 $count = $_REQUEST['count'];
1646 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1647 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1648 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1650 $start = $page * $count;
1653 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1657 "SELECT ".item_fieldlists()."
1658 FROM `item` ".item_joins()."
1659 WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1660 AND `item`.`body` LIKE CONCAT('%',?,'%')
1663 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
1669 $data['status'] = api_format_items(dba::inArray($r), api_get_user(get_app()));
1671 return api_format_data("statuses", $type, $data);
1674 /// @TODO move to top of file or somewhere better
1675 api_register_func('api/search/tweets', 'api_search', true);
1676 api_register_func('api/search', 'api_search', true);
1679 * Returns the most recent statuses posted by the user and the users they follow.
1681 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1683 * @param string $type Return type (atom, rss, xml, json)
1685 * @todo Optional parameters
1686 * @todo Add reply info
1688 function api_statuses_home_timeline($type)
1692 if (api_user() === false) {
1693 throw new ForbiddenException();
1696 unset($_REQUEST["user_id"]);
1697 unset($_GET["user_id"]);
1699 unset($_REQUEST["screen_name"]);
1700 unset($_GET["screen_name"]);
1702 $user_info = api_get_user($a);
1703 // get last newtork messages
1706 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1707 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1711 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1712 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1713 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1714 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1715 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1717 $start = $page * $count;
1721 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1723 if ($exclude_replies > 0) {
1724 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1726 if ($conversation_id > 0) {
1727 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1731 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1732 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1733 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1734 `contact`.`id` AS `cid`
1736 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1737 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1738 WHERE `item`.`uid` = %d AND `verb` = '%s'
1739 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1742 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1744 dbesc(ACTIVITY_POST),
1750 $ret = api_format_items($r, $user_info, false, $type);
1752 // Set all posts from the query above to seen
1754 foreach ($r as $item) {
1755 $idarray[] = intval($item["id"]);
1758 $idlist = implode(",", $idarray);
1760 if ($idlist != "") {
1761 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1764 q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1768 $data = ['status' => $ret];
1772 $data = api_rss_extra($a, $data, $user_info);
1776 return api_format_data("statuses", $type, $data);
1779 /// @TODO move to top of file or somewhere better
1780 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1781 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1784 * Returns the most recent statuses from public users.
1786 * @param string $type Return type (atom, rss, xml, json)
1788 * @return array|string
1790 function api_statuses_public_timeline($type)
1794 if (api_user() === false) {
1795 throw new ForbiddenException();
1798 $user_info = api_get_user($a);
1799 // get last newtork messages
1802 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1803 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1807 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1808 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1809 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1810 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1811 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1813 $start = $page * $count;
1816 if ($exclude_replies && !$conversation_id) {
1818 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1822 "SELECT " . item_fieldlists() . "
1824 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1825 " . item_joins() . "
1826 STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1827 AND NOT `user`.`hidewall`
1829 AND NOT `thread`.`private`
1831 AND `thread`.`visible`
1832 AND NOT `thread`.`deleted`
1833 AND NOT `thread`.`moderated`
1834 AND `thread`.`iid` > ?
1836 ORDER BY `thread`.`iid` DESC
1837 LIMIT " . intval($start) . ", " . intval($count),
1842 $r = dba::inArray($r);
1845 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1847 if ($conversation_id > 0) {
1848 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1852 "SELECT " . item_fieldlists() . "
1854 " . item_joins() . "
1855 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1856 AND NOT `user`.`hidewall`
1858 AND NOT `item`.`private`
1860 AND `item`.`visible`
1861 AND NOT `item`.`deleted`
1862 AND NOT `item`.`moderated`
1865 ORDER BY `item`.`id` DESC
1866 LIMIT " . intval($start) . ", " . intval($count),
1871 $r = dba::inArray($r);
1874 $ret = api_format_items($r, $user_info, false, $type);
1876 $data = ['status' => $ret];
1880 $data = api_rss_extra($a, $data, $user_info);
1884 return api_format_data("statuses", $type, $data);
1887 /// @TODO move to top of file or somewhere better
1888 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1891 * Returns the most recent statuses posted by users this node knows about.
1893 * @brief Returns the list of public federated posts this node knows about
1895 * @param string $type Return format: json, xml, atom, rss
1896 * @return array|string
1897 * @throws ForbiddenException
1899 function api_statuses_networkpublic_timeline($type)
1903 if (api_user() === false) {
1904 throw new ForbiddenException();
1907 $user_info = api_get_user($a);
1909 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1910 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1913 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1914 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1918 $start = ($page - 1) * $count;
1922 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1926 "SELECT " . item_fieldlists() . "
1928 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1929 " . item_joins() . "
1930 WHERE `thread`.`uid` = 0
1932 AND NOT `thread`.`private`
1933 AND `thread`.`visible`
1934 AND NOT `thread`.`deleted`
1935 AND NOT `thread`.`moderated`
1936 AND `thread`.`iid` > ?
1938 ORDER BY `thread`.`iid` DESC
1939 LIMIT " . intval($start) . ", " . intval($count),
1944 $r = dba::inArray($r);
1946 $ret = api_format_items($r, $user_info, false, $type);
1948 $data = ['status' => $ret];
1952 $data = api_rss_extra($a, $data, $user_info);
1956 return api_format_data("statuses", $type, $data);
1959 /// @TODO move to top of file or somewhere better
1960 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1963 * Returns a single status.
1965 * @param string $type Return type (atom, rss, xml, json)
1967 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1969 function api_statuses_show($type)
1973 if (api_user() === false) {
1974 throw new ForbiddenException();
1977 $user_info = api_get_user($a);
1980 $id = intval($a->argv[3]);
1983 $id = intval($_REQUEST["id"]);
1988 $id = intval($a->argv[4]);
1991 logger('API: api_statuses_show: ' . $id);
1993 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1996 if ($conversation) {
1997 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1999 $sql_extra .= " AND `item`.`id` = %d";
2003 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2004 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2005 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2006 `contact`.`id` AS `cid`
2008 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2009 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2010 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2011 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2014 dbesc(ACTIVITY_POST),
2018 /// @TODO How about copying this to above methods which don't check $r ?
2019 if (!DBM::is_result($r)) {
2020 throw new BadRequestException("There is no status with this id.");
2023 $ret = api_format_items($r, $user_info, false, $type);
2025 if ($conversation) {
2026 $data = ['status' => $ret];
2027 return api_format_data("statuses", $type, $data);
2029 $data = ['status' => $ret[0]];
2030 return api_format_data("status", $type, $data);
2034 /// @TODO move to top of file or somewhere better
2035 api_register_func('api/statuses/show', 'api_statuses_show', true);
2039 * @param string $type Return type (atom, rss, xml, json)
2041 * @todo nothing to say?
2043 function api_conversation_show($type)
2047 if (api_user() === false) {
2048 throw new ForbiddenException();
2051 $user_info = api_get_user($a);
2054 $id = intval($a->argv[3]);
2055 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2056 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
2060 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2061 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2063 $start = $page*$count;
2066 $id = intval($_REQUEST["id"]);
2071 $id = intval($a->argv[4]);
2074 logger('API: api_conversation_show: '.$id);
2076 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
2077 if (DBM::is_result($r)) {
2078 $id = $r[0]["parent"];
2084 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2087 // Not sure why this query was so complicated. We should keep it here for a while,
2088 // just to make sure that we really don't need it.
2089 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
2090 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
2093 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2094 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2095 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2096 `contact`.`id` AS `cid`
2098 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2099 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2100 WHERE `item`.`parent` = %d AND `item`.`visible`
2101 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2102 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2103 AND `item`.`id`>%d $sql_extra
2104 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2107 dbesc(ACTIVITY_POST),
2113 if (!DBM::is_result($r)) {
2114 throw new BadRequestException("There is no status with this id.");
2117 $ret = api_format_items($r, $user_info, false, $type);
2119 $data = ['status' => $ret];
2120 return api_format_data("statuses", $type, $data);
2123 /// @TODO move to top of file or somewhere better
2124 api_register_func('api/conversation/show', 'api_conversation_show', true);
2125 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2130 * @param string $type Return type (atom, rss, xml, json)
2132 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2134 function api_statuses_repeat($type)
2140 if (api_user() === false) {
2141 throw new ForbiddenException();
2147 $id = intval($a->argv[3]);
2150 $id = intval($_REQUEST["id"]);
2155 $id = intval($a->argv[4]);
2158 logger('API: api_statuses_repeat: '.$id);
2161 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2162 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2163 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2164 `contact`.`id` AS `cid`
2166 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2167 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2168 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2169 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2170 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2171 AND `item`.`id`=%d",
2175 /// @TODO other style than above functions!
2176 if (DBM::is_result($r) && $r[0]['body'] != "") {
2177 if (strpos($r[0]['body'], "[/share]") !== false) {
2178 $pos = strpos($r[0]['body'], "[share");
2179 $post = substr($r[0]['body'], $pos);
2181 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2183 $post .= $r[0]['body'];
2184 $post .= "[/share]";
2186 $_REQUEST['body'] = $post;
2187 $_REQUEST['profile_uid'] = api_user();
2188 $_REQUEST['type'] = 'wall';
2189 $_REQUEST['api_source'] = true;
2191 if (!x($_REQUEST, "source")) {
2192 $_REQUEST["source"] = api_source();
2197 throw new ForbiddenException();
2200 // this should output the last post (the one we just posted).
2202 return api_status_show($type);
2205 /// @TODO move to top of file or somewhere better
2206 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2209 * Destroys a specific status.
2211 * @param string $type Return type (atom, rss, xml, json)
2213 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2215 function api_statuses_destroy($type)
2219 if (api_user() === false) {
2220 throw new ForbiddenException();
2226 $id = intval($a->argv[3]);
2229 $id = intval($_REQUEST["id"]);
2234 $id = intval($a->argv[4]);
2237 logger('API: api_statuses_destroy: '.$id);
2239 $ret = api_statuses_show($type);
2241 Item::deleteById($id);
2246 /// @TODO move to top of file or somewhere better
2247 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2250 * Returns the most recent mentions.
2252 * @param string $type Return type (atom, rss, xml, json)
2254 * @see http://developer.twitter.com/doc/get/statuses/mentions
2256 function api_statuses_mentions($type)
2260 if (api_user() === false) {
2261 throw new ForbiddenException();
2264 unset($_REQUEST["user_id"]);
2265 unset($_GET["user_id"]);
2267 unset($_REQUEST["screen_name"]);
2268 unset($_GET["screen_name"]);
2270 $user_info = api_get_user($a);
2271 // get last newtork messages
2275 $since_id = defaults($_REQUEST, 'since_id', 0);
2276 $max_id = defaults($_REQUEST, 'max_id' , 0);
2277 $count = defaults($_REQUEST, 'count' , 20);
2278 $page = defaults($_REQUEST, 'page' , 1);
2283 $start = ($page - 1) * $count;
2285 // Ugly code - should be changed
2286 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2287 $myurl = substr($myurl, strpos($myurl, '://') + 3);
2288 $myurl = str_replace('www.', '', $myurl);
2293 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2297 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2298 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2299 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2300 `contact`.`id` AS `cid`
2301 FROM `item` FORCE INDEX (`uid_id`)
2302 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2303 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2304 WHERE `item`.`uid` = %d AND `verb` = '%s'
2305 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2306 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2307 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2310 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2312 dbesc(ACTIVITY_POST),
2313 dbesc(protect_sprintf($myurl)),
2314 dbesc(protect_sprintf($myurl)),
2321 $ret = api_format_items($r, $user_info, false, $type);
2323 $data = ['status' => $ret];
2327 $data = api_rss_extra($a, $data, $user_info);
2331 return api_format_data("statuses", $type, $data);
2334 /// @TODO move to top of file or somewhere better
2335 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2336 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2339 * Returns the most recent statuses posted by the user.
2341 * @brief Returns a user's public timeline
2343 * @param string $type Either "json" or "xml"
2344 * @return string|array
2345 * @throws ForbiddenException
2346 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2348 function api_statuses_user_timeline($type)
2352 if (api_user() === false) {
2353 throw new ForbiddenException();
2356 $user_info = api_get_user($a);
2359 "api_statuses_user_timeline: api_user: ". api_user() .
2360 "\nuser_info: ".print_r($user_info, true) .
2361 "\n_REQUEST: ".print_r($_REQUEST, true),
2365 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2366 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2367 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2368 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2371 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2372 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2376 $start = ($page - 1) * $count;
2379 if ($user_info['self'] == 1) {
2380 $sql_extra .= " AND `item`.`wall` = 1 ";
2383 if ($exclude_replies > 0) {
2384 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2387 if ($conversation_id > 0) {
2388 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2392 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2396 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2397 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2398 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2399 `contact`.`id` AS `cid`
2400 FROM `item` FORCE INDEX (`uid_contactid_id`)
2401 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2402 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2403 WHERE `item`.`uid` = %d AND `verb` = '%s'
2404 AND `item`.`contact-id` = %d
2405 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2407 AND `item`.`id` > %d
2408 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2410 dbesc(ACTIVITY_POST),
2411 intval($user_info['cid']),
2417 $ret = api_format_items($r, $user_info, true, $type);
2419 $data = ['status' => $ret];
2423 $data = api_rss_extra($a, $data, $user_info);
2427 return api_format_data("statuses", $type, $data);
2430 /// @TODO move to top of file or somewhere better
2431 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2434 * Star/unstar an item.
2435 * param: id : id of the item
2437 * @param string $type Return type (atom, rss, xml, json)
2439 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2441 function api_favorites_create_destroy($type)
2445 if (api_user() === false) {
2446 throw new ForbiddenException();
2449 // for versioned api.
2450 /// @TODO We need a better global soluton
2451 $action_argv_id = 2;
2452 if ($a->argv[1] == "1.1") {
2453 $action_argv_id = 3;
2456 if ($a->argc <= $action_argv_id) {
2457 throw new BadRequestException("Invalid request.");
2459 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2460 if ($a->argc == $action_argv_id + 2) {
2461 $itemid = intval($a->argv[$action_argv_id + 1]);
2463 /// @TODO use x() to check if _REQUEST contains 'id'
2464 $itemid = intval($_REQUEST['id']);
2467 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2469 if (!DBM::is_result($item) || count($item) == 0) {
2470 throw new BadRequestException("Invalid item.");
2475 $item[0]['starred'] = 1;
2478 $item[0]['starred'] = 0;
2481 throw new BadRequestException("Invalid action ".$action);
2484 $r = Item::update(['starred' => $item[0]['starred']], ['id' => $itemid]);
2487 throw new InternalServerErrorException("DB error");
2491 $user_info = api_get_user($a);
2492 $rets = api_format_items($item, $user_info, false, $type);
2495 $data = ['status' => $ret];
2499 $data = api_rss_extra($a, $data, $user_info);
2502 return api_format_data("status", $type, $data);
2505 /// @TODO move to top of file or somewhere better
2506 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2507 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2510 * Returns the most recent favorite statuses.
2512 * @param string $type Return type (atom, rss, xml, json)
2514 * @return string|array
2516 function api_favorites($type)
2522 if (api_user() === false) {
2523 throw new ForbiddenException();
2528 $user_info = api_get_user($a);
2530 // in friendica starred item are private
2531 // return favorites only for self
2532 logger('api_favorites: self:' . $user_info['self']);
2534 if ($user_info['self'] == 0) {
2540 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2541 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2542 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2543 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2548 $start = $page*$count;
2551 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2555 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2556 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2557 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2558 `contact`.`id` AS `cid`
2559 FROM `item`, `contact`
2560 WHERE `item`.`uid` = %d
2561 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2562 AND `item`.`starred` = 1
2563 AND `contact`.`id` = `item`.`contact-id`
2564 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2567 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2574 $ret = api_format_items($r, $user_info, false, $type);
2577 $data = ['status' => $ret];
2581 $data = api_rss_extra($a, $data, $user_info);
2584 return api_format_data("statuses", $type, $data);
2587 /// @TODO move to top of file or somewhere better
2588 api_register_func('api/favorites', 'api_favorites', true);
2592 * @param array $item
2593 * @param array $recipient
2594 * @param array $sender
2598 function api_format_messages($item, $recipient, $sender)
2600 // standard meta information
2602 'id' => $item['id'],
2603 'sender_id' => $sender['id'] ,
2605 'recipient_id' => $recipient['id'],
2606 'created_at' => api_date($item['created']),
2607 'sender_screen_name' => $sender['screen_name'],
2608 'recipient_screen_name' => $recipient['screen_name'],
2609 'sender' => $sender,
2610 'recipient' => $recipient,
2612 'friendica_seen' => $item['seen'],
2613 'friendica_parent_uri' => $item['parent-uri'],
2616 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2617 unset($ret["sender"]["uid"]);
2618 unset($ret["sender"]["self"]);
2619 unset($ret["recipient"]["uid"]);
2620 unset($ret["recipient"]["self"]);
2622 //don't send title to regular StatusNET requests to avoid confusing these apps
2623 if (x($_GET, 'getText')) {
2624 $ret['title'] = $item['title'];
2625 if ($_GET['getText'] == 'html') {
2626 $ret['text'] = BBCode::convert($item['body'], false);
2627 } elseif ($_GET['getText'] == 'plain') {
2628 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2631 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2633 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2634 unset($ret['sender']);
2635 unset($ret['recipient']);
2643 * @param array $item
2647 function api_convert_item($item)
2649 $body = $item['body'];
2650 $attachments = api_get_attachments($body);
2652 // Workaround for ostatus messages where the title is identically to the body
2653 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2654 $statusbody = trim(HTML::toPlaintext($html, 0));
2656 // handle data: images
2657 $statusbody = api_format_items_embeded_images($item, $statusbody);
2659 $statustitle = trim($item['title']);
2661 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2662 $statustext = trim($statusbody);
2664 $statustext = trim($statustitle."\n\n".$statusbody);
2667 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2668 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2671 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2673 // Workaround for clients with limited HTML parser functionality
2674 $search = ["<br>", "<blockquote>", "</blockquote>",
2675 "<h1>", "</h1>", "<h2>", "</h2>",
2676 "<h3>", "</h3>", "<h4>", "</h4>",
2677 "<h5>", "</h5>", "<h6>", "</h6>"];
2678 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2679 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2680 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2681 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2682 $statushtml = str_replace($search, $replace, $statushtml);
2684 if ($item['title'] != "") {
2685 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2689 $oldtext = $statushtml;
2690 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2691 } while ($oldtext != $statushtml);
2693 if (substr($statushtml, 0, 4) == '<br>') {
2694 $statushtml = substr($statushtml, 4);
2697 if (substr($statushtml, 0, -4) == '<br>') {
2698 $statushtml = substr($statushtml, -4);
2701 // feeds without body should contain the link
2702 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2703 $statushtml .= BBCode::convert($item['plink']);
2706 $entities = api_get_entitities($statustext, $body);
2709 "text" => $statustext,
2710 "html" => $statushtml,
2711 "attachments" => $attachments,
2712 "entities" => $entities
2718 * @param string $body
2720 * @return array|false
2722 function api_get_attachments(&$body)
2725 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2727 $URLSearchString = "^\[\]";
2728 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2736 foreach ($images[1] as $image) {
2737 $imagedata = Image::getInfoFromURL($image);
2740 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2744 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2745 foreach ($images[0] as $orig) {
2746 $body = str_replace($orig, "", $body);
2750 return $attachments;
2755 * @param string $text
2756 * @param string $bbcode
2759 * @todo Links at the first character of the post
2761 function api_get_entitities(&$text, $bbcode)
2763 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2765 if ($include_entities != "true") {
2766 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2768 foreach ($images[1] as $image) {
2769 $replace = proxy_url($image);
2770 $text = str_replace($image, $replace, $text);
2775 $bbcode = BBCode::cleanPictureLinks($bbcode);
2777 // Change pure links in text to bbcode uris
2778 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2781 $entities["hashtags"] = [];
2782 $entities["symbols"] = [];
2783 $entities["urls"] = [];
2784 $entities["user_mentions"] = [];
2786 $URLSearchString = "^\[\]";
2788 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2790 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2791 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2792 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2794 $bbcode = preg_replace(
2795 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2796 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2799 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2801 $bbcode = preg_replace(
2802 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2803 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2806 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2808 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2810 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2811 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2814 foreach ($urls[1] as $id => $url) {
2815 //$start = strpos($text, $url, $offset);
2816 $start = iconv_strpos($text, $url, 0, "UTF-8");
2817 if (!($start === false)) {
2818 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2822 ksort($ordered_urls);
2825 //foreach ($urls[1] AS $id=>$url) {
2826 foreach ($ordered_urls as $url) {
2827 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2828 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2830 $display_url = $url["title"];
2832 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2833 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2835 if (strlen($display_url) > 26) {
2836 $display_url = substr($display_url, 0, 25)."…";
2840 //$start = strpos($text, $url, $offset);
2841 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2842 if (!($start === false)) {
2843 $entities["urls"][] = ["url" => $url["url"],
2844 "expanded_url" => $url["url"],
2845 "display_url" => $display_url,
2846 "indices" => [$start, $start+strlen($url["url"])]];
2847 $offset = $start + 1;
2851 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2852 $ordered_images = [];
2853 foreach ($images[1] as $image) {
2854 //$start = strpos($text, $url, $offset);
2855 $start = iconv_strpos($text, $image, 0, "UTF-8");
2856 if (!($start === false)) {
2857 $ordered_images[$start] = $image;
2860 //$entities["media"] = array();
2863 foreach ($ordered_images as $url) {
2864 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2865 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2867 if (strlen($display_url) > 26) {
2868 $display_url = substr($display_url, 0, 25)."…";
2871 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2872 if (!($start === false)) {
2873 $image = Image::getInfoFromURL($url);
2875 // If image cache is activated, then use the following sizes:
2876 // thumb (150), small (340), medium (600) and large (1024)
2877 if (!Config::get("system", "proxy_disabled")) {
2878 $media_url = proxy_url($url);
2881 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2882 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2884 if (($image[0] > 150) || ($image[1] > 150)) {
2885 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2886 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2889 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2890 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2892 if (($image[0] > 600) || ($image[1] > 600)) {
2893 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2894 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2898 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2901 $entities["media"][] = [
2903 "id_str" => (string)$start+1,
2904 "indices" => [$start, $start+strlen($url)],
2905 "media_url" => normalise_link($media_url),
2906 "media_url_https" => $media_url,
2908 "display_url" => $display_url,
2909 "expanded_url" => $url,
2913 $offset = $start + 1;
2922 * @param array $item
2923 * @param string $text
2927 function api_format_items_embeded_images($item, $text)
2929 $text = preg_replace_callback(
2930 '|data:image/([^;]+)[^=]+=*|m',
2931 function () use ($item) {
2932 return System::baseUrl() . '/display/' . $item['guid'];
2940 * @brief return <a href='url'>name</a> as array
2942 * @param string $txt text
2947 function api_contactlink_to_array($txt)
2950 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2951 if ($r && count($match)==3) {
2953 'name' => $match[2],
2967 * @brief return likes, dislikes and attend status for item
2969 * @param array $item array
2970 * @param string $type Return type (atom, rss, xml, json)
2973 * likes => int count,
2974 * dislikes => int count
2976 function api_format_items_activities(&$item, $type = "json")
2985 'attendmaybe' => [],
2990 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2991 intval($item['uid']),
2995 foreach ($items as $i) {
2996 // not used as result should be structured like other user data
2997 //builtin_activity_puller($i, $activities);
2999 // get user data and add it to the array of the activity
3000 $user = api_get_user($a, $i['author-link']);
3001 switch ($i['verb']) {
3003 $activities['like'][] = $user;
3005 case ACTIVITY_DISLIKE:
3006 $activities['dislike'][] = $user;
3008 case ACTIVITY_ATTEND:
3009 $activities['attendyes'][] = $user;
3011 case ACTIVITY_ATTENDNO:
3012 $activities['attendno'][] = $user;
3014 case ACTIVITY_ATTENDMAYBE:
3015 $activities['attendmaybe'][] = $user;
3022 if ($type == "xml") {
3023 $xml_activities = [];
3024 foreach ($activities as $k => $v) {
3025 // change xml element from "like" to "friendica:like"
3026 $xml_activities["friendica:".$k] = $v;
3027 // add user data into xml output
3029 foreach ($v as $user) {
3030 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
3033 $activities = $xml_activities;
3041 * @brief return data from profiles
3043 * @param array $profile_row array containing data from db table 'profile'
3046 function api_format_items_profiles($profile_row)
3049 'profile_id' => $profile_row['id'],
3050 'profile_name' => $profile_row['profile-name'],
3051 'is_default' => $profile_row['is-default'] ? true : false,
3052 'hide_friends' => $profile_row['hide-friends'] ? true : false,
3053 'profile_photo' => $profile_row['photo'],
3054 'profile_thumb' => $profile_row['thumb'],
3055 'publish' => $profile_row['publish'] ? true : false,
3056 'net_publish' => $profile_row['net-publish'] ? true : false,
3057 'description' => $profile_row['pdesc'],
3058 'date_of_birth' => $profile_row['dob'],
3059 'address' => $profile_row['address'],
3060 'city' => $profile_row['locality'],
3061 'region' => $profile_row['region'],
3062 'postal_code' => $profile_row['postal-code'],
3063 'country' => $profile_row['country-name'],
3064 'hometown' => $profile_row['hometown'],
3065 'gender' => $profile_row['gender'],
3066 'marital' => $profile_row['marital'],
3067 'marital_with' => $profile_row['with'],
3068 'marital_since' => $profile_row['howlong'],
3069 'sexual' => $profile_row['sexual'],
3070 'politic' => $profile_row['politic'],
3071 'religion' => $profile_row['religion'],
3072 'public_keywords' => $profile_row['pub_keywords'],
3073 'private_keywords' => $profile_row['prv_keywords'],
3074 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
3075 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
3076 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
3077 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
3078 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
3079 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
3080 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
3081 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
3082 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
3083 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
3084 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
3085 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
3086 'homepage' => $profile_row['homepage'],
3093 * @brief format items to be returned by api
3095 * @param array $r array of items
3096 * @param array $user_info
3097 * @param bool $filter_user filter items by $user_info
3098 * @param string $type Return type (atom, rss, xml, json)
3100 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
3106 foreach ($r as $item) {
3107 localize_item($item);
3108 list($status_user, $owner_user) = api_item_get_user($a, $item);
3110 // Look if the posts are matching if they should be filtered by user id
3111 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3115 $in_reply_to = api_in_reply_to($item);
3117 $converted = api_convert_item($item);
3119 if ($type == "xml") {
3120 $geo = "georss:point";
3126 'text' => $converted["text"],
3127 'truncated' => false,
3128 'created_at'=> api_date($item['created']),
3129 'in_reply_to_status_id' => $in_reply_to['status_id'],
3130 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3131 'source' => (($item['app']) ? $item['app'] : 'web'),
3132 'id' => intval($item['id']),
3133 'id_str' => (string) intval($item['id']),
3134 'in_reply_to_user_id' => $in_reply_to['user_id'],
3135 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3136 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3138 'favorited' => $item['starred'] ? true : false,
3139 'user' => $status_user ,
3140 'friendica_owner' => $owner_user,
3141 //'entities' => NULL,
3142 'statusnet_html' => $converted["html"],
3143 'statusnet_conversation_id' => $item['parent'],
3144 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3145 'friendica_activities' => api_format_items_activities($item, $type),
3148 if (count($converted["attachments"]) > 0) {
3149 $status["attachments"] = $converted["attachments"];
3152 if (count($converted["entities"]) > 0) {
3153 $status["entities"] = $converted["entities"];
3156 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
3157 $status["source"] = ContactSelector::networkToName($item['item_network'], $user_info['url']);
3158 } elseif (($item['item_network'] != "") && (ContactSelector::networkToName($item['item_network'], $user_info['url']) != $status["source"])) {
3159 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['item_network'], $user_info['url']).')');
3163 // Retweets are only valid for top postings
3164 // It doesn't work reliable with the link if its a feed
3165 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
3167 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
3170 if ($item["id"] == $item["parent"]) {
3171 $retweeted_item = api_share_as_retweet($item);
3172 if ($retweeted_item !== false) {
3173 $retweeted_status = $status;
3175 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
3176 } catch (BadRequestException $e) {
3177 // user not found. should be found?
3178 /// @todo check if the user should be always found
3179 $retweeted_status["user"] = [];
3182 $rt_converted = api_convert_item($retweeted_item);
3184 $retweeted_status['text'] = $rt_converted["text"];
3185 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3186 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3187 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3188 $status['retweeted_status'] = $retweeted_status;
3192 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3193 unset($status["user"]["uid"]);
3194 unset($status["user"]["self"]);
3196 if ($item["coord"] != "") {
3197 $coords = explode(' ', $item["coord"]);
3198 if (count($coords) == 2) {
3199 if ($type == "json") {
3200 $status["geo"] = ['type' => 'Point',
3201 'coordinates' => [(float) $coords[0],
3202 (float) $coords[1]]];
3203 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3204 $status["georss:point"] = $item["coord"];
3214 * Returns the remaining number of API requests available to the user before the API limit is reached.
3216 * @param string $type Return type (atom, rss, xml, json)
3218 * @return array|string
3220 function api_account_rate_limit_status($type)
3222 if ($type == "xml") {
3224 'remaining-hits' => '150',
3225 '@attributes' => ["type" => "integer"],
3226 'hourly-limit' => '150',
3227 '@attributes2' => ["type" => "integer"],
3228 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3229 '@attributes3' => ["type" => "datetime"],
3230 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3231 '@attributes4' => ["type" => "integer"],
3235 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3236 'remaining_hits' => '150',
3237 'hourly_limit' => '150',
3238 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3242 return api_format_data('hash', $type, ['hash' => $hash]);
3245 /// @TODO move to top of file or somewhere better
3246 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3249 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3251 * @param string $type Return type (atom, rss, xml, json)
3253 * @return array|string
3255 function api_help_test($type)
3257 if ($type == 'xml') {
3263 return api_format_data('ok', $type, ["ok" => $ok]);
3266 /// @TODO move to top of file or somewhere better
3267 api_register_func('api/help/test', 'api_help_test', false);
3271 * @param string $type Return type (atom, rss, xml, json)
3273 * @return array|string
3275 function api_lists($type)
3278 /// @TODO $ret is not filled here?
3279 return api_format_data('lists', $type, ["lists_list" => $ret]);
3282 /// @TODO move to top of file or somewhere better
3283 api_register_func('api/lists', 'api_lists', true);
3286 * Returns all lists the user subscribes to.
3288 * @param string $type Return type (atom, rss, xml, json)
3290 * @return array|string
3291 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3293 function api_lists_list($type)
3296 /// @TODO $ret is not filled here?
3297 return api_format_data('lists', $type, ["lists_list" => $ret]);
3300 /// @TODO move to top of file or somewhere better
3301 api_register_func('api/lists/list', 'api_lists_list', true);
3304 * Considers friends and followers lists to be private and won't return
3305 * anything if any user_id parameter is passed.
3307 * @brief Returns either the friends of the follower list
3309 * @param string $qtype Either "friends" or "followers"
3310 * @return boolean|array
3311 * @throws ForbiddenException
3313 function api_statuses_f($qtype)
3317 if (api_user() === false) {
3318 throw new ForbiddenException();
3322 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3323 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3327 $start = ($page - 1) * $count;
3329 $user_info = api_get_user($a);
3331 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3332 /* this is to stop Hotot to load friends multiple times
3333 * I'm not sure if I'm missing return something or
3334 * is a bug in hotot. Workaround, meantime
3338 return array('$users' => $ret);*/
3343 if ($qtype == 'friends') {
3344 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3345 } elseif ($qtype == 'followers') {
3346 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3349 // friends and followers only for self
3350 if ($user_info['self'] == 0) {
3351 $sql_extra = " AND false ";
3354 if ($qtype == 'blocks') {
3355 $sql_filter = 'AND `blocked` AND NOT `pending`';
3356 } elseif ($qtype == 'incoming') {
3357 $sql_filter = 'AND `pending`';
3359 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3377 foreach ($r as $cid) {
3378 $user = api_get_user($a, $cid['nurl']);
3379 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3380 unset($user["uid"]);
3381 unset($user["self"]);
3388 return ['user' => $ret];
3393 * Returns the user's friends.
3395 * @brief Returns the list of friends of the provided user
3397 * @deprecated By Twitter API in favor of friends/list
3399 * @param string $type Either "json" or "xml"
3400 * @return boolean|string|array
3402 function api_statuses_friends($type)
3404 $data = api_statuses_f("friends");
3405 if ($data === false) {
3408 return api_format_data("users", $type, $data);
3412 * Returns the user's followers.
3414 * @brief Returns the list of followers of the provided user
3416 * @deprecated By Twitter API in favor of friends/list
3418 * @param string $type Either "json" or "xml"
3419 * @return boolean|string|array
3421 function api_statuses_followers($type)
3423 $data = api_statuses_f("followers");
3424 if ($data === false) {
3427 return api_format_data("users", $type, $data);
3430 /// @TODO move to top of file or somewhere better
3431 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3432 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3435 * Returns the list of blocked users
3437 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3439 * @param string $type Either "json" or "xml"
3441 * @return boolean|string|array
3443 function api_blocks_list($type)
3445 $data = api_statuses_f('blocks');
3446 if ($data === false) {
3449 return api_format_data("users", $type, $data);
3452 /// @TODO move to top of file or somewhere better
3453 api_register_func('api/blocks/list', 'api_blocks_list', true);
3456 * Returns the list of pending users IDs
3458 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3460 * @param string $type Either "json" or "xml"
3462 * @return boolean|string|array
3464 function api_friendships_incoming($type)
3466 $data = api_statuses_f('incoming');
3467 if ($data === false) {
3472 foreach ($data['user'] as $user) {
3473 $ids[] = $user['id'];
3476 return api_format_data("ids", $type, ['id' => $ids]);
3479 /// @TODO move to top of file or somewhere better
3480 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3483 * Returns the instance's configuration information.
3485 * @param string $type Return type (atom, rss, xml, json)
3487 * @return array|string
3489 function api_statusnet_config($type)
3493 $name = $a->config['sitename'];
3494 $server = $a->get_hostname();
3495 $logo = System::baseUrl() . '/images/friendica-64.png';
3496 $email = $a->config['admin_email'];
3497 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3498 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3499 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3500 if ($a->config['api_import_size']) {
3501 $textlimit = (string) $a->config['api_import_size'];
3503 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3504 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3507 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3508 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3509 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3510 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3511 'shorturllength' => '30',
3513 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3514 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3515 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3516 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3521 return api_format_data('config', $type, ['config' => $config]);
3524 /// @TODO move to top of file or somewhere better
3525 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3526 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3530 * @param string $type Return type (atom, rss, xml, json)
3532 * @return array|string
3534 function api_statusnet_version($type)
3537 $fake_statusnet_version = "0.9.7";
3539 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3542 /// @TODO move to top of file or somewhere better
3543 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3544 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3548 * @param string $type Return type (atom, rss, xml, json)
3550 * @todo use api_format_data() to return data
3552 function api_ff_ids($type)
3555 throw new ForbiddenException();
3562 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3565 "SELECT `pcontact`.`id` FROM `contact`
3566 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3567 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3570 if (!DBM::is_result($r)) {
3575 foreach ($r as $rr) {
3576 if ($stringify_ids) {
3579 $ids[] = intval($rr['id']);
3583 return api_format_data("ids", $type, ['id' => $ids]);
3587 * Returns the ID of every user the user is following.
3589 * @param string $type Return type (atom, rss, xml, json)
3591 * @return array|string
3592 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3594 function api_friends_ids($type)
3596 return api_ff_ids($type);
3600 * Returns the ID of every user following the user.
3602 * @param string $type Return type (atom, rss, xml, json)
3604 * @return array|string
3605 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3607 function api_followers_ids($type)
3609 return api_ff_ids($type);
3612 /// @TODO move to top of file or somewhere better
3613 api_register_func('api/friends/ids', 'api_friends_ids', true);
3614 api_register_func('api/followers/ids', 'api_followers_ids', true);
3617 * Sends a new direct message.
3619 * @param string $type Return type (atom, rss, xml, json)
3621 * @return array|string
3622 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3624 function api_direct_messages_new($type)
3629 if (api_user() === false) {
3630 throw new ForbiddenException();
3633 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3637 $sender = api_get_user($a);
3639 if ($_POST['screen_name']) {
3641 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3643 dbesc($_POST['screen_name'])
3646 // Selecting the id by priority, friendica first
3647 api_best_nickname($r);
3649 $recipient = api_get_user($a, $r[0]['nurl']);
3651 $recipient = api_get_user($a, $_POST['user_id']);
3656 if (x($_REQUEST, 'replyto')) {
3658 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3660 intval($_REQUEST['replyto'])
3662 $replyto = $r[0]['parent-uri'];
3663 $sub = $r[0]['title'];
3665 if (x($_REQUEST, 'title')) {
3666 $sub = $_REQUEST['title'];
3668 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3672 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3675 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3676 $ret = api_format_messages($r[0], $recipient, $sender);
3678 $ret = ["error"=>$id];
3681 $data = ['direct_message'=>$ret];
3686 $data = api_rss_extra($a, $data, $sender);
3689 return api_format_data("direct-messages", $type, $data);
3692 /// @TODO move to top of file or somewhere better
3693 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3696 * Destroys a direct message.
3698 * @brief delete a direct_message from mail table through api
3700 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3702 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3704 function api_direct_messages_destroy($type)
3708 if (api_user() === false) {
3709 throw new ForbiddenException();
3713 $user_info = api_get_user($a);
3715 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3717 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3718 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3719 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3721 $uid = $user_info['uid'];
3722 // error if no id or parenturi specified (for clients posting parent-uri as well)
3723 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3724 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3725 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3728 // BadRequestException if no id specified (for clients using Twitter API)
3730 throw new BadRequestException('Message id not specified');
3733 // add parent-uri to sql command if specified by calling app
3734 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3736 // get data of the specified message id
3738 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3743 // error message if specified id is not in database
3744 if (!DBM::is_result($r)) {
3745 if ($verbose == "true") {
3746 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3747 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3749 /// @todo BadRequestException ok for Twitter API clients?
3750 throw new BadRequestException('message id not in database');
3755 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3760 if ($verbose == "true") {
3763 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3764 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3766 $answer = ['result' => 'error', 'message' => 'unknown error'];
3767 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3770 /// @todo return JSON data like Twitter API not yet implemented
3773 /// @TODO move to top of file or somewhere better
3774 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3778 * @param string $type Return type (atom, rss, xml, json)
3779 * @param string $box
3780 * @param string $verbose
3782 * @return array|string
3784 function api_direct_messages_box($type, $box, $verbose)
3788 if (api_user() === false) {
3789 throw new ForbiddenException();
3793 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3794 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3799 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3800 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3802 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3803 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3806 unset($_REQUEST["user_id"]);
3807 unset($_GET["user_id"]);
3809 unset($_REQUEST["screen_name"]);
3810 unset($_GET["screen_name"]);
3812 $user_info = api_get_user($a);
3813 $profile_url = $user_info["url"];
3816 $start = $page * $count;
3821 if ($box=="sentbox") {
3822 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3823 } elseif ($box == "conversation") {
3824 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3825 } elseif ($box == "all") {
3826 $sql_extra = "true";
3827 } elseif ($box == "inbox") {
3828 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3832 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3835 if ($user_id != "") {
3836 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3837 } elseif ($screen_name !="") {
3838 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3842 "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",
3848 if ($verbose == "true" && !DBM::is_result($r)) {
3849 $answer = ['result' => 'error', 'message' => 'no mails available'];
3850 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3854 foreach ($r as $item) {
3855 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3856 $recipient = $user_info;
3857 $sender = api_get_user($a, normalise_link($item['contact-url']));
3858 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3859 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3860 $sender = $user_info;
3863 $ret[] = api_format_messages($item, $recipient, $sender);
3867 $data = ['direct_message' => $ret];
3871 $data = api_rss_extra($a, $data, $user_info);
3874 return api_format_data("direct-messages", $type, $data);
3878 * Returns the most recent direct messages sent by the user.
3880 * @param string $type Return type (atom, rss, xml, json)
3882 * @return array|string
3883 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3885 function api_direct_messages_sentbox($type)
3887 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3888 return api_direct_messages_box($type, "sentbox", $verbose);
3892 * Returns the most recent direct messages sent to the user.
3894 * @param string $type Return type (atom, rss, xml, json)
3896 * @return array|string
3897 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3899 function api_direct_messages_inbox($type)
3901 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3902 return api_direct_messages_box($type, "inbox", $verbose);
3907 * @param string $type Return type (atom, rss, xml, json)
3909 * @return array|string
3911 function api_direct_messages_all($type)
3913 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3914 return api_direct_messages_box($type, "all", $verbose);
3919 * @param string $type Return type (atom, rss, xml, json)
3921 * @return array|string
3923 function api_direct_messages_conversation($type)
3925 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3926 return api_direct_messages_box($type, "conversation", $verbose);
3929 /// @TODO move to top of file or somewhere better
3930 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3931 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3932 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3933 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3936 * Returns an OAuth Request Token.
3938 * @see https://oauth.net/core/1.0/#auth_step1
3940 function api_oauth_request_token()
3942 $oauth1 = new FKOAuth1();
3944 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3945 } catch (Exception $e) {
3946 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3954 * Returns an OAuth Access Token.
3956 * @return array|string
3957 * @see https://oauth.net/core/1.0/#auth_step3
3959 function api_oauth_access_token()
3961 $oauth1 = new FKOAuth1();
3963 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3964 } catch (Exception $e) {
3965 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3972 /// @TODO move to top of file or somewhere better
3973 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3974 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3978 * @brief delete a complete photoalbum with all containing photos from database through api
3980 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3983 function api_fr_photoalbum_delete($type)
3985 if (api_user() === false) {
3986 throw new ForbiddenException();
3989 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3991 // we do not allow calls without album string
3993 throw new BadRequestException("no albumname specified");
3995 // check if album is existing
3997 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4001 if (!DBM::is_result($r)) {
4002 throw new BadRequestException("album not available");
4005 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4006 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4007 foreach ($r as $rr) {
4009 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4010 intval(local_user()),
4011 dbesc($rr['resource-id'])
4014 if (!DBM::is_result($photo_item)) {
4015 throw new InternalServerErrorException("problem with deleting items occured");
4017 Item::deleteById($photo_item[0]['id']);
4020 // now let's delete all photos from the album
4021 $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
4023 // return success of deletion or error message
4025 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4026 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4028 throw new InternalServerErrorException("unknown error - deleting from database failed");
4033 * @brief update the name of the album for all photos of an album
4035 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4038 function api_fr_photoalbum_update($type)
4040 if (api_user() === false) {
4041 throw new ForbiddenException();
4044 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
4045 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
4047 // we do not allow calls without album string
4049 throw new BadRequestException("no albumname specified");
4051 if ($album_new == "") {
4052 throw new BadRequestException("no new albumname specified");
4054 // check if album is existing
4056 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4060 if (!DBM::is_result($r)) {
4061 throw new BadRequestException("album not available");
4063 // now let's update all photos to the albumname
4065 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
4071 // return success of updating or error message
4073 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4074 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4076 throw new InternalServerErrorException("unknown error - updating in database failed");
4082 * @brief list all photos of the authenticated user
4084 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4087 function api_fr_photos_list($type)
4089 if (api_user() === false) {
4090 throw new ForbiddenException();
4093 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4094 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4095 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4096 intval(local_user())
4099 'image/jpeg' => 'jpg',
4100 'image/png' => 'png',
4101 'image/gif' => 'gif'
4103 $data = ['photo'=>[]];
4104 if (DBM::is_result($r)) {
4105 foreach ($r as $rr) {
4107 $photo['id'] = $rr['resource-id'];
4108 $photo['album'] = $rr['album'];
4109 $photo['filename'] = $rr['filename'];
4110 $photo['type'] = $rr['type'];
4111 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4112 $photo['created'] = $rr['created'];
4113 $photo['edited'] = $rr['edited'];
4114 $photo['desc'] = $rr['desc'];
4116 if ($type == "xml") {
4117 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4119 $photo['thumb'] = $thumb;
4120 $data['photo'][] = $photo;
4124 return api_format_data("photos", $type, $data);
4128 * @brief upload a new photo or change an existing photo
4130 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4133 function api_fr_photo_create_update($type)
4135 if (api_user() === false) {
4136 throw new ForbiddenException();
4139 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4140 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4141 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4142 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4143 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4144 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4145 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4146 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4147 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4149 // do several checks on input parameters
4150 // we do not allow calls without album string
4151 if ($album == null) {
4152 throw new BadRequestException("no albumname specified");
4154 // if photo_id == null --> we are uploading a new photo
4155 if ($photo_id == null) {
4158 // error if no media posted in create-mode
4159 if (!x($_FILES, 'media')) {
4161 throw new BadRequestException("no media data submitted");
4164 // album_new will be ignored in create-mode
4169 // check if photo is existing in database
4171 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4176 if (!DBM::is_result($r)) {
4177 throw new BadRequestException("photo not available");
4181 // checks on acl strings provided by clients
4182 $acl_input_error = false;
4183 $acl_input_error |= check_acl_input($allow_cid);
4184 $acl_input_error |= check_acl_input($deny_cid);
4185 $acl_input_error |= check_acl_input($allow_gid);
4186 $acl_input_error |= check_acl_input($deny_gid);
4187 if ($acl_input_error) {
4188 throw new BadRequestException("acl data invalid");
4190 // now let's upload the new media in create-mode
4191 if ($mode == "create") {
4192 $media = $_FILES['media'];
4193 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4195 // return success of updating or error message
4196 if (!is_null($data)) {
4197 return api_format_data("photo_create", $type, $data);
4199 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4203 // now let's do the changes in update-mode
4204 if ($mode == "update") {
4207 if (!is_null($desc)) {
4208 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4211 if (!is_null($album_new)) {
4212 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4215 if (!is_null($allow_cid)) {
4216 $allow_cid = trim($allow_cid);
4217 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4220 if (!is_null($deny_cid)) {
4221 $deny_cid = trim($deny_cid);
4222 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4225 if (!is_null($allow_gid)) {
4226 $allow_gid = trim($allow_gid);
4227 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4230 if (!is_null($deny_gid)) {
4231 $deny_gid = trim($deny_gid);
4232 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4236 if ($sql_extra != "") {
4237 $nothingtodo = false;
4239 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4241 DateTimeFormat::utcNow(), // update edited timestamp
4247 $nothingtodo = true;
4250 if (x($_FILES, 'media')) {
4251 $nothingtodo = false;
4252 $media = $_FILES['media'];
4253 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4254 if (!is_null($data)) {
4255 return api_format_data("photo_update", $type, $data);
4259 // return success of updating or error message
4261 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4262 return api_format_data("photo_update", $type, ['$result' => $answer]);
4265 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4266 return api_format_data("photo_update", $type, ['$result' => $answer]);
4268 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4271 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4276 * @brief delete a single photo from the database through api
4278 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4281 function api_fr_photo_delete($type)
4283 if (api_user() === false) {
4284 throw new ForbiddenException();
4287 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4289 // do several checks on input parameters
4290 // we do not allow calls without photo id
4291 if ($photo_id == null) {
4292 throw new BadRequestException("no photo_id specified");
4294 // check if photo is existing in database
4296 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4300 if (!DBM::is_result($r)) {
4301 throw new BadRequestException("photo not available");
4303 // now we can perform on the deletion of the photo
4304 $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4306 // return success of deletion or error message
4308 // retrieve the id of the parent element (the photo element)
4310 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4311 intval(local_user()),
4315 if (!DBM::is_result($photo_item)) {
4316 throw new InternalServerErrorException("problem with deleting items occured");
4318 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4319 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4320 Item::deleteById($photo_item[0]['id']);
4322 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4323 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4325 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4331 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4333 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4334 * @return string|array
4336 function api_fr_photo_detail($type)
4338 if (api_user() === false) {
4339 throw new ForbiddenException();
4341 if (!x($_REQUEST, 'photo_id')) {
4342 throw new BadRequestException("No photo id.");
4345 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4346 $photo_id = $_REQUEST['photo_id'];
4348 // prepare json/xml output with data from database for the requested photo
4349 $data = prepare_photo_data($type, $scale, $photo_id);
4351 return api_format_data("photo_detail", $type, $data);
4356 * Updates the user’s profile image.
4358 * @brief updates the profile image for the user (either a specified profile or the default profile)
4360 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4363 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4365 function api_account_update_profile_image($type)
4367 if (api_user() === false) {
4368 throw new ForbiddenException();
4371 $profileid = defaults($_REQUEST, 'profile_id', 0);
4373 // error if image data is missing
4374 if (!x($_FILES, 'image')) {
4375 throw new BadRequestException("no media data submitted");
4378 // check if specified profile id is valid
4379 if ($profileid != 0) {
4381 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4385 // error message if specified profile id is not in database
4386 if (!DBM::is_result($r)) {
4387 throw new BadRequestException("profile_id not available");
4389 $is_default_profile = $r['profile'];
4391 $is_default_profile = 1;
4394 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4396 if (x($_FILES, 'image')) {
4397 $media = $_FILES['image'];
4398 } elseif (x($_FILES, 'media')) {
4399 $media = $_FILES['media'];
4401 // save new profile image
4402 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4405 if (is_array($media['type'])) {
4406 $filetype = $media['type'][0];
4408 $filetype = $media['type'];
4410 if ($filetype == "image/jpeg") {
4412 } elseif ($filetype == "image/png") {
4415 // change specified profile or all profiles to the new resource-id
4416 if ($is_default_profile) {
4418 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4419 dbesc($data['photo']['id']),
4420 intval(local_user())
4424 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
4425 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4426 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4427 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4428 intval(local_user())
4432 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4433 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4434 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4435 intval($_REQUEST['profile']),
4436 intval(local_user())
4440 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4441 // so that browsers will do a cache update unconditionally
4444 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4445 dbesc(DateTimeFormat::utcNow()),
4446 intval(local_user())
4449 // Update global directory in background
4450 //$user = api_get_user(get_app());
4451 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4452 if ($url && strlen(Config::get('system', 'directory'))) {
4453 Worker::add(PRIORITY_LOW, "Directory", $url);
4456 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4458 // output for client
4460 return api_account_verify_credentials($type);
4462 // SaveMediaToDatabase failed for some reason
4463 throw new InternalServerErrorException("image upload failed");
4467 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4468 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4469 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4470 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4471 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4472 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4473 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4474 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4475 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4478 * Update user profile
4480 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4482 * @return array|string
4484 function api_account_update_profile($type)
4486 $local_user = api_user();
4487 $api_user = api_get_user(get_app());
4489 if (!empty($_POST['name'])) {
4490 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4491 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4492 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4493 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4496 if (isset($_POST['description'])) {
4497 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4498 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4499 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4502 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4503 // Update global directory in background
4504 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4505 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4508 return api_account_verify_credentials($type);
4511 /// @TODO move to top of file or somewhere better
4512 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4516 * @param string $acl_string
4518 function check_acl_input($acl_string)
4520 if ($acl_string == null || $acl_string == " ") {
4523 $contact_not_found = false;
4525 // split <x><y><z> into array of cid's
4526 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4528 // check for each cid if it is available on server
4529 $cid_array = $array[0];
4530 foreach ($cid_array as $cid) {
4531 $cid = str_replace("<", "", $cid);
4532 $cid = str_replace(">", "", $cid);
4534 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4538 $contact_not_found |= !DBM::is_result($contact);
4540 return $contact_not_found;
4545 * @param string $mediatype
4546 * @param array $media
4547 * @param string $type
4548 * @param string $album
4549 * @param string $allow_cid
4550 * @param string $deny_cid
4551 * @param string $allow_gid
4552 * @param string $deny_gid
4553 * @param string $desc
4554 * @param integer $profile
4555 * @param boolean $visibility
4556 * @param string $photo_id
4558 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)
4566 if (is_array($media)) {
4567 if (is_array($media['tmp_name'])) {
4568 $src = $media['tmp_name'][0];
4570 $src = $media['tmp_name'];
4572 if (is_array($media['name'])) {
4573 $filename = basename($media['name'][0]);
4575 $filename = basename($media['name']);
4577 if (is_array($media['size'])) {
4578 $filesize = intval($media['size'][0]);
4580 $filesize = intval($media['size']);
4582 if (is_array($media['type'])) {
4583 $filetype = $media['type'][0];
4585 $filetype = $media['type'];
4589 if ($filetype == "") {
4590 $filetype=Image::guessType($filename);
4592 $imagedata = getimagesize($src);
4594 $filetype = $imagedata['mime'];
4597 "File upload src: " . $src . " - filename: " . $filename .
4598 " - size: " . $filesize . " - type: " . $filetype,
4602 // check if there was a php upload error
4603 if ($filesize == 0 && $media['error'] == 1) {
4604 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4606 // check against max upload size within Friendica instance
4607 $maximagesize = Config::get('system', 'maximagesize');
4608 if ($maximagesize && ($filesize > $maximagesize)) {
4609 $formattedBytes = formatBytes($maximagesize);
4610 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4613 // create Photo instance with the data of the image
4614 $imagedata = @file_get_contents($src);
4615 $Image = new Image($imagedata, $filetype);
4616 if (! $Image->isValid()) {
4617 throw new InternalServerErrorException("unable to process image data");
4620 // check orientation of image
4621 $Image->orient($src);
4624 // check max length of images on server
4625 $max_length = Config::get('system', 'max_image_length');
4626 if (! $max_length) {
4627 $max_length = MAX_IMAGE_LENGTH;
4629 if ($max_length > 0) {
4630 $Image->scaleDown($max_length);
4631 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4633 $width = $Image->getWidth();
4634 $height = $Image->getHeight();
4636 // create a new resource-id if not already provided
4637 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4639 if ($mediatype == "photo") {
4640 // upload normal image (scales 0, 1, 2)
4641 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4643 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4645 logger("photo upload: image upload with scale 0 (original size) failed");
4647 if ($width > 640 || $height > 640) {
4648 $Image->scaleDown(640);
4649 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4651 logger("photo upload: image upload with scale 1 (640x640) failed");
4655 if ($width > 320 || $height > 320) {
4656 $Image->scaleDown(320);
4657 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4659 logger("photo upload: image upload with scale 2 (320x320) failed");
4662 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4663 } elseif ($mediatype == "profileimage") {
4664 // upload profile image (scales 4, 5, 6)
4665 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4667 if ($width > 175 || $height > 175) {
4668 $Image->scaleDown(175);
4669 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4671 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4675 if ($width > 80 || $height > 80) {
4676 $Image->scaleDown(80);
4677 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4679 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4683 if ($width > 48 || $height > 48) {
4684 $Image->scaleDown(48);
4685 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4687 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4690 $Image->__destruct();
4691 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4695 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4696 if ($photo_id == null && $mediatype == "photo") {
4697 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4699 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4700 return prepare_photo_data($type, false, $hash);
4702 throw new InternalServerErrorException("image upload failed");
4708 * @param string $hash
4709 * @param string $allow_cid
4710 * @param string $deny_cid
4711 * @param string $allow_gid
4712 * @param string $deny_gid
4713 * @param string $filetype
4714 * @param boolean $visibility
4716 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4718 // get data about the api authenticated user
4719 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4720 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4723 $arr['guid'] = get_guid(32);
4724 $arr['uid'] = intval(api_user());
4726 $arr['parent-uri'] = $uri;
4727 $arr['type'] = 'photo';
4729 $arr['resource-id'] = $hash;
4730 $arr['contact-id'] = $owner_record[0]['id'];
4731 $arr['owner-name'] = $owner_record[0]['name'];
4732 $arr['owner-link'] = $owner_record[0]['url'];
4733 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4734 $arr['author-name'] = $owner_record[0]['name'];
4735 $arr['author-link'] = $owner_record[0]['url'];
4736 $arr['author-avatar'] = $owner_record[0]['thumb'];
4738 $arr['allow_cid'] = $allow_cid;
4739 $arr['allow_gid'] = $allow_gid;
4740 $arr['deny_cid'] = $deny_cid;
4741 $arr['deny_gid'] = $deny_gid;
4742 $arr['visible'] = $visibility;
4746 'image/jpeg' => 'jpg',
4747 'image/png' => 'png',
4748 'image/gif' => 'gif'
4751 // adds link to the thumbnail scale photo
4752 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4753 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4756 // do the magic for storing the item in the database and trigger the federation to other contacts
4762 * @param string $type
4764 * @param string $photo_id
4768 function prepare_photo_data($type, $scale, $photo_id)
4770 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4771 $data_sql = ($scale === false ? "" : "data, ");
4773 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4774 // clients needs to convert this in their way for further processing
4776 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4777 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4778 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4779 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4781 intval(local_user()),
4787 'image/jpeg' => 'jpg',
4788 'image/png' => 'png',
4789 'image/gif' => 'gif'
4792 // prepare output data for photo
4793 if (DBM::is_result($r)) {
4794 $data = ['photo' => $r[0]];
4795 $data['photo']['id'] = $data['photo']['resource-id'];
4796 if ($scale !== false) {
4797 $data['photo']['data'] = base64_encode($data['photo']['data']);
4799 unset($data['photo']['datasize']); //needed only with scale param
4801 if ($type == "xml") {
4802 $data['photo']['links'] = [];
4803 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4804 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4806 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4809 $data['photo']['link'] = [];
4810 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4812 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4813 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4817 unset($data['photo']['resource-id']);
4818 unset($data['photo']['minscale']);
4819 unset($data['photo']['maxscale']);
4821 throw new NotFoundException();
4824 // retrieve item element for getting activities (like, dislike etc.) related to photo
4826 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4827 intval(local_user()),
4830 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4832 // retrieve comments on photo
4834 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4835 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4836 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4837 `contact`.`id` AS `cid`
4839 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4840 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4841 WHERE `item`.`parent` = %d AND `item`.`visible`
4842 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4843 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4844 intval($item[0]['parent']),
4846 dbesc(ACTIVITY_POST)
4849 // prepare output of comments
4850 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4852 if ($type == "xml") {
4854 foreach ($commentData as $comment) {
4855 $comments[$k++ . ":comment"] = $comment;
4858 foreach ($commentData as $comment) {
4859 $comments[] = $comment;
4862 $data['photo']['friendica_comments'] = $comments;
4864 // include info if rights on photo and rights on item are mismatching
4865 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4866 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4867 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4868 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4869 $data['photo']['rights_mismatch'] = $rights_mismatch;
4876 * Similar as /mod/redir.php
4877 * redirect to 'url' after dfrn auth
4879 * Why this when there is mod/redir.php already?
4880 * This use api_user() and api_login()
4883 * c_url: url of remote contact to auth to
4884 * url: string, url to redirect after auth
4886 function api_friendica_remoteauth()
4888 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4889 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4891 if ($url === '' || $c_url === '') {
4892 throw new BadRequestException("Wrong parameters.");
4895 $c_url = normalise_link($c_url);
4899 $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4901 if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
4902 throw new BadRequestException("Unknown contact");
4905 $cid = $contact['id'];
4907 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4909 if ($contact['duplex'] && $contact['issued-id']) {
4910 $orig_id = $contact['issued-id'];
4911 $dfrn_id = '1:' . $orig_id;
4913 if ($contact['duplex'] && $contact['dfrn-id']) {
4914 $orig_id = $contact['dfrn-id'];
4915 $dfrn_id = '0:' . $orig_id;
4918 $sec = random_string();
4921 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4922 VALUES( %d, %s, '%s', '%s', %d )",
4930 logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
4931 $dest = ($url ? '&destination_url=' . $url : '');
4933 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4934 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4935 . '&type=profile&sec=' . $sec . $dest
4938 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4941 * @brief Return the item shared, if the item contains only the [share] tag
4943 * @param array $item Sharer item
4944 * @return array|false Shared item or false if not a reshare
4946 function api_share_as_retweet(&$item)
4948 $body = trim($item["body"]);
4950 if (Diaspora::isReshare($body, false)===false) {
4954 /// @TODO "$1" should maybe mean '$1' ?
4955 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4957 * Skip if there is no shared message in there
4958 * we already checked this in diaspora::isReshare()
4959 * but better one more than one less...
4961 if ($body == $attributes) {
4966 // build the fake reshared item
4967 $reshared_item = $item;
4970 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4971 if ($matches[1] != "") {
4972 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4975 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4976 if ($matches[1] != "") {
4977 $author = $matches[1];
4981 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4982 if ($matches[1] != "") {
4983 $profile = $matches[1];
4986 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4987 if ($matches[1] != "") {
4988 $profile = $matches[1];
4992 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4993 if ($matches[1] != "") {
4994 $avatar = $matches[1];
4997 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4998 if ($matches[1] != "") {
4999 $avatar = $matches[1];
5003 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5004 if ($matches[1] != "") {
5005 $link = $matches[1];
5008 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5009 if ($matches[1] != "") {
5010 $link = $matches[1];
5014 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5015 if ($matches[1] != "") {
5016 $posted = $matches[1];
5019 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5020 if ($matches[1] != "") {
5021 $posted = $matches[1];
5024 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5026 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5030 $reshared_item["body"] = $shared_body;
5031 $reshared_item["author-name"] = $author;
5032 $reshared_item["author-link"] = $profile;
5033 $reshared_item["author-avatar"] = $avatar;
5034 $reshared_item["plink"] = $link;
5035 $reshared_item["created"] = $posted;
5036 $reshared_item["edited"] = $posted;
5038 return $reshared_item;
5043 * @param string $profile
5045 * @return string|false
5046 * @todo remove trailing junk from profile url
5047 * @todo pump.io check has to check the website
5049 function api_get_nick($profile)
5054 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5055 dbesc(normalise_link($profile))
5058 if (DBM::is_result($r)) {
5059 $nick = $r[0]["nick"];
5064 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5065 dbesc(normalise_link($profile))
5068 if (DBM::is_result($r)) {
5069 $nick = $r[0]["nick"];
5074 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5075 if ($friendica != $profile) {
5081 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5082 if ($diaspora != $profile) {
5088 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5089 if ($twitter != $profile) {
5096 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5097 if ($StatusnetHost != $profile) {
5098 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5099 if ($StatusnetUser != $profile) {
5100 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5101 $user = json_decode($UserData);
5103 $nick = $user->screen_name;
5109 // To-Do: look at the page if its really a pumpio site
5110 //if (!$nick == "") {
5111 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5112 // if ($pumpio != $profile)
5114 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5127 * @param array $item
5131 function api_in_reply_to($item)
5135 $in_reply_to['status_id'] = null;
5136 $in_reply_to['user_id'] = null;
5137 $in_reply_to['status_id_str'] = null;
5138 $in_reply_to['user_id_str'] = null;
5139 $in_reply_to['screen_name'] = null;
5141 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5143 "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
5144 intval($item['uid']),
5145 dbesc($item['thr-parent'])
5148 if (DBM::is_result($r)) {
5149 $in_reply_to['status_id'] = intval($r[0]['id']);
5151 $in_reply_to['status_id'] = intval($item['parent']);
5154 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5157 "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
5158 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
5159 WHERE `item`.`id` = %d LIMIT 1",
5160 intval($in_reply_to['status_id'])
5163 if (DBM::is_result($r)) {
5164 if ($r[0]['nick'] == "") {
5165 $r[0]['nick'] = api_get_nick($r[0]["url"]);
5168 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
5169 $in_reply_to['user_id'] = intval($r[0]['id']);
5170 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
5173 // There seems to be situation, where both fields are identical:
5174 // https://github.com/friendica/friendica/issues/1010
5175 // This is a bugfix for that.
5176 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5177 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
5178 $in_reply_to['status_id'] = null;
5179 $in_reply_to['user_id'] = null;
5180 $in_reply_to['status_id_str'] = null;
5181 $in_reply_to['user_id_str'] = null;
5182 $in_reply_to['screen_name'] = null;
5186 return $in_reply_to;
5191 * @param string $Text
5195 function api_clean_plain_items($Text)
5197 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5199 $Text = BBCode::cleanPictureLinks($Text);
5200 $URLSearchString = "^\[\]";
5202 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
5204 if ($include_entities == "true") {
5205 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
5208 // Simplify "attachment" element
5209 $Text = api_clean_attachments($Text);
5215 * @brief Removes most sharing information for API text export
5217 * @param string $body The original body
5219 * @return string Cleaned body
5221 function api_clean_attachments($body)
5223 $data = BBCode::getAttachmentData($body);
5230 if (isset($data["text"])) {
5231 $body = $data["text"];
5233 if (($body == "") && isset($data["title"])) {
5234 $body = $data["title"];
5236 if (isset($data["url"])) {
5237 $body .= "\n".$data["url"];
5239 $body .= $data["after"];
5246 * @param array $contacts
5250 function api_best_nickname(&$contacts)
5254 if (count($contacts) == 0) {
5258 foreach ($contacts as $contact) {
5259 if ($contact["network"] == "") {
5260 $contact["network"] = "dfrn";
5261 $best_contact = [$contact];
5265 if (sizeof($best_contact) == 0) {
5266 foreach ($contacts as $contact) {
5267 if ($contact["network"] == "dfrn") {
5268 $best_contact = [$contact];
5273 if (sizeof($best_contact) == 0) {
5274 foreach ($contacts as $contact) {
5275 if ($contact["network"] == "dspr") {
5276 $best_contact = [$contact];
5281 if (sizeof($best_contact) == 0) {
5282 foreach ($contacts as $contact) {
5283 if ($contact["network"] == "stat") {
5284 $best_contact = [$contact];
5289 if (sizeof($best_contact) == 0) {
5290 foreach ($contacts as $contact) {
5291 if ($contact["network"] == "pump") {
5292 $best_contact = [$contact];
5297 if (sizeof($best_contact) == 0) {
5298 foreach ($contacts as $contact) {
5299 if ($contact["network"] == "twit") {
5300 $best_contact = [$contact];
5305 if (sizeof($best_contact) == 1) {
5306 $contacts = $best_contact;
5308 $contacts = [$contacts[0]];
5313 * Return all or a specified group of the user with the containing contacts.
5315 * @param string $type Return type (atom, rss, xml, json)
5317 * @return array|string
5319 function api_friendica_group_show($type)
5323 if (api_user() === false) {
5324 throw new ForbiddenException();
5328 $user_info = api_get_user($a);
5329 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5330 $uid = $user_info['uid'];
5332 // get data of the specified group id or all groups if not specified
5335 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5339 // error message if specified gid is not in database
5340 if (!DBM::is_result($r)) {
5341 throw new BadRequestException("gid not available");
5345 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5350 // loop through all groups and retrieve all members for adding data in the user array
5351 foreach ($r as $rr) {
5352 $members = Contact::getByGroupId($rr['id']);
5355 if ($type == "xml") {
5356 $user_element = "users";
5358 foreach ($members as $member) {
5359 $user = api_get_user($a, $member['nurl']);
5360 $users[$k++.":user"] = $user;
5363 $user_element = "user";
5364 foreach ($members as $member) {
5365 $user = api_get_user($a, $member['nurl']);
5369 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5371 return api_format_data("groups", $type, ['group' => $grps]);
5373 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5377 * Delete the specified group of the user.
5379 * @param string $type Return type (atom, rss, xml, json)
5381 * @return array|string
5383 function api_friendica_group_delete($type)
5387 if (api_user() === false) {
5388 throw new ForbiddenException();
5392 $user_info = api_get_user($a);
5393 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5394 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5395 $uid = $user_info['uid'];
5397 // error if no gid specified
5398 if ($gid == 0 || $name == "") {
5399 throw new BadRequestException('gid or name not specified');
5402 // get data of the specified group id
5404 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5408 // error message if specified gid is not in database
5409 if (!DBM::is_result($r)) {
5410 throw new BadRequestException('gid not available');
5413 // get data of the specified group id and group name
5415 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5420 // error message if specified gid is not in database
5421 if (!DBM::is_result($rname)) {
5422 throw new BadRequestException('wrong group name');
5426 $ret = Group::removeByName($uid, $name);
5429 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5430 return api_format_data("group_delete", $type, ['result' => $success]);
5432 throw new BadRequestException('other API error');
5435 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5439 * Create the specified group with the posted array of contacts.
5441 * @param string $type Return type (atom, rss, xml, json)
5443 * @return array|string
5445 function api_friendica_group_create($type)
5449 if (api_user() === false) {
5450 throw new ForbiddenException();
5454 $user_info = api_get_user($a);
5455 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5456 $uid = $user_info['uid'];
5457 $json = json_decode($_POST['json'], true);
5458 $users = $json['user'];
5460 // error if no name specified
5462 throw new BadRequestException('group name not specified');
5465 // get data of the specified group name
5467 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5471 // error message if specified group name already exists
5472 if (DBM::is_result($rname)) {
5473 throw new BadRequestException('group name already exists');
5476 // check if specified group name is a deleted group
5478 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5482 // error message if specified group name already exists
5483 if (DBM::is_result($rname)) {
5484 $reactivate_group = true;
5488 $ret = Group::create($uid, $name);
5490 $gid = Group::getIdByName($uid, $name);
5492 throw new BadRequestException('other API error');
5496 $erroraddinguser = false;
5498 foreach ($users as $user) {
5499 $cid = $user['cid'];
5500 // check if user really exists as contact
5502 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5506 if (count($contact)) {
5507 Group::addMember($gid, $cid);
5509 $erroraddinguser = true;
5510 $errorusers[] = $cid;
5514 // return success message incl. missing users in array
5515 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
5516 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5517 return api_format_data("group_create", $type, ['result' => $success]);
5519 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5523 * Update the specified group with the posted array of contacts.
5525 * @param string $type Return type (atom, rss, xml, json)
5527 * @return array|string
5529 function api_friendica_group_update($type)
5533 if (api_user() === false) {
5534 throw new ForbiddenException();
5538 $user_info = api_get_user($a);
5539 $uid = $user_info['uid'];
5540 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5541 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5542 $json = json_decode($_POST['json'], true);
5543 $users = $json['user'];
5545 // error if no name specified
5547 throw new BadRequestException('group name not specified');
5550 // error if no gid specified
5552 throw new BadRequestException('gid not specified');
5556 $members = Contact::getByGroupId($gid);
5557 foreach ($members as $member) {
5558 $cid = $member['id'];
5559 foreach ($users as $user) {
5560 $found = ($user['cid'] == $cid ? true : false);
5563 Group::removeMemberByName($uid, $name, $cid);
5568 $erroraddinguser = false;
5570 foreach ($users as $user) {
5571 $cid = $user['cid'];
5572 // check if user really exists as contact
5574 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5579 if (count($contact)) {
5580 Group::addMember($gid, $cid);
5582 $erroraddinguser = true;
5583 $errorusers[] = $cid;
5587 // return success message incl. missing users in array
5588 $status = ($erroraddinguser ? "missing user" : "ok");
5589 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5590 return api_format_data("group_update", $type, ['result' => $success]);
5593 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5597 * @param string $type Return type (atom, rss, xml, json)
5599 * @return array|string
5601 function api_friendica_activity($type)
5605 if (api_user() === false) {
5606 throw new ForbiddenException();
5608 $verb = strtolower($a->argv[3]);
5609 $verb = preg_replace("|\..*$|", "", $verb);
5611 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5613 $res = Item::performLike($id, $verb);
5616 if ($type == "xml") {
5621 return api_format_data('ok', $type, ['ok' => $ok]);
5623 throw new BadRequestException('Error adding activity');
5627 /// @TODO move to top of file or somewhere better
5628 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5629 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5630 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5631 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5632 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5633 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5634 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5635 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5636 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5637 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5640 * @brief Returns notifications
5642 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5645 function api_friendica_notification($type)
5649 if (api_user() === false) {
5650 throw new ForbiddenException();
5653 throw new BadRequestException("Invalid argument count");
5655 $nm = new NotificationsManager();
5657 $notes = $nm->getAll([], "+seen -date", 50);
5659 if ($type == "xml") {
5661 foreach ($notes as $note) {
5662 $xmlnotes[] = ["@attributes" => $note];
5668 return api_format_data("notes", $type, ['note' => $notes]);
5672 * POST request with 'id' param as notification id
5674 * @brief Set notification as seen and returns associated item (if possible)
5676 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5679 function api_friendica_notification_seen($type)
5683 if (api_user() === false) {
5684 throw new ForbiddenException();
5687 throw new BadRequestException("Invalid argument count");
5690 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5692 $nm = new NotificationsManager();
5693 $note = $nm->getByID($id);
5694 if (is_null($note)) {
5695 throw new BadRequestException("Invalid argument");
5698 $nm->setSeen($note);
5699 if ($note['otype']=='item') {
5700 // would be really better with an ItemsManager and $im->getByID() :-P
5702 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5703 intval($note['iid']),
5704 intval(local_user())
5707 // we found the item, return it to the user
5708 $user_info = api_get_user($a);
5709 $ret = api_format_items($r, $user_info, false, $type);
5710 $data = ['status' => $ret];
5711 return api_format_data("status", $type, $data);
5713 // the item can't be found, but we set the note as seen, so we count this as a success
5715 return api_format_data('result', $type, ['result' => "success"]);
5718 /// @TODO move to top of file or somewhere better
5719 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5720 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5723 * @brief update a direct_message to seen state
5725 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5726 * @return string (success result=ok, error result=error with error message)
5728 function api_friendica_direct_messages_setseen($type)
5731 if (api_user() === false) {
5732 throw new ForbiddenException();
5736 $user_info = api_get_user($a);
5737 $uid = $user_info['uid'];
5738 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5740 // return error if id is zero
5742 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5743 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5746 // get data of the specified message id
5748 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5753 // error message if specified id is not in database
5754 if (!DBM::is_result($r)) {
5755 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5756 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5759 // update seen indicator
5761 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5768 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5769 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5771 $answer = ['result' => 'error', 'message' => 'unknown error'];
5772 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5776 /// @TODO move to top of file or somewhere better
5777 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5780 * @brief search for direct_messages containing a searchstring through api
5782 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5783 * @param string $box
5784 * @return string (success: success=true if found and search_result contains found messages,
5785 * success=false if nothing was found, search_result='nothing found',
5786 * error: result=error with error message)
5788 function api_friendica_direct_messages_search($type, $box = "")
5792 if (api_user() === false) {
5793 throw new ForbiddenException();
5797 $user_info = api_get_user($a);
5798 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5799 $uid = $user_info['uid'];
5801 // error if no searchstring specified
5802 if ($searchstring == "") {
5803 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5804 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5807 // get data for the specified searchstring
5809 "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",
5811 dbesc('%'.$searchstring.'%')
5814 $profile_url = $user_info["url"];
5816 // message if nothing was found
5817 if (!DBM::is_result($r)) {
5818 $success = ['success' => false, 'search_results' => 'problem with query'];
5819 } elseif (count($r) == 0) {
5820 $success = ['success' => false, 'search_results' => 'nothing found'];
5823 foreach ($r as $item) {
5824 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5825 $recipient = $user_info;
5826 $sender = api_get_user($a, normalise_link($item['contact-url']));
5827 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5828 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5829 $sender = $user_info;
5832 $ret[] = api_format_messages($item, $recipient, $sender);
5834 $success = ['success' => true, 'search_results' => $ret];
5837 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5840 /// @TODO move to top of file or somewhere better
5841 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5844 * @brief return data of all the profiles a user has to the client
5846 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5849 function api_friendica_profile_show($type)
5853 if (api_user() === false) {
5854 throw new ForbiddenException();
5858 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5860 // retrieve general information about profiles for user
5861 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5862 $directory = Config::get('system', 'directory');
5864 // get data of the specified profile id or all profiles of the user if not specified
5865 if ($profileid != 0) {
5867 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5872 // error message if specified gid is not in database
5873 if (!DBM::is_result($r)) {
5874 throw new BadRequestException("profile_id not available");
5878 "SELECT * FROM `profile` WHERE `uid` = %d",
5882 // loop through all returned profiles and retrieve data and users
5884 foreach ($r as $rr) {
5885 $profile = api_format_items_profiles($rr);
5887 // select all users from contact table, loop and prepare standard return for user data
5890 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5892 intval($rr['profile_id'])
5895 foreach ($r as $rr) {
5896 $user = api_get_user($a, $rr['nurl']);
5897 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5899 $profile['users'] = $users;
5901 // add prepared profile data to array for final return
5902 if ($type == "xml") {
5903 $profiles[$k++ . ":profile"] = $profile;
5905 $profiles[] = $profile;
5909 // return settings, authenticated user and profiles data
5910 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5912 $result = ['multi_profiles' => $multi_profiles ? true : false,
5913 'global_dir' => $directory,
5914 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5915 'profiles' => $profiles];
5916 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5918 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5921 * Returns a list of saved searches.
5923 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5925 * @param string $type Return format: json or xml
5927 * @return string|array
5929 function api_saved_searches_list($type)
5931 $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
5934 while ($term = $terms->fetch()) {
5936 'name' => $term['term'],
5937 'query' => $term['term'],
5938 'id_str' => $term['id'],
5939 'id' => intval($term['id'])
5945 return api_format_data("terms", $type, ['terms' => $result]);
5948 /// @TODO move to top of file or somewhere better
5949 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5952 @TODO Maybe open to implement?
5954 [pagename] => api/1.1/statuses/lookup.json
5955 [id] => 605138389168451584
5956 [include_cards] => true
5957 [cards_platform] => Android-12
5958 [include_entities] => true
5959 [include_my_retweet] => 1
5961 [include_reply_count] => true
5962 [include_descendent_reply_count] => true
5966 Not implemented by now:
5967 statuses/retweets_of_me
5972 account/update_location
5973 account/update_profile_background_image
5976 friendica/profile/update
5977 friendica/profile/create
5978 friendica/profile/delete
5980 Not implemented in status.net:
5981 statuses/retweeted_to_me
5982 statuses/retweeted_by_me
5983 direct_messages/destroy
5985 account/update_delivery_device
5986 notifications/follow