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 'mod/share.php';
46 require_once 'mod/item.php';
47 require_once 'include/security.php';
48 require_once 'mod/wall_upload.php';
49 require_once 'mod/proxy.php';
51 define('API_METHOD_ANY', '*');
52 define('API_METHOD_GET', 'GET');
53 define('API_METHOD_POST', 'POST,PUT');
54 define('API_METHOD_DELETE', 'POST,DELETE');
60 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
61 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
62 * into a page, and visitors will post something without noticing it).
64 * @brief Auth API user
68 if (x($_SESSION, 'allow_api')) {
76 * Clients can send 'source' parameter to be show in post metadata
77 * as "sent via <source>".
78 * Some clients doesn't send a source param, we support ones we know
81 * @brief Get source name from API client
84 * Client source name, default to "api" if unset/unknown
88 if (requestdata('source')) {
89 return requestdata('source');
92 // Support for known clients that doesn't send a source name
93 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
97 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
103 * @brief Format date for API
105 * @param string $str Source date, as UTC
106 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
108 function api_date($str)
110 // Wed May 23 06:01:13 +0000 2007
111 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
115 * Register a function to be the endpoint for defined API path.
117 * @brief Register API endpoint
119 * @param string $path API URL path, relative to System::baseUrl()
120 * @param string $func Function name to call on path request
121 * @param bool $auth API need logged user
122 * @param string $method HTTP method reqiured to call this endpoint.
123 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
124 * Default to API_METHOD_ANY
126 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
136 // Workaround for hotot
137 $path = str_replace("api/", "api/1.1/", $path);
147 * Log in user via OAuth1 or Simple HTTP Auth.
148 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
150 * @brief Login API user
152 * @param object $a App
153 * @hook 'authenticate'
155 * 'username' => username from login form
156 * 'password' => password from login form
157 * 'authenticated' => return status,
158 * 'user_record' => return authenticated user record
160 * array $user logged user record
162 function api_login(App $a)
164 $oauth1 = new FKOAuth1();
167 list($consumer, $token) = $oauth1->verify_request(OAuthRequest::from_request());
168 if (!is_null($token)) {
169 $oauth1->loginUser($token->uid);
170 Addon::callHooks('logged_in', $a->user);
173 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
174 var_dump($consumer, $token);
176 } catch (Exception $e) {
180 // workaround for HTTP-auth in CGI mode
181 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
182 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
183 if (strlen($userpass)) {
184 list($name, $password) = explode(':', $userpass);
185 $_SERVER['PHP_AUTH_USER'] = $name;
186 $_SERVER['PHP_AUTH_PW'] = $password;
190 if (!x($_SERVER, 'PHP_AUTH_USER')) {
191 logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
192 header('WWW-Authenticate: Basic realm="Friendica"');
193 throw new UnauthorizedException("This API requires login");
196 $user = $_SERVER['PHP_AUTH_USER'];
197 $password = $_SERVER['PHP_AUTH_PW'];
199 // allow "user@server" login (but ignore 'server' part)
200 $at = strstr($user, "@", true);
205 // next code from mod/auth.php. needs better solution
209 'username' => trim($user),
210 'password' => trim($password),
211 'authenticated' => 0,
212 'user_record' => null,
216 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
217 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
218 * and later addons should not interfere with an earlier one that succeeded.
220 Addon::callHooks('authenticate', $addon_auth);
222 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
223 $record = $addon_auth['user_record'];
225 $user_id = User::authenticate(trim($user), trim($password));
226 if ($user_id !== false) {
227 $record = dba::selectFirst('user', [], ['uid' => $user_id]);
231 if (!DBM::is_result($record)) {
232 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
233 header('WWW-Authenticate: Basic realm="Friendica"');
234 //header('HTTP/1.0 401 Unauthorized');
235 //die('This api requires login');
236 throw new UnauthorizedException("This API requires login");
239 authenticate_success($record);
241 $_SESSION["allow_api"] = true;
243 Addon::callHooks('logged_in', $a->user);
247 * API endpoints can define which HTTP method to accept when called.
248 * This function check the current HTTP method agains endpoint
251 * @brief Check HTTP method of called API
253 * @param string $method Required methods, uppercase, separated by comma
256 function api_check_method($method)
258 if ($method == "*") {
261 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
265 * Authenticate user, call registered API function, set HTTP headers
267 * @brief Main API entry point
269 * @param object $a App
270 * @return string|array API call result
272 function api_call(App $a)
274 global $API, $called_api;
277 if (strpos($a->query_string, ".xml") > 0) {
280 if (strpos($a->query_string, ".json") > 0) {
283 if (strpos($a->query_string, ".rss") > 0) {
286 if (strpos($a->query_string, ".atom") > 0) {
291 foreach ($API as $p => $info) {
292 if (strpos($a->query_string, $p) === 0) {
293 if (!api_check_method($info['method'])) {
294 throw new MethodNotAllowedException();
297 $called_api = explode("/", $p);
298 //unset($_SERVER['PHP_AUTH_USER']);
300 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
301 if ($info['auth'] === true && api_user() === false) {
305 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
306 logger('API parameters: ' . print_r($_REQUEST, true));
308 $stamp = microtime(true);
309 $return = call_user_func($info['func'], $type);
310 $duration = (float) (microtime(true) - $stamp);
311 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
313 if (Config::get("system", "profiler")) {
314 $duration = microtime(true)-$a->performance["start"];
316 /// @TODO round() really everywhere?
318 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
319 "Database: %s/%s, Cache %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
320 round($a->performance["database"] - $a->performance["database_write"], 3),
321 round($a->performance["database_write"], 3),
322 round($a->performance["cache"], 3),
323 round($a->performance["cache_write"], 3),
324 round($a->performance["network"], 2),
325 round($a->performance["file"], 2),
326 round($duration - ($a->performance["database"]
327 + $a->performance["cache"] + $a->performance["cache_write"]
328 + $a->performance["network"] + $a->performance["file"]), 2),
334 if (Config::get("rendertime", "callstack")) {
335 $o = "Database Read:\n";
336 foreach ($a->callstack["database"] as $func => $time) {
337 $time = round($time, 3);
339 $o .= $func . ": " . $time . "\n";
342 $o .= "\nDatabase Write:\n";
343 foreach ($a->callstack["database_write"] as $func => $time) {
344 $time = round($time, 3);
346 $o .= $func . ": " . $time . "\n";
350 $o = "Cache Read:\n";
351 foreach ($a->callstack["cache"] as $func => $time) {
352 $time = round($time, 3);
354 $o .= $func . ": " . $time . "\n";
357 $o .= "\nCache Write:\n";
358 foreach ($a->callstack["cache_write"] as $func => $time) {
359 $time = round($time, 3);
361 $o .= $func . ": " . $time . "\n";
365 $o .= "\nNetwork:\n";
366 foreach ($a->callstack["network"] as $func => $time) {
367 $time = round($time, 3);
369 $o .= $func . ": " . $time . "\n";
372 logger($o, LOGGER_DEBUG);
376 if (false === $return) {
378 * api function returned false withour throw an
379 * exception. This should not happend, throw a 500
381 throw new InternalServerErrorException();
386 header("Content-Type: text/xml");
389 header("Content-Type: application/json");
390 $json = json_encode(end($return));
391 if (x($_GET, 'callback')) {
392 $json = $_GET['callback'] . "(" . $json . ")";
397 header("Content-Type: application/rss+xml");
398 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
401 header("Content-Type: application/atom+xml");
402 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
409 logger('API call not implemented: ' . $a->query_string);
410 throw new NotImplementedException();
411 } catch (HTTPException $e) {
412 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
413 return api_error($type, $e);
418 * @brief Format API error string
420 * @param string $type Return type (xml, json, rss, as)
421 * @param object $e HTTPException Error object
422 * @return string|array error message formatted as $type
424 function api_error($type, $e)
428 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
429 /// @TODO: https://dev.twitter.com/overview/api/response-codes
431 $error = ["error" => $error,
432 "code" => $e->httpcode . " " . $e->httpdesc,
433 "request" => $a->query_string];
435 $return = api_format_data('status', $type, ['status' => $error]);
439 header("Content-Type: text/xml");
442 header("Content-Type: application/json");
443 $return = json_encode($return);
446 header("Content-Type: application/rss+xml");
449 header("Content-Type: application/atom+xml");
457 * @brief Set values for RSS template
460 * @param array $arr Array to be passed to template
461 * @param array $user_info User info
463 * @todo find proper type-hints
465 function api_rss_extra(App $a, $arr, $user_info)
467 if (is_null($user_info)) {
468 $user_info = api_get_user($a);
471 $arr['$user'] = $user_info;
473 'alternate' => $user_info['url'],
474 'self' => System::baseUrl() . "/" . $a->query_string,
475 'base' => System::baseUrl(),
476 'updated' => api_date(null),
477 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
478 'language' => $user_info['language'],
479 'logo' => System::baseUrl() . "/images/friendica-32.png",
487 * @brief Unique contact to contact url.
489 * @param int $id Contact id
490 * @return bool|string
491 * Contact url or False if contact id is unknown
493 function api_unique_id_to_nurl($id)
495 $r = dba::selectFirst('contact', ['nurl'], ['uid' => 0, 'id' => $id]);
497 if (DBM::is_result($r)) {
505 * @brief Get user info array.
507 * @param object $a App
508 * @param int|string $contact_id Contact ID or URL
510 function api_get_user(App $a, $contact_id = null)
518 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
520 // Searching for contact URL
521 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
522 $user = dbesc(normalise_link($contact_id));
524 $extra_query = "AND `contact`.`nurl` = '%s' ";
525 if (api_user() !== false) {
526 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
530 // Searching for contact id with uid = 0
531 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
532 $user = dbesc(api_unique_id_to_nurl(intval($contact_id)));
535 throw new BadRequestException("User not found.");
539 $extra_query = "AND `contact`.`nurl` = '%s' ";
540 if (api_user() !== false) {
541 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
545 if (is_null($user) && x($_GET, 'user_id')) {
546 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
549 throw new BadRequestException("User not found.");
553 $extra_query = "AND `contact`.`nurl` = '%s' ";
554 if (api_user() !== false) {
555 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
558 if (is_null($user) && x($_GET, 'screen_name')) {
559 $user = dbesc($_GET['screen_name']);
560 $extra_query = "AND `contact`.`nick` = '%s' ";
561 if (api_user() !== false) {
562 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
566 if (is_null($user) && x($_GET, 'profileurl')) {
567 $user = dbesc(normalise_link($_GET['profileurl']));
568 $extra_query = "AND `contact`.`nurl` = '%s' ";
569 if (api_user() !== false) {
570 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
574 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
575 $argid = count($called_api);
576 list($user, $null) = explode(".", $a->argv[$argid]);
577 if (is_numeric($user)) {
578 $user = dbesc(api_unique_id_to_nurl(intval($user)));
585 $extra_query = "AND `contact`.`nurl` = '%s' ";
586 if (api_user() !== false) {
587 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
590 $user = dbesc($user);
591 $extra_query = "AND `contact`.`nick` = '%s' ";
592 if (api_user() !== false) {
593 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
598 logger("api_get_user: user ".$user, LOGGER_DEBUG);
601 if (api_user() === false) {
605 $user = $_SESSION['uid'];
606 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
610 logger('api_user: ' . $extra_query . ', user: ' . $user);
614 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
620 // Selecting the id by priority, friendica first
621 if (is_array($uinfo)) {
622 api_best_nickname($uinfo);
625 // if the contact wasn't found, fetch it from the contacts with uid = 0
626 if (!DBM::is_result($uinfo)) {
630 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
633 if (DBM::is_result($r)) {
634 $network_name = ContactSelector::networkToName($r[0]['network'], $r[0]['url']);
636 // If no nick where given, extract it from the address
637 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
638 $r[0]['nick'] = api_get_nick($r[0]["url"]);
643 'id_str' => (string) $r[0]["id"],
644 'name' => $r[0]["name"],
645 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
646 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
647 'description' => $r[0]["about"],
648 'profile_image_url' => $r[0]["micro"],
649 'profile_image_url_https' => $r[0]["micro"],
650 'profile_image_url_profile_size' => $r[0]["thumb"],
651 'profile_image_url_large' => $r[0]["photo"],
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 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
788 'profile_image_url_large' => $uinfo[0]["photo"],
789 'url' => $uinfo[0]['url'],
790 'protected' => false,
791 'followers_count' => intval($countfollowers),
792 'friends_count' => intval($countfriends),
794 'created_at' => api_date($uinfo[0]['created']),
795 'favourites_count' => intval($starred),
797 'time_zone' => 'UTC',
798 'geo_enabled' => false,
800 'statuses_count' => intval($countitms),
802 'contributors_enabled' => false,
803 'is_translator' => false,
804 'is_translation_enabled' => false,
805 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
806 'follow_request_sent' => false,
807 'statusnet_blocking' => false,
808 'notifications' => false,
810 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
811 'statusnet_profile_url' => $uinfo[0]['url'],
812 'uid' => intval($uinfo[0]['uid']),
813 'cid' => intval($uinfo[0]['cid']),
814 'self' => $uinfo[0]['self'],
815 'network' => $uinfo[0]['network'],
818 // If this is a local user and it uses Frio, we can get its color preferences.
820 $theme_info = dba::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
821 if ($theme_info['theme'] === 'frio') {
822 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
823 if ($schema && ($schema != '---')) {
824 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
825 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
826 require_once $schemefile;
829 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
830 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
831 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
837 $link_color = "#6fdbe8";
840 $bgcolor = "#ededed";
843 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
844 $ret['profile_link_color'] = str_replace('#', '', $link_color);
845 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
853 * @brief return api-formatted array for item's author and owner
855 * @param object $a App
856 * @param array $item item from db
857 * @return array(array:author, array:owner)
859 function api_item_get_user(App $a, $item)
861 $status_user = api_get_user($a, $item["author-link"]);
863 $status_user["protected"] = (($item["allow_cid"] != "") ||
864 ($item["allow_gid"] != "") ||
865 ($item["deny_cid"] != "") ||
866 ($item["deny_gid"] != "") ||
869 if ($item['thr-parent'] == $item['uri']) {
870 $owner_user = api_get_user($a, $item["owner-link"]);
872 $owner_user = $status_user;
875 return ([$status_user, $owner_user]);
879 * @brief walks recursively through an array with the possibility to change value and key
881 * @param array $array The array to walk through
882 * @param string $callback The callback function
884 * @return array the transformed array
886 function api_walk_recursive(array &$array, callable $callback)
890 foreach ($array as $k => $v) {
892 if ($callback($v, $k)) {
893 $new_array[$k] = api_walk_recursive($v, $callback);
896 if ($callback($v, $k)) {
907 * @brief Callback function to transform the array in an array that can be transformed in a XML file
909 * @param mixed $item Array item value
910 * @param string $key Array key
912 * @return boolean Should the array item be deleted?
914 function api_reformat_xml(&$item, &$key)
916 if (is_bool($item)) {
917 $item = ($item ? "true" : "false");
920 if (substr($key, 0, 10) == "statusnet_") {
921 $key = "statusnet:".substr($key, 10);
922 } elseif (substr($key, 0, 10) == "friendica_") {
923 $key = "friendica:".substr($key, 10);
925 /// @TODO old-lost code?
927 // $key = "default:".$key;
933 * @brief Creates the XML from a JSON style array
935 * @param array $data JSON style array
936 * @param string $root_element Name of the root element
938 * @return string The XML data
940 function api_create_xml($data, $root_element)
942 $childname = key($data);
943 $data2 = array_pop($data);
946 $namespaces = ["" => "http://api.twitter.com",
947 "statusnet" => "http://status.net/schema/api/1/",
948 "friendica" => "http://friendi.ca/schema/api/1/",
949 "georss" => "http://www.georss.org/georss"];
951 /// @todo Auto detection of needed namespaces
952 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
956 if (is_array($data2)) {
957 api_walk_recursive($data2, "api_reformat_xml");
964 foreach ($data2 as $item) {
965 $data4[$i++.":".$childname] = $item;
971 $data3 = [$root_element => $data2];
973 $ret = XML::fromArray($data3, $xml, false, $namespaces);
978 * @brief Formats the data according to the data type
980 * @param string $root_element Name of the root element
981 * @param string $type Return type (atom, rss, xml, json)
982 * @param array $data JSON style array
984 * @return (string|array) XML data or JSON data
986 function api_format_data($root_element, $type, $data)
992 $ret = api_create_xml($data, $root_element);
1008 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
1009 * returns a 401 status code and an error message if not.
1010 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
1012 * @param string $type Return type (atom, rss, xml, json)
1014 function api_account_verify_credentials($type)
1019 if (api_user() === false) {
1020 throw new ForbiddenException();
1023 unset($_REQUEST["user_id"]);
1024 unset($_GET["user_id"]);
1026 unset($_REQUEST["screen_name"]);
1027 unset($_GET["screen_name"]);
1029 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
1031 $user_info = api_get_user($a);
1033 // "verified" isn't used here in the standard
1034 unset($user_info["verified"]);
1036 // - Adding last status
1037 if (!$skip_status) {
1038 $user_info["status"] = api_status_show("raw");
1039 if (!count($user_info["status"])) {
1040 unset($user_info["status"]);
1042 unset($user_info["status"]["user"]);
1046 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1047 unset($user_info["uid"]);
1048 unset($user_info["self"]);
1050 return api_format_data("user", $type, ['user' => $user_info]);
1053 /// @TODO move to top of file or somewhere better
1054 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1057 * Get data from $_POST or $_GET
1061 function requestdata($k)
1063 if (x($_POST, $k)) {
1073 * Waitman Gobble Mod
1075 * @param string $type Return type (atom, rss, xml, json)
1077 * @return array|string
1079 function api_statuses_mediap($type)
1083 if (api_user() === false) {
1084 logger('api_statuses_update: no user');
1085 throw new ForbiddenException();
1087 $user_info = api_get_user($a);
1089 $_REQUEST['type'] = 'wall';
1090 $_REQUEST['profile_uid'] = api_user();
1091 $_REQUEST['api_source'] = true;
1092 $txt = requestdata('status');
1093 /// @TODO old-lost code?
1094 //$txt = urldecode(requestdata('status'));
1096 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1097 $txt = html2bb_video($txt);
1098 $config = HTMLPurifier_Config::createDefault();
1099 $config->set('Cache.DefinitionImpl', null);
1100 $purifier = new HTMLPurifier($config);
1101 $txt = $purifier->purify($txt);
1103 $txt = HTML::toBBCode($txt);
1105 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1107 // tell wall_upload function to return img info instead of echo
1108 $_REQUEST['hush'] = 'yeah';
1109 $bebop = wall_upload_post($a);
1111 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1112 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1115 // this should output the last post (the one we just posted).
1116 return api_status_show($type);
1119 /// @TODO move this to top of file or somewhere better!
1120 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1123 * Updates the user’s current status.
1125 * @param string $type Return type (atom, rss, xml, json)
1127 * @return array|string
1128 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1130 function api_statuses_update($type)
1135 if (api_user() === false) {
1136 logger('api_statuses_update: no user');
1137 throw new ForbiddenException();
1142 // convert $_POST array items to the form we use for web posts.
1143 if (requestdata('htmlstatus')) {
1144 $txt = requestdata('htmlstatus');
1145 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1146 $txt = html2bb_video($txt);
1148 $config = HTMLPurifier_Config::createDefault();
1149 $config->set('Cache.DefinitionImpl', null);
1151 $purifier = new HTMLPurifier($config);
1152 $txt = $purifier->purify($txt);
1154 $_REQUEST['body'] = HTML::toBBCode($txt);
1157 $_REQUEST['body'] = requestdata('status');
1160 $_REQUEST['title'] = requestdata('title');
1162 $parent = requestdata('in_reply_to_status_id');
1164 // Twidere sends "-1" if it is no reply ...
1165 if ($parent == -1) {
1169 if (ctype_digit($parent)) {
1170 $_REQUEST['parent'] = $parent;
1172 $_REQUEST['parent_uri'] = $parent;
1175 if (requestdata('lat') && requestdata('long')) {
1176 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1178 $_REQUEST['profile_uid'] = api_user();
1181 $_REQUEST['type'] = 'net-comment';
1183 // Check for throttling (maximum posts per day, week and month)
1184 $throttle_day = Config::get('system', 'throttle_limit_day');
1185 if ($throttle_day > 0) {
1186 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1189 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1190 AND `created` > '%s' AND `id` = `parent`",
1195 if (DBM::is_result($r)) {
1196 $posts_day = $r[0]["posts_day"];
1201 if ($posts_day > $throttle_day) {
1202 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1203 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1204 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));
1208 $throttle_week = Config::get('system', 'throttle_limit_week');
1209 if ($throttle_week > 0) {
1210 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1213 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1214 AND `created` > '%s' AND `id` = `parent`",
1219 if (DBM::is_result($r)) {
1220 $posts_week = $r[0]["posts_week"];
1225 if ($posts_week > $throttle_week) {
1226 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1227 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1228 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));
1232 $throttle_month = Config::get('system', 'throttle_limit_month');
1233 if ($throttle_month > 0) {
1234 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1237 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1238 AND `created` > '%s' AND `id` = `parent`",
1243 if (DBM::is_result($r)) {
1244 $posts_month = $r[0]["posts_month"];
1249 if ($posts_month > $throttle_month) {
1250 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1251 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1252 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));
1256 $_REQUEST['type'] = 'wall';
1259 if (x($_FILES, 'media')) {
1260 // upload the image if we have one
1261 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1262 $media = wall_upload_post($a);
1263 if (strlen($media) > 0) {
1264 $_REQUEST['body'] .= "\n\n" . $media;
1268 // To-Do: Multiple IDs
1269 if (requestdata('media_ids')) {
1271 "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",
1272 intval(requestdata('media_ids')),
1275 if (DBM::is_result($r)) {
1276 $phototypes = Image::supportedTypes();
1277 $ext = $phototypes[$r[0]['type']];
1278 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1279 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1283 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1285 $_REQUEST['api_source'] = true;
1287 if (!x($_REQUEST, "source")) {
1288 $_REQUEST["source"] = api_source();
1291 // call out normal post function
1294 // this should output the last post (the one we just posted).
1295 return api_status_show($type);
1298 /// @TODO move to top of file or somewhere better
1299 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1300 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1303 * Uploads an image to Friendica.
1306 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1308 function api_media_upload()
1312 if (api_user() === false) {
1314 throw new ForbiddenException();
1319 if (!x($_FILES, 'media')) {
1321 throw new BadRequestException("No media.");
1324 $media = wall_upload_post($a, false);
1327 throw new InternalServerErrorException();
1331 $returndata["media_id"] = $media["id"];
1332 $returndata["media_id_string"] = (string)$media["id"];
1333 $returndata["size"] = $media["size"];
1334 $returndata["image"] = ["w" => $media["width"],
1335 "h" => $media["height"],
1336 "image_type" => $media["type"]];
1338 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1340 return ["media" => $returndata];
1343 /// @TODO move to top of file or somewhere better
1344 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1348 * @param string $type Return type (atom, rss, xml, json)
1350 * @return array|string
1352 function api_status_show($type)
1356 $user_info = api_get_user($a);
1358 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1360 if ($type == "raw") {
1361 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1366 // get last public wall message
1370 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1371 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1372 AND `item`.`type` != 'activity' $privacy_sql
1373 ORDER BY `item`.`id` DESC
1375 intval($user_info['cid']),
1377 dbesc($user_info['url']),
1378 dbesc(normalise_link($user_info['url'])),
1379 dbesc($user_info['url']),
1380 dbesc(normalise_link($user_info['url']))
1383 if (DBM::is_result($lastwall)) {
1384 $lastwall = $lastwall[0];
1386 $in_reply_to = api_in_reply_to($lastwall);
1388 $converted = api_convert_item($lastwall);
1390 if ($type == "xml") {
1391 $geo = "georss:point";
1397 'created_at' => api_date($lastwall['created']),
1398 'id' => intval($lastwall['id']),
1399 'id_str' => (string) $lastwall['id'],
1400 'text' => $converted["text"],
1401 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1402 'truncated' => false,
1403 'in_reply_to_status_id' => $in_reply_to['status_id'],
1404 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1405 'in_reply_to_user_id' => $in_reply_to['user_id'],
1406 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1407 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1408 'user' => $user_info,
1410 'coordinates' => "",
1412 'contributors' => "",
1413 'is_quote_status' => false,
1414 'retweet_count' => 0,
1415 'favorite_count' => 0,
1416 'favorited' => $lastwall['starred'] ? true : false,
1417 'retweeted' => false,
1418 'possibly_sensitive' => false,
1420 'statusnet_html' => $converted["html"],
1421 'statusnet_conversation_id' => $lastwall['parent'],
1422 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1425 if (count($converted["attachments"]) > 0) {
1426 $status_info["attachments"] = $converted["attachments"];
1429 if (count($converted["entities"]) > 0) {
1430 $status_info["entities"] = $converted["entities"];
1433 if (($lastwall['item_network'] != "") && ($status_info["source"] == 'web')) {
1434 $status_info["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1435 } elseif (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1436 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['item_network'], $user_info['url']).')');
1439 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1440 unset($status_info["user"]["uid"]);
1441 unset($status_info["user"]["self"]);
1443 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1445 if ($type == "raw") {
1446 return $status_info;
1449 return api_format_data("statuses", $type, ['status' => $status_info]);
1454 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1455 * The author's most recent status will be returned inline.
1457 * @param string $type Return type (atom, rss, xml, json)
1458 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1460 function api_users_show($type)
1464 $user_info = api_get_user($a);
1468 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1469 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1470 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1471 AND `type`!='activity'
1472 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1476 dbesc(ACTIVITY_POST),
1477 intval($user_info['cid']),
1478 dbesc($user_info['url']),
1479 dbesc(normalise_link($user_info['url'])),
1480 dbesc($user_info['url']),
1481 dbesc(normalise_link($user_info['url']))
1484 if (DBM::is_result($lastwall)) {
1485 $lastwall = $lastwall[0];
1487 $in_reply_to = api_in_reply_to($lastwall);
1489 $converted = api_convert_item($lastwall);
1491 if ($type == "xml") {
1492 $geo = "georss:point";
1497 $user_info['status'] = [
1498 'text' => $converted["text"],
1499 'truncated' => false,
1500 'created_at' => api_date($lastwall['created']),
1501 'in_reply_to_status_id' => $in_reply_to['status_id'],
1502 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1503 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1504 'id' => intval($lastwall['contact-id']),
1505 'id_str' => (string) $lastwall['contact-id'],
1506 'in_reply_to_user_id' => $in_reply_to['user_id'],
1507 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1508 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1510 'favorited' => $lastwall['starred'] ? true : false,
1511 'statusnet_html' => $converted["html"],
1512 'statusnet_conversation_id' => $lastwall['parent'],
1513 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1516 if (count($converted["attachments"]) > 0) {
1517 $user_info["status"]["attachments"] = $converted["attachments"];
1520 if (count($converted["entities"]) > 0) {
1521 $user_info["status"]["entities"] = $converted["entities"];
1524 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1525 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1528 if (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1529 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) . ')');
1533 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1534 unset($user_info["uid"]);
1535 unset($user_info["self"]);
1537 return api_format_data("user", $type, ['user' => $user_info]);
1540 /// @TODO move to top of file or somewhere better
1541 api_register_func('api/users/show', 'api_users_show');
1542 api_register_func('api/externalprofile/show', 'api_users_show');
1545 * Search a public user account.
1547 * @param string $type Return type (atom, rss, xml, json)
1549 * @return array|string
1550 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1552 function api_users_search($type)
1558 if (x($_GET, 'q')) {
1559 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1561 if (!DBM::is_result($r)) {
1562 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1565 if (DBM::is_result($r)) {
1567 foreach ($r as $user) {
1568 $user_info = api_get_user($a, $user["id"]);
1570 if ($type == "xml") {
1571 $userlist[$k++.":user"] = $user_info;
1573 $userlist[] = $user_info;
1576 $userlist = ["users" => $userlist];
1578 throw new BadRequestException("User not found.");
1581 throw new BadRequestException("User not found.");
1584 return api_format_data("users", $type, $userlist);
1587 /// @TODO move to top of file or somewhere better
1588 api_register_func('api/users/search', 'api_users_search');
1591 * Return user objects
1593 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1595 * @param string $type Return format: json or xml
1597 * @return array|string
1598 * @throws NotFoundException if the results are empty.
1600 function api_users_lookup($type)
1604 if (x($_REQUEST['user_id'])) {
1605 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1607 $users[] = api_get_user(get_app(), $id);
1612 if (empty($users)) {
1613 throw new NotFoundException;
1616 return api_format_data("users", $type, ['users' => $users]);
1619 /// @TODO move to top of file or somewhere better
1620 api_register_func('api/users/lookup', 'api_users_lookup', true);
1623 * Returns statuses that match a specified query.
1625 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1627 * @param string $type Return format: json, xml, atom, rss
1629 * @return array|string
1630 * @throws BadRequestException if the "q" parameter is missing.
1632 function api_search($type)
1635 $user_info = api_get_user($a);
1637 if (api_user() === false || $user_info === false) {
1638 throw new ForbiddenException();
1644 if (!x($_REQUEST, 'q')) {
1645 throw new BadRequestException("q parameter is required.");
1648 if (x($_REQUEST, 'rpp')) {
1649 $count = $_REQUEST['rpp'];
1650 } elseif (x($_REQUEST, 'count')) {
1651 $count = $_REQUEST['count'];
1656 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1657 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1658 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1660 $start = $page * $count;
1663 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1667 "SELECT ".item_fieldlists()."
1668 FROM `item` ".item_joins()."
1669 WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1670 AND `item`.`body` LIKE CONCAT('%',?,'%')
1673 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
1679 $data['status'] = api_format_items(dba::inArray($r), $user_info);
1681 return api_format_data("statuses", $type, $data);
1684 /// @TODO move to top of file or somewhere better
1685 api_register_func('api/search/tweets', 'api_search', true);
1686 api_register_func('api/search', 'api_search', true);
1689 * Returns the most recent statuses posted by the user and the users they follow.
1691 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1693 * @param string $type Return type (atom, rss, xml, json)
1695 * @todo Optional parameters
1696 * @todo Add reply info
1698 function api_statuses_home_timeline($type)
1701 $user_info = api_get_user($a);
1703 if (api_user() === false || $user_info === false) {
1704 throw new ForbiddenException();
1707 unset($_REQUEST["user_id"]);
1708 unset($_GET["user_id"]);
1710 unset($_REQUEST["screen_name"]);
1711 unset($_GET["screen_name"]);
1713 // get last network messages
1716 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1717 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1721 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1722 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1723 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1724 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1725 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1727 $start = $page * $count;
1731 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1733 if ($exclude_replies > 0) {
1734 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1736 if ($conversation_id > 0) {
1737 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1741 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1742 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1743 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1744 `contact`.`id` AS `cid`
1746 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1747 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1748 WHERE `item`.`uid` = %d AND `verb` = '%s'
1749 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1752 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1754 dbesc(ACTIVITY_POST),
1760 $ret = api_format_items($r, $user_info, false, $type);
1762 // Set all posts from the query above to seen
1764 foreach ($r as $item) {
1765 $idarray[] = intval($item["id"]);
1768 $idlist = implode(",", $idarray);
1770 if ($idlist != "") {
1771 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1774 q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1778 $data = ['status' => $ret];
1782 $data = api_rss_extra($a, $data, $user_info);
1786 return api_format_data("statuses", $type, $data);
1789 /// @TODO move to top of file or somewhere better
1790 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1791 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1794 * Returns the most recent statuses from public users.
1796 * @param string $type Return type (atom, rss, xml, json)
1798 * @return array|string
1800 function api_statuses_public_timeline($type)
1803 $user_info = api_get_user($a);
1805 if (api_user() === false || $user_info === false) {
1806 throw new ForbiddenException();
1809 // get last network messages
1812 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1813 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1817 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1818 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1819 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1820 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1821 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1823 $start = $page * $count;
1826 if ($exclude_replies && !$conversation_id) {
1828 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1832 "SELECT " . item_fieldlists() . "
1834 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1835 " . item_joins() . "
1836 STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1837 AND NOT `user`.`hidewall`
1839 AND NOT `thread`.`private`
1841 AND `thread`.`visible`
1842 AND NOT `thread`.`deleted`
1843 AND NOT `thread`.`moderated`
1844 AND `thread`.`iid` > ?
1846 ORDER BY `thread`.`iid` DESC
1847 LIMIT " . intval($start) . ", " . intval($count),
1852 $r = dba::inArray($r);
1855 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1857 if ($conversation_id > 0) {
1858 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1862 "SELECT " . item_fieldlists() . "
1864 " . item_joins() . "
1865 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1866 AND NOT `user`.`hidewall`
1868 AND NOT `item`.`private`
1870 AND `item`.`visible`
1871 AND NOT `item`.`deleted`
1872 AND NOT `item`.`moderated`
1875 ORDER BY `item`.`id` DESC
1876 LIMIT " . intval($start) . ", " . intval($count),
1881 $r = dba::inArray($r);
1884 $ret = api_format_items($r, $user_info, false, $type);
1886 $data = ['status' => $ret];
1890 $data = api_rss_extra($a, $data, $user_info);
1894 return api_format_data("statuses", $type, $data);
1897 /// @TODO move to top of file or somewhere better
1898 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1901 * Returns the most recent statuses posted by users this node knows about.
1903 * @brief Returns the list of public federated posts this node knows about
1905 * @param string $type Return format: json, xml, atom, rss
1906 * @return array|string
1907 * @throws ForbiddenException
1909 function api_statuses_networkpublic_timeline($type)
1912 $user_info = api_get_user($a);
1914 if (api_user() === false || $user_info === false) {
1915 throw new ForbiddenException();
1918 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1919 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1922 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1923 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1927 $start = ($page - 1) * $count;
1931 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1935 "SELECT " . item_fieldlists() . "
1937 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1938 " . item_joins() . "
1939 WHERE `thread`.`uid` = 0
1941 AND NOT `thread`.`private`
1942 AND `thread`.`visible`
1943 AND NOT `thread`.`deleted`
1944 AND NOT `thread`.`moderated`
1945 AND `thread`.`iid` > ?
1947 ORDER BY `thread`.`iid` DESC
1948 LIMIT " . intval($start) . ", " . intval($count),
1953 $r = dba::inArray($r);
1955 $ret = api_format_items($r, $user_info, false, $type);
1957 $data = ['status' => $ret];
1961 $data = api_rss_extra($a, $data, $user_info);
1965 return api_format_data("statuses", $type, $data);
1968 /// @TODO move to top of file or somewhere better
1969 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1972 * Returns a single status.
1974 * @param string $type Return type (atom, rss, xml, json)
1976 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1978 function api_statuses_show($type)
1981 $user_info = api_get_user($a);
1983 if (api_user() === false || $user_info === false) {
1984 throw new ForbiddenException();
1988 $id = intval($a->argv[3]);
1991 $id = intval($_REQUEST["id"]);
1996 $id = intval($a->argv[4]);
1999 logger('API: api_statuses_show: ' . $id);
2001 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
2004 if ($conversation) {
2005 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
2007 $sql_extra .= " AND `item`.`id` = %d";
2011 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2012 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2013 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2014 `contact`.`id` AS `cid`
2016 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2017 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2018 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2019 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2022 dbesc(ACTIVITY_POST),
2026 /// @TODO How about copying this to above methods which don't check $r ?
2027 if (!DBM::is_result($r)) {
2028 throw new BadRequestException("There is no status with this id.");
2031 $ret = api_format_items($r, $user_info, false, $type);
2033 if ($conversation) {
2034 $data = ['status' => $ret];
2035 return api_format_data("statuses", $type, $data);
2037 $data = ['status' => $ret[0]];
2038 return api_format_data("status", $type, $data);
2042 /// @TODO move to top of file or somewhere better
2043 api_register_func('api/statuses/show', 'api_statuses_show', true);
2047 * @param string $type Return type (atom, rss, xml, json)
2049 * @todo nothing to say?
2051 function api_conversation_show($type)
2054 $user_info = api_get_user($a);
2056 if (api_user() === false || $user_info === false) {
2057 throw new ForbiddenException();
2061 $id = intval($a->argv[3]);
2062 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2063 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
2067 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2068 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2070 $start = $page*$count;
2073 $id = intval($_REQUEST["id"]);
2078 $id = intval($a->argv[4]);
2081 logger('API: api_conversation_show: '.$id);
2083 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
2084 if (DBM::is_result($r)) {
2085 $id = $r[0]["parent"];
2091 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2094 // Not sure why this query was so complicated. We should keep it here for a while,
2095 // just to make sure that we really don't need it.
2096 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
2097 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
2100 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2101 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2102 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2103 `contact`.`id` AS `cid`
2105 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2106 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2107 WHERE `item`.`parent` = %d AND `item`.`visible`
2108 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2109 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2110 AND `item`.`id`>%d $sql_extra
2111 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2114 dbesc(ACTIVITY_POST),
2120 if (!DBM::is_result($r)) {
2121 throw new BadRequestException("There is no status with this id.");
2124 $ret = api_format_items($r, $user_info, false, $type);
2126 $data = ['status' => $ret];
2127 return api_format_data("statuses", $type, $data);
2130 /// @TODO move to top of file or somewhere better
2131 api_register_func('api/conversation/show', 'api_conversation_show', true);
2132 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2137 * @param string $type Return type (atom, rss, xml, json)
2139 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2141 function api_statuses_repeat($type)
2147 if (api_user() === false) {
2148 throw new ForbiddenException();
2154 $id = intval($a->argv[3]);
2157 $id = intval($_REQUEST["id"]);
2162 $id = intval($a->argv[4]);
2165 logger('API: api_statuses_repeat: '.$id);
2168 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2169 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2170 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2171 `contact`.`id` AS `cid`
2173 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2174 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2175 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2176 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2177 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2178 AND `item`.`id`=%d",
2182 /// @TODO other style than above functions!
2183 if (DBM::is_result($r) && $r[0]['body'] != "") {
2184 if (strpos($r[0]['body'], "[/share]") !== false) {
2185 $pos = strpos($r[0]['body'], "[share");
2186 $post = substr($r[0]['body'], $pos);
2188 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2190 $post .= $r[0]['body'];
2191 $post .= "[/share]";
2193 $_REQUEST['body'] = $post;
2194 $_REQUEST['profile_uid'] = api_user();
2195 $_REQUEST['type'] = 'wall';
2196 $_REQUEST['api_source'] = true;
2198 if (!x($_REQUEST, "source")) {
2199 $_REQUEST["source"] = api_source();
2204 throw new ForbiddenException();
2207 // this should output the last post (the one we just posted).
2209 return api_status_show($type);
2212 /// @TODO move to top of file or somewhere better
2213 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2216 * Destroys a specific status.
2218 * @param string $type Return type (atom, rss, xml, json)
2220 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2222 function api_statuses_destroy($type)
2226 if (api_user() === false) {
2227 throw new ForbiddenException();
2233 $id = intval($a->argv[3]);
2236 $id = intval($_REQUEST["id"]);
2241 $id = intval($a->argv[4]);
2244 logger('API: api_statuses_destroy: '.$id);
2246 $ret = api_statuses_show($type);
2248 Item::deleteById($id);
2253 /// @TODO move to top of file or somewhere better
2254 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2257 * Returns the most recent mentions.
2259 * @param string $type Return type (atom, rss, xml, json)
2261 * @see http://developer.twitter.com/doc/get/statuses/mentions
2263 function api_statuses_mentions($type)
2266 $user_info = api_get_user($a);
2268 if (api_user() === false || $user_info === false) {
2269 throw new ForbiddenException();
2272 unset($_REQUEST["user_id"]);
2273 unset($_GET["user_id"]);
2275 unset($_REQUEST["screen_name"]);
2276 unset($_GET["screen_name"]);
2278 // get last network messages
2281 $since_id = defaults($_REQUEST, 'since_id', 0);
2282 $max_id = defaults($_REQUEST, 'max_id' , 0);
2283 $count = defaults($_REQUEST, 'count' , 20);
2284 $page = defaults($_REQUEST, 'page' , 1);
2289 $start = ($page - 1) * $count;
2291 // Ugly code - should be changed
2292 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2293 $myurl = substr($myurl, strpos($myurl, '://') + 3);
2294 $myurl = str_replace('www.', '', $myurl);
2299 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2303 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2304 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2305 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2306 `contact`.`id` AS `cid`
2307 FROM `item` FORCE INDEX (`uid_id`)
2308 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2309 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2310 WHERE `item`.`uid` = %d AND `verb` = '%s'
2311 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2312 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2313 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2316 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2318 dbesc(ACTIVITY_POST),
2319 dbesc(protect_sprintf($myurl)),
2320 dbesc(protect_sprintf($myurl)),
2327 $ret = api_format_items($r, $user_info, false, $type);
2329 $data = ['status' => $ret];
2333 $data = api_rss_extra($a, $data, $user_info);
2337 return api_format_data("statuses", $type, $data);
2340 /// @TODO move to top of file or somewhere better
2341 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2342 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2345 * Returns the most recent statuses posted by the user.
2347 * @brief Returns a user's public timeline
2349 * @param string $type Either "json" or "xml"
2350 * @return string|array
2351 * @throws ForbiddenException
2352 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2354 function api_statuses_user_timeline($type)
2357 $user_info = api_get_user($a);
2359 if (api_user() === false || $user_info === false) {
2360 throw new ForbiddenException();
2364 "api_statuses_user_timeline: api_user: ". api_user() .
2365 "\nuser_info: ".print_r($user_info, true) .
2366 "\n_REQUEST: ".print_r($_REQUEST, true),
2370 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2371 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2372 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2373 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2376 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2377 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2381 $start = ($page - 1) * $count;
2384 if ($user_info['self'] == 1) {
2385 $sql_extra .= " AND `item`.`wall` = 1 ";
2388 if ($exclude_replies > 0) {
2389 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2392 if ($conversation_id > 0) {
2393 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2397 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2401 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2402 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2403 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2404 `contact`.`id` AS `cid`
2405 FROM `item` FORCE INDEX (`uid_contactid_id`)
2406 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2407 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2408 WHERE `item`.`uid` = %d AND `verb` = '%s'
2409 AND `item`.`contact-id` = %d
2410 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2412 AND `item`.`id` > %d
2413 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2415 dbesc(ACTIVITY_POST),
2416 intval($user_info['cid']),
2422 $ret = api_format_items($r, $user_info, true, $type);
2424 $data = ['status' => $ret];
2428 $data = api_rss_extra($a, $data, $user_info);
2432 return api_format_data("statuses", $type, $data);
2435 /// @TODO move to top of file or somewhere better
2436 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2439 * Star/unstar an item.
2440 * param: id : id of the item
2442 * @param string $type Return type (atom, rss, xml, json)
2444 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2446 function api_favorites_create_destroy($type)
2450 if (api_user() === false) {
2451 throw new ForbiddenException();
2454 // for versioned api.
2455 /// @TODO We need a better global soluton
2456 $action_argv_id = 2;
2457 if ($a->argv[1] == "1.1") {
2458 $action_argv_id = 3;
2461 if ($a->argc <= $action_argv_id) {
2462 throw new BadRequestException("Invalid request.");
2464 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2465 if ($a->argc == $action_argv_id + 2) {
2466 $itemid = intval($a->argv[$action_argv_id + 1]);
2468 /// @TODO use x() to check if _REQUEST contains 'id'
2469 $itemid = intval($_REQUEST['id']);
2472 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2474 if (!DBM::is_result($item) || count($item) == 0) {
2475 throw new BadRequestException("Invalid item.");
2480 $item[0]['starred'] = 1;
2483 $item[0]['starred'] = 0;
2486 throw new BadRequestException("Invalid action ".$action);
2489 $r = Item::update(['starred' => $item[0]['starred']], ['id' => $itemid]);
2492 throw new InternalServerErrorException("DB error");
2496 $user_info = api_get_user($a);
2497 $rets = api_format_items($item, $user_info, false, $type);
2500 $data = ['status' => $ret];
2504 $data = api_rss_extra($a, $data, $user_info);
2507 return api_format_data("status", $type, $data);
2510 /// @TODO move to top of file or somewhere better
2511 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2512 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2515 * Returns the most recent favorite statuses.
2517 * @param string $type Return type (atom, rss, xml, json)
2519 * @return string|array
2521 function api_favorites($type)
2526 $user_info = api_get_user($a);
2528 if (api_user() === false || $user_info === false) {
2529 throw new ForbiddenException();
2534 // in friendica starred item are private
2535 // return favorites only for self
2536 logger('api_favorites: self:' . $user_info['self']);
2538 if ($user_info['self'] == 0) {
2544 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2545 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2546 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2547 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2552 $start = $page*$count;
2555 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2559 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2560 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2561 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2562 `contact`.`id` AS `cid`
2563 FROM `item`, `contact`
2564 WHERE `item`.`uid` = %d
2565 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2566 AND `item`.`starred` = 1
2567 AND `contact`.`id` = `item`.`contact-id`
2568 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2571 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2578 $ret = api_format_items($r, $user_info, false, $type);
2581 $data = ['status' => $ret];
2585 $data = api_rss_extra($a, $data, $user_info);
2588 return api_format_data("statuses", $type, $data);
2591 /// @TODO move to top of file or somewhere better
2592 api_register_func('api/favorites', 'api_favorites', true);
2596 * @param array $item
2597 * @param array $recipient
2598 * @param array $sender
2602 function api_format_messages($item, $recipient, $sender)
2604 // standard meta information
2606 'id' => $item['id'],
2607 'sender_id' => $sender['id'] ,
2609 'recipient_id' => $recipient['id'],
2610 'created_at' => api_date($item['created']),
2611 'sender_screen_name' => $sender['screen_name'],
2612 'recipient_screen_name' => $recipient['screen_name'],
2613 'sender' => $sender,
2614 'recipient' => $recipient,
2616 'friendica_seen' => $item['seen'],
2617 'friendica_parent_uri' => $item['parent-uri'],
2620 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2621 unset($ret["sender"]["uid"]);
2622 unset($ret["sender"]["self"]);
2623 unset($ret["recipient"]["uid"]);
2624 unset($ret["recipient"]["self"]);
2626 //don't send title to regular StatusNET requests to avoid confusing these apps
2627 if (x($_GET, 'getText')) {
2628 $ret['title'] = $item['title'];
2629 if ($_GET['getText'] == 'html') {
2630 $ret['text'] = BBCode::convert($item['body'], false);
2631 } elseif ($_GET['getText'] == 'plain') {
2632 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2635 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2637 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2638 unset($ret['sender']);
2639 unset($ret['recipient']);
2647 * @param array $item
2651 function api_convert_item($item)
2653 $body = $item['body'];
2654 $attachments = api_get_attachments($body);
2656 // Workaround for ostatus messages where the title is identically to the body
2657 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2658 $statusbody = trim(HTML::toPlaintext($html, 0));
2660 // handle data: images
2661 $statusbody = api_format_items_embeded_images($item, $statusbody);
2663 $statustitle = trim($item['title']);
2665 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2666 $statustext = trim($statusbody);
2668 $statustext = trim($statustitle."\n\n".$statusbody);
2671 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2672 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2675 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2677 // Workaround for clients with limited HTML parser functionality
2678 $search = ["<br>", "<blockquote>", "</blockquote>",
2679 "<h1>", "</h1>", "<h2>", "</h2>",
2680 "<h3>", "</h3>", "<h4>", "</h4>",
2681 "<h5>", "</h5>", "<h6>", "</h6>"];
2682 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2683 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2684 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2685 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2686 $statushtml = str_replace($search, $replace, $statushtml);
2688 if ($item['title'] != "") {
2689 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2693 $oldtext = $statushtml;
2694 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2695 } while ($oldtext != $statushtml);
2697 if (substr($statushtml, 0, 4) == '<br>') {
2698 $statushtml = substr($statushtml, 4);
2701 if (substr($statushtml, 0, -4) == '<br>') {
2702 $statushtml = substr($statushtml, -4);
2705 // feeds without body should contain the link
2706 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2707 $statushtml .= BBCode::convert($item['plink']);
2710 $entities = api_get_entitities($statustext, $body);
2713 "text" => $statustext,
2714 "html" => $statushtml,
2715 "attachments" => $attachments,
2716 "entities" => $entities
2722 * @param string $body
2724 * @return array|false
2726 function api_get_attachments(&$body)
2729 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2731 $URLSearchString = "^\[\]";
2732 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2740 foreach ($images[1] as $image) {
2741 $imagedata = Image::getInfoFromURL($image);
2744 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2748 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2749 foreach ($images[0] as $orig) {
2750 $body = str_replace($orig, "", $body);
2754 return $attachments;
2759 * @param string $text
2760 * @param string $bbcode
2763 * @todo Links at the first character of the post
2765 function api_get_entitities(&$text, $bbcode)
2767 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2769 if ($include_entities != "true") {
2770 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2772 foreach ($images[1] as $image) {
2773 $replace = proxy_url($image);
2774 $text = str_replace($image, $replace, $text);
2779 $bbcode = BBCode::cleanPictureLinks($bbcode);
2781 // Change pure links in text to bbcode uris
2782 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2785 $entities["hashtags"] = [];
2786 $entities["symbols"] = [];
2787 $entities["urls"] = [];
2788 $entities["user_mentions"] = [];
2790 $URLSearchString = "^\[\]";
2792 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2794 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2795 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2796 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2798 $bbcode = preg_replace(
2799 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2800 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2803 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2805 $bbcode = preg_replace(
2806 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2807 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2810 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2812 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2814 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2815 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2818 foreach ($urls[1] as $id => $url) {
2819 //$start = strpos($text, $url, $offset);
2820 $start = iconv_strpos($text, $url, 0, "UTF-8");
2821 if (!($start === false)) {
2822 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2826 ksort($ordered_urls);
2829 //foreach ($urls[1] AS $id=>$url) {
2830 foreach ($ordered_urls as $url) {
2831 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2832 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2834 $display_url = $url["title"];
2836 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2837 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2839 if (strlen($display_url) > 26) {
2840 $display_url = substr($display_url, 0, 25)."…";
2844 //$start = strpos($text, $url, $offset);
2845 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2846 if (!($start === false)) {
2847 $entities["urls"][] = ["url" => $url["url"],
2848 "expanded_url" => $url["url"],
2849 "display_url" => $display_url,
2850 "indices" => [$start, $start+strlen($url["url"])]];
2851 $offset = $start + 1;
2855 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2856 $ordered_images = [];
2857 foreach ($images[1] as $image) {
2858 //$start = strpos($text, $url, $offset);
2859 $start = iconv_strpos($text, $image, 0, "UTF-8");
2860 if (!($start === false)) {
2861 $ordered_images[$start] = $image;
2864 //$entities["media"] = array();
2867 foreach ($ordered_images as $url) {
2868 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2869 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2871 if (strlen($display_url) > 26) {
2872 $display_url = substr($display_url, 0, 25)."…";
2875 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2876 if (!($start === false)) {
2877 $image = Image::getInfoFromURL($url);
2879 // If image cache is activated, then use the following sizes:
2880 // thumb (150), small (340), medium (600) and large (1024)
2881 if (!Config::get("system", "proxy_disabled")) {
2882 $media_url = proxy_url($url);
2885 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2886 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2888 if (($image[0] > 150) || ($image[1] > 150)) {
2889 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2890 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2893 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2894 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2896 if (($image[0] > 600) || ($image[1] > 600)) {
2897 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2898 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2902 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2905 $entities["media"][] = [
2907 "id_str" => (string)$start+1,
2908 "indices" => [$start, $start+strlen($url)],
2909 "media_url" => normalise_link($media_url),
2910 "media_url_https" => $media_url,
2912 "display_url" => $display_url,
2913 "expanded_url" => $url,
2917 $offset = $start + 1;
2926 * @param array $item
2927 * @param string $text
2931 function api_format_items_embeded_images($item, $text)
2933 $text = preg_replace_callback(
2934 '|data:image/([^;]+)[^=]+=*|m',
2935 function () use ($item) {
2936 return System::baseUrl() . '/display/' . $item['guid'];
2944 * @brief return <a href='url'>name</a> as array
2946 * @param string $txt text
2951 function api_contactlink_to_array($txt)
2954 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2955 if ($r && count($match)==3) {
2957 'name' => $match[2],
2971 * @brief return likes, dislikes and attend status for item
2973 * @param array $item array
2974 * @param string $type Return type (atom, rss, xml, json)
2977 * likes => int count,
2978 * dislikes => int count
2980 function api_format_items_activities(&$item, $type = "json")
2989 'attendmaybe' => [],
2994 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2995 intval($item['uid']),
2999 foreach ($items as $i) {
3000 // not used as result should be structured like other user data
3001 //builtin_activity_puller($i, $activities);
3003 // get user data and add it to the array of the activity
3004 $user = api_get_user($a, $i['author-link']);
3005 switch ($i['verb']) {
3007 $activities['like'][] = $user;
3009 case ACTIVITY_DISLIKE:
3010 $activities['dislike'][] = $user;
3012 case ACTIVITY_ATTEND:
3013 $activities['attendyes'][] = $user;
3015 case ACTIVITY_ATTENDNO:
3016 $activities['attendno'][] = $user;
3018 case ACTIVITY_ATTENDMAYBE:
3019 $activities['attendmaybe'][] = $user;
3026 if ($type == "xml") {
3027 $xml_activities = [];
3028 foreach ($activities as $k => $v) {
3029 // change xml element from "like" to "friendica:like"
3030 $xml_activities["friendica:".$k] = $v;
3031 // add user data into xml output
3033 foreach ($v as $user) {
3034 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
3037 $activities = $xml_activities;
3045 * @brief return data from profiles
3047 * @param array $profile_row array containing data from db table 'profile'
3050 function api_format_items_profiles($profile_row)
3053 'profile_id' => $profile_row['id'],
3054 'profile_name' => $profile_row['profile-name'],
3055 'is_default' => $profile_row['is-default'] ? true : false,
3056 'hide_friends' => $profile_row['hide-friends'] ? true : false,
3057 'profile_photo' => $profile_row['photo'],
3058 'profile_thumb' => $profile_row['thumb'],
3059 'publish' => $profile_row['publish'] ? true : false,
3060 'net_publish' => $profile_row['net-publish'] ? true : false,
3061 'description' => $profile_row['pdesc'],
3062 'date_of_birth' => $profile_row['dob'],
3063 'address' => $profile_row['address'],
3064 'city' => $profile_row['locality'],
3065 'region' => $profile_row['region'],
3066 'postal_code' => $profile_row['postal-code'],
3067 'country' => $profile_row['country-name'],
3068 'hometown' => $profile_row['hometown'],
3069 'gender' => $profile_row['gender'],
3070 'marital' => $profile_row['marital'],
3071 'marital_with' => $profile_row['with'],
3072 'marital_since' => $profile_row['howlong'],
3073 'sexual' => $profile_row['sexual'],
3074 'politic' => $profile_row['politic'],
3075 'religion' => $profile_row['religion'],
3076 'public_keywords' => $profile_row['pub_keywords'],
3077 'private_keywords' => $profile_row['prv_keywords'],
3078 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
3079 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
3080 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
3081 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
3082 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
3083 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
3084 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
3085 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
3086 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
3087 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
3088 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
3089 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
3090 'homepage' => $profile_row['homepage'],
3097 * @brief format items to be returned by api
3099 * @param array $r array of items
3100 * @param array $user_info
3101 * @param bool $filter_user filter items by $user_info
3102 * @param string $type Return type (atom, rss, xml, json)
3104 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
3110 foreach ($r as $item) {
3111 localize_item($item);
3112 list($status_user, $owner_user) = api_item_get_user($a, $item);
3114 // Look if the posts are matching if they should be filtered by user id
3115 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3119 $in_reply_to = api_in_reply_to($item);
3121 $converted = api_convert_item($item);
3123 if ($type == "xml") {
3124 $geo = "georss:point";
3130 'text' => $converted["text"],
3131 'truncated' => false,
3132 'created_at'=> api_date($item['created']),
3133 'in_reply_to_status_id' => $in_reply_to['status_id'],
3134 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3135 'source' => (($item['app']) ? $item['app'] : 'web'),
3136 'id' => intval($item['id']),
3137 'id_str' => (string) intval($item['id']),
3138 'in_reply_to_user_id' => $in_reply_to['user_id'],
3139 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3140 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3142 'favorited' => $item['starred'] ? true : false,
3143 'user' => $status_user ,
3144 'friendica_owner' => $owner_user,
3145 //'entities' => NULL,
3146 'statusnet_html' => $converted["html"],
3147 'statusnet_conversation_id' => $item['parent'],
3148 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3149 'friendica_activities' => api_format_items_activities($item, $type),
3152 if (count($converted["attachments"]) > 0) {
3153 $status["attachments"] = $converted["attachments"];
3156 if (count($converted["entities"]) > 0) {
3157 $status["entities"] = $converted["entities"];
3160 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
3161 $status["source"] = ContactSelector::networkToName($item['item_network'], $user_info['url']);
3162 } elseif (($item['item_network'] != "") && (ContactSelector::networkToName($item['item_network'], $user_info['url']) != $status["source"])) {
3163 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['item_network'], $user_info['url']).')');
3167 // Retweets are only valid for top postings
3168 // It doesn't work reliable with the link if its a feed
3169 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
3171 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
3174 if ($item["id"] == $item["parent"]) {
3175 $retweeted_item = api_share_as_retweet($item);
3176 if ($retweeted_item !== false) {
3177 $retweeted_status = $status;
3179 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
3180 } catch (BadRequestException $e) {
3181 // user not found. should be found?
3182 /// @todo check if the user should be always found
3183 $retweeted_status["user"] = [];
3186 $rt_converted = api_convert_item($retweeted_item);
3188 $retweeted_status['text'] = $rt_converted["text"];
3189 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3190 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3191 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3192 $status['retweeted_status'] = $retweeted_status;
3196 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3197 unset($status["user"]["uid"]);
3198 unset($status["user"]["self"]);
3200 if ($item["coord"] != "") {
3201 $coords = explode(' ', $item["coord"]);
3202 if (count($coords) == 2) {
3203 if ($type == "json") {
3204 $status["geo"] = ['type' => 'Point',
3205 'coordinates' => [(float) $coords[0],
3206 (float) $coords[1]]];
3207 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3208 $status["georss:point"] = $item["coord"];
3218 * Returns the remaining number of API requests available to the user before the API limit is reached.
3220 * @param string $type Return type (atom, rss, xml, json)
3222 * @return array|string
3224 function api_account_rate_limit_status($type)
3226 if ($type == "xml") {
3228 'remaining-hits' => '150',
3229 '@attributes' => ["type" => "integer"],
3230 'hourly-limit' => '150',
3231 '@attributes2' => ["type" => "integer"],
3232 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3233 '@attributes3' => ["type" => "datetime"],
3234 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3235 '@attributes4' => ["type" => "integer"],
3239 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3240 'remaining_hits' => '150',
3241 'hourly_limit' => '150',
3242 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3246 return api_format_data('hash', $type, ['hash' => $hash]);
3249 /// @TODO move to top of file or somewhere better
3250 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3253 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3255 * @param string $type Return type (atom, rss, xml, json)
3257 * @return array|string
3259 function api_help_test($type)
3261 if ($type == 'xml') {
3267 return api_format_data('ok', $type, ["ok" => $ok]);
3270 /// @TODO move to top of file or somewhere better
3271 api_register_func('api/help/test', 'api_help_test', false);
3274 * Returns all lists the user subscribes to.
3276 * @param string $type Return type (atom, rss, xml, json)
3278 * @return array|string
3279 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3281 function api_lists_list($type)
3284 /// @TODO $ret is not filled here?
3285 return api_format_data('lists', $type, ["lists_list" => $ret]);
3288 /// @TODO move to top of file or somewhere better
3289 api_register_func('api/lists/list', 'api_lists_list', true);
3290 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3293 * Returns all groups the user owns.
3295 * @param string $type Return type (atom, rss, xml, json)
3297 * @return array|string
3298 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3300 function api_lists_ownerships($type)
3304 if (api_user() === false) {
3305 throw new ForbiddenException();
3309 $user_info = api_get_user($a);
3310 $uid = $user_info['uid'];
3312 $groups = dba::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3314 // loop through all groups
3316 foreach ($groups as $group) {
3317 if ($group['visible']) {
3323 'name' => $group['name'],
3324 'id' => intval($group['id']),
3325 'id_str' => (string) $group['id'],
3326 'user' => $user_info,
3330 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3333 /// @TODO move to top of file or somewhere better
3334 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3337 * Returns recent statuses from users in the specified group.
3339 * @param string $type Return type (atom, rss, xml, json)
3341 * @return array|string
3342 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3344 function api_lists_statuses($type)
3348 $user_info = api_get_user($a);
3349 if (api_user() === false || $user_info === false) {
3350 throw new ForbiddenException();
3353 unset($_REQUEST["user_id"]);
3354 unset($_GET["user_id"]);
3356 unset($_REQUEST["screen_name"]);
3357 unset($_GET["screen_name"]);
3359 if (empty($_REQUEST['list_id'])) {
3360 throw new BadRequestException('list_id not specified');
3364 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
3365 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
3369 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3370 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3371 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
3372 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
3374 $start = $page * $count;
3378 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
3380 if ($exclude_replies > 0) {
3381 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
3383 if ($conversation_id > 0) {
3384 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
3388 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
3389 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
3390 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
3391 `contact`.`id` AS `cid`, `group_member`.`gid`
3393 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
3394 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
3395 STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = `item`.`contact-id`
3396 WHERE `item`.`uid` = ? AND `verb` = ?
3397 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
3400 AND `group_member`.`gid` = ?
3401 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count),
3405 $_REQUEST['list_id']
3408 $items = api_format_items(dba::inArray($statuses), $user_info, false, $type);
3410 $data = ['status' => $items];
3414 $data = api_rss_extra($a, $data, $user_info);
3418 return api_format_data("statuses", $type, $data);
3421 /// @TODO move to top of file or somewhere better
3422 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3425 * Considers friends and followers lists to be private and won't return
3426 * anything if any user_id parameter is passed.
3428 * @brief Returns either the friends of the follower list
3430 * @param string $qtype Either "friends" or "followers"
3431 * @return boolean|array
3432 * @throws ForbiddenException
3434 function api_statuses_f($qtype)
3438 if (api_user() === false) {
3439 throw new ForbiddenException();
3443 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3444 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3448 $start = ($page - 1) * $count;
3450 $user_info = api_get_user($a);
3452 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3453 /* this is to stop Hotot to load friends multiple times
3454 * I'm not sure if I'm missing return something or
3455 * is a bug in hotot. Workaround, meantime
3459 return array('$users' => $ret);*/
3464 if ($qtype == 'friends') {
3465 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3466 } elseif ($qtype == 'followers') {
3467 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3470 // friends and followers only for self
3471 if ($user_info['self'] == 0) {
3472 $sql_extra = " AND false ";
3475 if ($qtype == 'blocks') {
3476 $sql_filter = 'AND `blocked` AND NOT `pending`';
3477 } elseif ($qtype == 'incoming') {
3478 $sql_filter = 'AND `pending`';
3480 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3498 foreach ($r as $cid) {
3499 $user = api_get_user($a, $cid['nurl']);
3500 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3501 unset($user["uid"]);
3502 unset($user["self"]);
3509 return ['user' => $ret];
3514 * Returns the user's friends.
3516 * @brief Returns the list of friends of the provided user
3518 * @deprecated By Twitter API in favor of friends/list
3520 * @param string $type Either "json" or "xml"
3521 * @return boolean|string|array
3523 function api_statuses_friends($type)
3525 $data = api_statuses_f("friends");
3526 if ($data === false) {
3529 return api_format_data("users", $type, $data);
3533 * Returns the user's followers.
3535 * @brief Returns the list of followers of the provided user
3537 * @deprecated By Twitter API in favor of friends/list
3539 * @param string $type Either "json" or "xml"
3540 * @return boolean|string|array
3542 function api_statuses_followers($type)
3544 $data = api_statuses_f("followers");
3545 if ($data === false) {
3548 return api_format_data("users", $type, $data);
3551 /// @TODO move to top of file or somewhere better
3552 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3553 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3556 * Returns the list of blocked users
3558 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3560 * @param string $type Either "json" or "xml"
3562 * @return boolean|string|array
3564 function api_blocks_list($type)
3566 $data = api_statuses_f('blocks');
3567 if ($data === false) {
3570 return api_format_data("users", $type, $data);
3573 /// @TODO move to top of file or somewhere better
3574 api_register_func('api/blocks/list', 'api_blocks_list', true);
3577 * Returns the list of pending users IDs
3579 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3581 * @param string $type Either "json" or "xml"
3583 * @return boolean|string|array
3585 function api_friendships_incoming($type)
3587 $data = api_statuses_f('incoming');
3588 if ($data === false) {
3593 foreach ($data['user'] as $user) {
3594 $ids[] = $user['id'];
3597 return api_format_data("ids", $type, ['id' => $ids]);
3600 /// @TODO move to top of file or somewhere better
3601 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3604 * Returns the instance's configuration information.
3606 * @param string $type Return type (atom, rss, xml, json)
3608 * @return array|string
3610 function api_statusnet_config($type)
3614 $name = $a->config['sitename'];
3615 $server = $a->get_hostname();
3616 $logo = System::baseUrl() . '/images/friendica-64.png';
3617 $email = $a->config['admin_email'];
3618 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3619 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3620 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3621 if ($a->config['api_import_size']) {
3622 $textlimit = (string) $a->config['api_import_size'];
3624 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3625 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3628 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3629 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3630 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3631 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3632 'shorturllength' => '30',
3634 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3635 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3636 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3637 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3642 return api_format_data('config', $type, ['config' => $config]);
3645 /// @TODO move to top of file or somewhere better
3646 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3647 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3651 * @param string $type Return type (atom, rss, xml, json)
3653 * @return array|string
3655 function api_statusnet_version($type)
3658 $fake_statusnet_version = "0.9.7";
3660 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3663 /// @TODO move to top of file or somewhere better
3664 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3665 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3669 * @param string $type Return type (atom, rss, xml, json)
3671 * @todo use api_format_data() to return data
3673 function api_ff_ids($type)
3676 throw new ForbiddenException();
3683 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3686 "SELECT `pcontact`.`id` FROM `contact`
3687 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3688 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3691 if (!DBM::is_result($r)) {
3696 foreach ($r as $rr) {
3697 if ($stringify_ids) {
3700 $ids[] = intval($rr['id']);
3704 return api_format_data("ids", $type, ['id' => $ids]);
3708 * Returns the ID of every user the user is following.
3710 * @param string $type Return type (atom, rss, xml, json)
3712 * @return array|string
3713 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3715 function api_friends_ids($type)
3717 return api_ff_ids($type);
3721 * Returns the ID of every user following the user.
3723 * @param string $type Return type (atom, rss, xml, json)
3725 * @return array|string
3726 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3728 function api_followers_ids($type)
3730 return api_ff_ids($type);
3733 /// @TODO move to top of file or somewhere better
3734 api_register_func('api/friends/ids', 'api_friends_ids', true);
3735 api_register_func('api/followers/ids', 'api_followers_ids', true);
3738 * Sends a new direct message.
3740 * @param string $type Return type (atom, rss, xml, json)
3742 * @return array|string
3743 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3745 function api_direct_messages_new($type)
3750 if (api_user() === false) {
3751 throw new ForbiddenException();
3754 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3758 $sender = api_get_user($a);
3760 if ($_POST['screen_name']) {
3762 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3764 dbesc($_POST['screen_name'])
3767 // Selecting the id by priority, friendica first
3768 api_best_nickname($r);
3770 $recipient = api_get_user($a, $r[0]['nurl']);
3772 $recipient = api_get_user($a, $_POST['user_id']);
3777 if (x($_REQUEST, 'replyto')) {
3779 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3781 intval($_REQUEST['replyto'])
3783 $replyto = $r[0]['parent-uri'];
3784 $sub = $r[0]['title'];
3786 if (x($_REQUEST, 'title')) {
3787 $sub = $_REQUEST['title'];
3789 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3793 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3796 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3797 $ret = api_format_messages($r[0], $recipient, $sender);
3799 $ret = ["error"=>$id];
3802 $data = ['direct_message'=>$ret];
3807 $data = api_rss_extra($a, $data, $sender);
3810 return api_format_data("direct-messages", $type, $data);
3813 /// @TODO move to top of file or somewhere better
3814 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3817 * Destroys a direct message.
3819 * @brief delete a direct_message from mail table through api
3821 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3822 * @return string|array
3823 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3825 function api_direct_messages_destroy($type)
3829 if (api_user() === false) {
3830 throw new ForbiddenException();
3834 $user_info = api_get_user($a);
3836 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3838 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3839 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3840 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3842 $uid = $user_info['uid'];
3843 // error if no id or parenturi specified (for clients posting parent-uri as well)
3844 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3845 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3846 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3849 // BadRequestException if no id specified (for clients using Twitter API)
3851 throw new BadRequestException('Message id not specified');
3854 // add parent-uri to sql command if specified by calling app
3855 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3857 // get data of the specified message id
3859 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3864 // error message if specified id is not in database
3865 if (!DBM::is_result($r)) {
3866 if ($verbose == "true") {
3867 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3868 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3870 /// @todo BadRequestException ok for Twitter API clients?
3871 throw new BadRequestException('message id not in database');
3876 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3881 if ($verbose == "true") {
3884 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3885 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3887 $answer = ['result' => 'error', 'message' => 'unknown error'];
3888 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3891 /// @todo return JSON data like Twitter API not yet implemented
3894 /// @TODO move to top of file or somewhere better
3895 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3899 * @param string $type Return type (atom, rss, xml, json)
3900 * @param string $box
3901 * @param string $verbose
3903 * @return array|string
3905 function api_direct_messages_box($type, $box, $verbose)
3908 $user_info = api_get_user($a);
3910 if (api_user() === false || $user_info === false) {
3911 throw new ForbiddenException();
3915 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3916 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3921 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3922 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3924 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3925 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3928 unset($_REQUEST["user_id"]);
3929 unset($_GET["user_id"]);
3931 unset($_REQUEST["screen_name"]);
3932 unset($_GET["screen_name"]);
3934 $profile_url = $user_info["url"];
3937 $start = $page * $count;
3942 if ($box=="sentbox") {
3943 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3944 } elseif ($box == "conversation") {
3945 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3946 } elseif ($box == "all") {
3947 $sql_extra = "true";
3948 } elseif ($box == "inbox") {
3949 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3953 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3956 if ($user_id != "") {
3957 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3958 } elseif ($screen_name !="") {
3959 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3963 "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",
3969 if ($verbose == "true" && !DBM::is_result($r)) {
3970 $answer = ['result' => 'error', 'message' => 'no mails available'];
3971 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3975 foreach ($r as $item) {
3976 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3977 $recipient = $user_info;
3978 $sender = api_get_user($a, normalise_link($item['contact-url']));
3979 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3980 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3981 $sender = $user_info;
3984 if (isset($recipient) && isset($sender)) {
3985 $ret[] = api_format_messages($item, $recipient, $sender);
3990 $data = ['direct_message' => $ret];
3994 $data = api_rss_extra($a, $data, $user_info);
3997 return api_format_data("direct-messages", $type, $data);
4001 * Returns the most recent direct messages sent by the user.
4003 * @param string $type Return type (atom, rss, xml, json)
4005 * @return array|string
4006 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4008 function api_direct_messages_sentbox($type)
4010 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
4011 return api_direct_messages_box($type, "sentbox", $verbose);
4015 * Returns the most recent direct messages sent to the user.
4017 * @param string $type Return type (atom, rss, xml, json)
4019 * @return array|string
4020 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4022 function api_direct_messages_inbox($type)
4024 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
4025 return api_direct_messages_box($type, "inbox", $verbose);
4030 * @param string $type Return type (atom, rss, xml, json)
4032 * @return array|string
4034 function api_direct_messages_all($type)
4036 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
4037 return api_direct_messages_box($type, "all", $verbose);
4042 * @param string $type Return type (atom, rss, xml, json)
4044 * @return array|string
4046 function api_direct_messages_conversation($type)
4048 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
4049 return api_direct_messages_box($type, "conversation", $verbose);
4052 /// @TODO move to top of file or somewhere better
4053 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4054 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4055 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4056 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4059 * Returns an OAuth Request Token.
4061 * @see https://oauth.net/core/1.0/#auth_step1
4063 function api_oauth_request_token()
4065 $oauth1 = new FKOAuth1();
4067 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4068 } catch (Exception $e) {
4069 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4077 * Returns an OAuth Access Token.
4079 * @return array|string
4080 * @see https://oauth.net/core/1.0/#auth_step3
4082 function api_oauth_access_token()
4084 $oauth1 = new FKOAuth1();
4086 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4087 } catch (Exception $e) {
4088 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4095 /// @TODO move to top of file or somewhere better
4096 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4097 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4101 * @brief delete a complete photoalbum with all containing photos from database through api
4103 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4104 * @return string|array
4106 function api_fr_photoalbum_delete($type)
4108 if (api_user() === false) {
4109 throw new ForbiddenException();
4112 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
4114 // we do not allow calls without album string
4116 throw new BadRequestException("no albumname specified");
4118 // check if album is existing
4120 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4124 if (!DBM::is_result($r)) {
4125 throw new BadRequestException("album not available");
4128 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4129 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4130 foreach ($r as $rr) {
4132 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4133 intval(local_user()),
4134 dbesc($rr['resource-id'])
4137 if (!DBM::is_result($photo_item)) {
4138 throw new InternalServerErrorException("problem with deleting items occured");
4140 Item::deleteById($photo_item[0]['id']);
4143 // now let's delete all photos from the album
4144 $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
4146 // return success of deletion or error message
4148 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4149 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4151 throw new InternalServerErrorException("unknown error - deleting from database failed");
4156 * @brief update the name of the album for all photos of an album
4158 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4159 * @return string|array
4161 function api_fr_photoalbum_update($type)
4163 if (api_user() === false) {
4164 throw new ForbiddenException();
4167 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
4168 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
4170 // we do not allow calls without album string
4172 throw new BadRequestException("no albumname specified");
4174 if ($album_new == "") {
4175 throw new BadRequestException("no new albumname specified");
4177 // check if album is existing
4179 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4183 if (!DBM::is_result($r)) {
4184 throw new BadRequestException("album not available");
4186 // now let's update all photos to the albumname
4188 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
4194 // return success of updating or error message
4196 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4197 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4199 throw new InternalServerErrorException("unknown error - updating in database failed");
4205 * @brief list all photos of the authenticated user
4207 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4208 * @return string|array
4210 function api_fr_photos_list($type)
4212 if (api_user() === false) {
4213 throw new ForbiddenException();
4216 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4217 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4218 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4219 intval(local_user())
4222 'image/jpeg' => 'jpg',
4223 'image/png' => 'png',
4224 'image/gif' => 'gif'
4226 $data = ['photo'=>[]];
4227 if (DBM::is_result($r)) {
4228 foreach ($r as $rr) {
4230 $photo['id'] = $rr['resource-id'];
4231 $photo['album'] = $rr['album'];
4232 $photo['filename'] = $rr['filename'];
4233 $photo['type'] = $rr['type'];
4234 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4235 $photo['created'] = $rr['created'];
4236 $photo['edited'] = $rr['edited'];
4237 $photo['desc'] = $rr['desc'];
4239 if ($type == "xml") {
4240 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4242 $photo['thumb'] = $thumb;
4243 $data['photo'][] = $photo;
4247 return api_format_data("photos", $type, $data);
4251 * @brief upload a new photo or change an existing photo
4253 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4254 * @return string|array
4256 function api_fr_photo_create_update($type)
4258 if (api_user() === false) {
4259 throw new ForbiddenException();
4262 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4263 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4264 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4265 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4266 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4267 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4268 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4269 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4270 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4272 // do several checks on input parameters
4273 // we do not allow calls without album string
4274 if ($album == null) {
4275 throw new BadRequestException("no albumname specified");
4277 // if photo_id == null --> we are uploading a new photo
4278 if ($photo_id == null) {
4281 // error if no media posted in create-mode
4282 if (!x($_FILES, 'media')) {
4284 throw new BadRequestException("no media data submitted");
4287 // album_new will be ignored in create-mode
4292 // check if photo is existing in database
4294 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4299 if (!DBM::is_result($r)) {
4300 throw new BadRequestException("photo not available");
4304 // checks on acl strings provided by clients
4305 $acl_input_error = false;
4306 $acl_input_error |= check_acl_input($allow_cid);
4307 $acl_input_error |= check_acl_input($deny_cid);
4308 $acl_input_error |= check_acl_input($allow_gid);
4309 $acl_input_error |= check_acl_input($deny_gid);
4310 if ($acl_input_error) {
4311 throw new BadRequestException("acl data invalid");
4313 // now let's upload the new media in create-mode
4314 if ($mode == "create") {
4315 $media = $_FILES['media'];
4316 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4318 // return success of updating or error message
4319 if (!is_null($data)) {
4320 return api_format_data("photo_create", $type, $data);
4322 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4326 // now let's do the changes in update-mode
4327 if ($mode == "update") {
4330 if (!is_null($desc)) {
4331 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4334 if (!is_null($album_new)) {
4335 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4338 if (!is_null($allow_cid)) {
4339 $allow_cid = trim($allow_cid);
4340 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4343 if (!is_null($deny_cid)) {
4344 $deny_cid = trim($deny_cid);
4345 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4348 if (!is_null($allow_gid)) {
4349 $allow_gid = trim($allow_gid);
4350 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4353 if (!is_null($deny_gid)) {
4354 $deny_gid = trim($deny_gid);
4355 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4359 if ($sql_extra != "") {
4360 $nothingtodo = false;
4362 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4364 DateTimeFormat::utcNow(), // update edited timestamp
4370 $nothingtodo = true;
4373 if (x($_FILES, 'media')) {
4374 $nothingtodo = false;
4375 $media = $_FILES['media'];
4376 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4377 if (!is_null($data)) {
4378 return api_format_data("photo_update", $type, $data);
4382 // return success of updating or error message
4384 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4385 return api_format_data("photo_update", $type, ['$result' => $answer]);
4388 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4389 return api_format_data("photo_update", $type, ['$result' => $answer]);
4391 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4394 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4399 * @brief delete a single photo from the database through api
4401 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4402 * @return string|array
4404 function api_fr_photo_delete($type)
4406 if (api_user() === false) {
4407 throw new ForbiddenException();
4410 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4412 // do several checks on input parameters
4413 // we do not allow calls without photo id
4414 if ($photo_id == null) {
4415 throw new BadRequestException("no photo_id specified");
4417 // check if photo is existing in database
4419 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4423 if (!DBM::is_result($r)) {
4424 throw new BadRequestException("photo not available");
4426 // now we can perform on the deletion of the photo
4427 $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4429 // return success of deletion or error message
4431 // retrieve the id of the parent element (the photo element)
4433 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4434 intval(local_user()),
4438 if (!DBM::is_result($photo_item)) {
4439 throw new InternalServerErrorException("problem with deleting items occured");
4441 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4442 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4443 Item::deleteById($photo_item[0]['id']);
4445 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4446 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4448 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4454 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4456 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4457 * @return string|array
4459 function api_fr_photo_detail($type)
4461 if (api_user() === false) {
4462 throw new ForbiddenException();
4464 if (!x($_REQUEST, 'photo_id')) {
4465 throw new BadRequestException("No photo id.");
4468 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4469 $photo_id = $_REQUEST['photo_id'];
4471 // prepare json/xml output with data from database for the requested photo
4472 $data = prepare_photo_data($type, $scale, $photo_id);
4474 return api_format_data("photo_detail", $type, $data);
4479 * Updates the user’s profile image.
4481 * @brief updates the profile image for the user (either a specified profile or the default profile)
4483 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4485 * @return string|array
4486 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4488 function api_account_update_profile_image($type)
4490 if (api_user() === false) {
4491 throw new ForbiddenException();
4494 $profileid = defaults($_REQUEST, 'profile_id', 0);
4496 // error if image data is missing
4497 if (!x($_FILES, 'image')) {
4498 throw new BadRequestException("no media data submitted");
4501 // check if specified profile id is valid
4502 if ($profileid != 0) {
4504 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4508 // error message if specified profile id is not in database
4509 if (!DBM::is_result($r)) {
4510 throw new BadRequestException("profile_id not available");
4512 $is_default_profile = $r['profile'];
4514 $is_default_profile = 1;
4517 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4519 if (x($_FILES, 'image')) {
4520 $media = $_FILES['image'];
4521 } elseif (x($_FILES, 'media')) {
4522 $media = $_FILES['media'];
4524 // save new profile image
4525 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4528 if (is_array($media['type'])) {
4529 $filetype = $media['type'][0];
4531 $filetype = $media['type'];
4533 if ($filetype == "image/jpeg") {
4535 } elseif ($filetype == "image/png") {
4538 throw new InternalServerErrorException('Unsupported filetype');
4540 // change specified profile or all profiles to the new resource-id
4541 if ($is_default_profile) {
4543 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4544 dbesc($data['photo']['id']),
4545 intval(local_user())
4549 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
4550 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4551 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4552 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4553 intval(local_user())
4557 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4558 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4559 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4560 intval($_REQUEST['profile']),
4561 intval(local_user())
4565 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4566 // so that browsers will do a cache update unconditionally
4569 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4570 dbesc(DateTimeFormat::utcNow()),
4571 intval(local_user())
4574 // Update global directory in background
4575 //$user = api_get_user(get_app());
4576 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4577 if ($url && strlen(Config::get('system', 'directory'))) {
4578 Worker::add(PRIORITY_LOW, "Directory", $url);
4581 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4583 // output for client
4585 return api_account_verify_credentials($type);
4587 // SaveMediaToDatabase failed for some reason
4588 throw new InternalServerErrorException("image upload failed");
4592 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4593 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4594 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4595 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4596 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4597 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4598 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4599 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4600 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4603 * Update user profile
4605 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4607 * @return array|string
4609 function api_account_update_profile($type)
4611 $local_user = api_user();
4612 $api_user = api_get_user(get_app());
4614 if (!empty($_POST['name'])) {
4615 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4616 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4617 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4618 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4621 if (isset($_POST['description'])) {
4622 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4623 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4624 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4627 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4628 // Update global directory in background
4629 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4630 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4633 return api_account_verify_credentials($type);
4636 /// @TODO move to top of file or somewhere better
4637 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4641 * @param string $acl_string
4643 function check_acl_input($acl_string)
4645 if ($acl_string == null || $acl_string == " ") {
4648 $contact_not_found = false;
4650 // split <x><y><z> into array of cid's
4651 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4653 // check for each cid if it is available on server
4654 $cid_array = $array[0];
4655 foreach ($cid_array as $cid) {
4656 $cid = str_replace("<", "", $cid);
4657 $cid = str_replace(">", "", $cid);
4659 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4663 $contact_not_found |= !DBM::is_result($contact);
4665 return $contact_not_found;
4670 * @param string $mediatype
4671 * @param array $media
4672 * @param string $type
4673 * @param string $album
4674 * @param string $allow_cid
4675 * @param string $deny_cid
4676 * @param string $allow_gid
4677 * @param string $deny_gid
4678 * @param string $desc
4679 * @param integer $profile
4680 * @param boolean $visibility
4681 * @param string $photo_id
4683 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)
4691 if (is_array($media)) {
4692 if (is_array($media['tmp_name'])) {
4693 $src = $media['tmp_name'][0];
4695 $src = $media['tmp_name'];
4697 if (is_array($media['name'])) {
4698 $filename = basename($media['name'][0]);
4700 $filename = basename($media['name']);
4702 if (is_array($media['size'])) {
4703 $filesize = intval($media['size'][0]);
4705 $filesize = intval($media['size']);
4707 if (is_array($media['type'])) {
4708 $filetype = $media['type'][0];
4710 $filetype = $media['type'];
4714 if ($filetype == "") {
4715 $filetype=Image::guessType($filename);
4717 $imagedata = getimagesize($src);
4719 $filetype = $imagedata['mime'];
4722 "File upload src: " . $src . " - filename: " . $filename .
4723 " - size: " . $filesize . " - type: " . $filetype,
4727 // check if there was a php upload error
4728 if ($filesize == 0 && $media['error'] == 1) {
4729 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4731 // check against max upload size within Friendica instance
4732 $maximagesize = Config::get('system', 'maximagesize');
4733 if ($maximagesize && ($filesize > $maximagesize)) {
4734 $formattedBytes = formatBytes($maximagesize);
4735 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4738 // create Photo instance with the data of the image
4739 $imagedata = @file_get_contents($src);
4740 $Image = new Image($imagedata, $filetype);
4741 if (! $Image->isValid()) {
4742 throw new InternalServerErrorException("unable to process image data");
4745 // check orientation of image
4746 $Image->orient($src);
4749 // check max length of images on server
4750 $max_length = Config::get('system', 'max_image_length');
4751 if (! $max_length) {
4752 $max_length = MAX_IMAGE_LENGTH;
4754 if ($max_length > 0) {
4755 $Image->scaleDown($max_length);
4756 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4758 $width = $Image->getWidth();
4759 $height = $Image->getHeight();
4761 // create a new resource-id if not already provided
4762 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4764 if ($mediatype == "photo") {
4765 // upload normal image (scales 0, 1, 2)
4766 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4768 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4770 logger("photo upload: image upload with scale 0 (original size) failed");
4772 if ($width > 640 || $height > 640) {
4773 $Image->scaleDown(640);
4774 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4776 logger("photo upload: image upload with scale 1 (640x640) failed");
4780 if ($width > 320 || $height > 320) {
4781 $Image->scaleDown(320);
4782 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4784 logger("photo upload: image upload with scale 2 (320x320) failed");
4787 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4788 } elseif ($mediatype == "profileimage") {
4789 // upload profile image (scales 4, 5, 6)
4790 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4792 if ($width > 175 || $height > 175) {
4793 $Image->scaleDown(175);
4794 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4796 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4800 if ($width > 80 || $height > 80) {
4801 $Image->scaleDown(80);
4802 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4804 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4808 if ($width > 48 || $height > 48) {
4809 $Image->scaleDown(48);
4810 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4812 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4815 $Image->__destruct();
4816 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4819 if (isset($r) && $r) {
4820 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4821 if ($photo_id == null && $mediatype == "photo") {
4822 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4824 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4825 return prepare_photo_data($type, false, $hash);
4827 throw new InternalServerErrorException("image upload failed");
4833 * @param string $hash
4834 * @param string $allow_cid
4835 * @param string $deny_cid
4836 * @param string $allow_gid
4837 * @param string $deny_gid
4838 * @param string $filetype
4839 * @param boolean $visibility
4841 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4843 // get data about the api authenticated user
4844 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4845 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4848 $arr['guid'] = get_guid(32);
4849 $arr['uid'] = intval(api_user());
4851 $arr['parent-uri'] = $uri;
4852 $arr['type'] = 'photo';
4854 $arr['resource-id'] = $hash;
4855 $arr['contact-id'] = $owner_record[0]['id'];
4856 $arr['owner-name'] = $owner_record[0]['name'];
4857 $arr['owner-link'] = $owner_record[0]['url'];
4858 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4859 $arr['author-name'] = $owner_record[0]['name'];
4860 $arr['author-link'] = $owner_record[0]['url'];
4861 $arr['author-avatar'] = $owner_record[0]['thumb'];
4863 $arr['allow_cid'] = $allow_cid;
4864 $arr['allow_gid'] = $allow_gid;
4865 $arr['deny_cid'] = $deny_cid;
4866 $arr['deny_gid'] = $deny_gid;
4867 $arr['visible'] = $visibility;
4871 'image/jpeg' => 'jpg',
4872 'image/png' => 'png',
4873 'image/gif' => 'gif'
4876 // adds link to the thumbnail scale photo
4877 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4878 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4881 // do the magic for storing the item in the database and trigger the federation to other contacts
4887 * @param string $type
4889 * @param string $photo_id
4893 function prepare_photo_data($type, $scale, $photo_id)
4896 $user_info = api_get_user($a);
4898 if ($user_info === false) {
4899 throw new ForbiddenException();
4902 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4903 $data_sql = ($scale === false ? "" : "data, ");
4905 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4906 // clients needs to convert this in their way for further processing
4908 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4909 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4910 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4911 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4913 intval(local_user()),
4919 'image/jpeg' => 'jpg',
4920 'image/png' => 'png',
4921 'image/gif' => 'gif'
4924 // prepare output data for photo
4925 if (DBM::is_result($r)) {
4926 $data = ['photo' => $r[0]];
4927 $data['photo']['id'] = $data['photo']['resource-id'];
4928 if ($scale !== false) {
4929 $data['photo']['data'] = base64_encode($data['photo']['data']);
4931 unset($data['photo']['datasize']); //needed only with scale param
4933 if ($type == "xml") {
4934 $data['photo']['links'] = [];
4935 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4936 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4938 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4941 $data['photo']['link'] = [];
4942 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4944 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4945 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4949 unset($data['photo']['resource-id']);
4950 unset($data['photo']['minscale']);
4951 unset($data['photo']['maxscale']);
4953 throw new NotFoundException();
4956 // retrieve item element for getting activities (like, dislike etc.) related to photo
4958 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4959 intval(local_user()),
4962 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4964 // retrieve comments on photo
4966 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4967 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4968 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4969 `contact`.`id` AS `cid`
4971 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4972 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4973 WHERE `item`.`parent` = %d AND `item`.`visible`
4974 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4975 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4976 intval($item[0]['parent']),
4978 dbesc(ACTIVITY_POST)
4981 // prepare output of comments
4982 $commentData = api_format_items($r, $user_info, false, $type);
4984 if ($type == "xml") {
4986 foreach ($commentData as $comment) {
4987 $comments[$k++ . ":comment"] = $comment;
4990 foreach ($commentData as $comment) {
4991 $comments[] = $comment;
4994 $data['photo']['friendica_comments'] = $comments;
4996 // include info if rights on photo and rights on item are mismatching
4997 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4998 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4999 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5000 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5001 $data['photo']['rights_mismatch'] = $rights_mismatch;
5008 * Similar as /mod/redir.php
5009 * redirect to 'url' after dfrn auth
5011 * Why this when there is mod/redir.php already?
5012 * This use api_user() and api_login()
5015 * c_url: url of remote contact to auth to
5016 * url: string, url to redirect after auth
5018 function api_friendica_remoteauth()
5020 $url = (x($_GET, 'url') ? $_GET['url'] : '');
5021 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
5023 if ($url === '' || $c_url === '') {
5024 throw new BadRequestException("Wrong parameters.");
5027 $c_url = normalise_link($c_url);
5031 $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5033 if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
5034 throw new BadRequestException("Unknown contact");
5037 $cid = $contact['id'];
5039 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
5041 if ($contact['duplex'] && $contact['issued-id']) {
5042 $orig_id = $contact['issued-id'];
5043 $dfrn_id = '1:' . $orig_id;
5045 if ($contact['duplex'] && $contact['dfrn-id']) {
5046 $orig_id = $contact['dfrn-id'];
5047 $dfrn_id = '0:' . $orig_id;
5050 $sec = random_string();
5053 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
5054 VALUES( %d, %s, '%s', '%s', %d )",
5062 logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
5063 $dest = ($url ? '&destination_url=' . $url : '');
5065 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5066 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5067 . '&type=profile&sec=' . $sec . $dest
5070 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5073 * @brief Return the item shared, if the item contains only the [share] tag
5075 * @param array $item Sharer item
5076 * @return array|false Shared item or false if not a reshare
5078 function api_share_as_retweet(&$item)
5080 $body = trim($item["body"]);
5082 if (Diaspora::isReshare($body, false)===false) {
5086 /// @TODO "$1" should maybe mean '$1' ?
5087 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
5089 * Skip if there is no shared message in there
5090 * we already checked this in diaspora::isReshare()
5091 * but better one more than one less...
5093 if ($body == $attributes) {
5098 // build the fake reshared item
5099 $reshared_item = $item;
5102 preg_match("/author='(.*?)'/ism", $attributes, $matches);
5103 if ($matches[1] != "") {
5104 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
5107 preg_match('/author="(.*?)"/ism', $attributes, $matches);
5108 if ($matches[1] != "") {
5109 $author = $matches[1];
5113 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
5114 if ($matches[1] != "") {
5115 $profile = $matches[1];
5118 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
5119 if ($matches[1] != "") {
5120 $profile = $matches[1];
5124 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
5125 if ($matches[1] != "") {
5126 $avatar = $matches[1];
5129 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
5130 if ($matches[1] != "") {
5131 $avatar = $matches[1];
5135 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5136 if ($matches[1] != "") {
5137 $link = $matches[1];
5140 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5141 if ($matches[1] != "") {
5142 $link = $matches[1];
5146 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5147 if ($matches[1] != "") {
5148 $posted = $matches[1];
5151 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5152 if ($matches[1] != "") {
5153 $posted = $matches[1];
5156 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5158 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5162 $reshared_item["body"] = $shared_body;
5163 $reshared_item["author-name"] = $author;
5164 $reshared_item["author-link"] = $profile;
5165 $reshared_item["author-avatar"] = $avatar;
5166 $reshared_item["plink"] = $link;
5167 $reshared_item["created"] = $posted;
5168 $reshared_item["edited"] = $posted;
5170 return $reshared_item;
5175 * @param string $profile
5177 * @return string|false
5178 * @todo remove trailing junk from profile url
5179 * @todo pump.io check has to check the website
5181 function api_get_nick($profile)
5186 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5187 dbesc(normalise_link($profile))
5190 if (DBM::is_result($r)) {
5191 $nick = $r[0]["nick"];
5196 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5197 dbesc(normalise_link($profile))
5200 if (DBM::is_result($r)) {
5201 $nick = $r[0]["nick"];
5206 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5207 if ($friendica != $profile) {
5213 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5214 if ($diaspora != $profile) {
5220 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5221 if ($twitter != $profile) {
5228 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5229 if ($StatusnetHost != $profile) {
5230 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5231 if ($StatusnetUser != $profile) {
5232 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5233 $user = json_decode($UserData);
5235 $nick = $user->screen_name;
5241 // To-Do: look at the page if its really a pumpio site
5242 //if (!$nick == "") {
5243 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5244 // if ($pumpio != $profile)
5246 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5259 * @param array $item
5263 function api_in_reply_to($item)
5267 $in_reply_to['status_id'] = null;
5268 $in_reply_to['user_id'] = null;
5269 $in_reply_to['status_id_str'] = null;
5270 $in_reply_to['user_id_str'] = null;
5271 $in_reply_to['screen_name'] = null;
5273 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5275 "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
5276 intval($item['uid']),
5277 dbesc($item['thr-parent'])
5280 if (DBM::is_result($r)) {
5281 $in_reply_to['status_id'] = intval($r[0]['id']);
5283 $in_reply_to['status_id'] = intval($item['parent']);
5286 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5289 "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
5290 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
5291 WHERE `item`.`id` = %d LIMIT 1",
5292 intval($in_reply_to['status_id'])
5295 if (DBM::is_result($r)) {
5296 if ($r[0]['nick'] == "") {
5297 $r[0]['nick'] = api_get_nick($r[0]["url"]);
5300 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
5301 $in_reply_to['user_id'] = intval($r[0]['id']);
5302 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
5305 // There seems to be situation, where both fields are identical:
5306 // https://github.com/friendica/friendica/issues/1010
5307 // This is a bugfix for that.
5308 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5309 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
5310 $in_reply_to['status_id'] = null;
5311 $in_reply_to['user_id'] = null;
5312 $in_reply_to['status_id_str'] = null;
5313 $in_reply_to['user_id_str'] = null;
5314 $in_reply_to['screen_name'] = null;
5318 return $in_reply_to;
5323 * @param string $Text
5327 function api_clean_plain_items($Text)
5329 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5331 $Text = BBCode::cleanPictureLinks($Text);
5332 $URLSearchString = "^\[\]";
5334 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
5336 if ($include_entities == "true") {
5337 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
5340 // Simplify "attachment" element
5341 $Text = api_clean_attachments($Text);
5347 * @brief Removes most sharing information for API text export
5349 * @param string $body The original body
5351 * @return string Cleaned body
5353 function api_clean_attachments($body)
5355 $data = BBCode::getAttachmentData($body);
5362 if (isset($data["text"])) {
5363 $body = $data["text"];
5365 if (($body == "") && isset($data["title"])) {
5366 $body = $data["title"];
5368 if (isset($data["url"])) {
5369 $body .= "\n".$data["url"];
5371 $body .= $data["after"];
5378 * @param array $contacts
5382 function api_best_nickname(&$contacts)
5386 if (count($contacts) == 0) {
5390 foreach ($contacts as $contact) {
5391 if ($contact["network"] == "") {
5392 $contact["network"] = "dfrn";
5393 $best_contact = [$contact];
5397 if (sizeof($best_contact) == 0) {
5398 foreach ($contacts as $contact) {
5399 if ($contact["network"] == "dfrn") {
5400 $best_contact = [$contact];
5405 if (sizeof($best_contact) == 0) {
5406 foreach ($contacts as $contact) {
5407 if ($contact["network"] == "dspr") {
5408 $best_contact = [$contact];
5413 if (sizeof($best_contact) == 0) {
5414 foreach ($contacts as $contact) {
5415 if ($contact["network"] == "stat") {
5416 $best_contact = [$contact];
5421 if (sizeof($best_contact) == 0) {
5422 foreach ($contacts as $contact) {
5423 if ($contact["network"] == "pump") {
5424 $best_contact = [$contact];
5429 if (sizeof($best_contact) == 0) {
5430 foreach ($contacts as $contact) {
5431 if ($contact["network"] == "twit") {
5432 $best_contact = [$contact];
5437 if (sizeof($best_contact) == 1) {
5438 $contacts = $best_contact;
5440 $contacts = [$contacts[0]];
5445 * Return all or a specified group of the user with the containing contacts.
5447 * @param string $type Return type (atom, rss, xml, json)
5449 * @return array|string
5451 function api_friendica_group_show($type)
5455 if (api_user() === false) {
5456 throw new ForbiddenException();
5460 $user_info = api_get_user($a);
5461 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5462 $uid = $user_info['uid'];
5464 // get data of the specified group id or all groups if not specified
5467 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5471 // error message if specified gid is not in database
5472 if (!DBM::is_result($r)) {
5473 throw new BadRequestException("gid not available");
5477 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5482 // loop through all groups and retrieve all members for adding data in the user array
5484 foreach ($r as $rr) {
5485 $members = Contact::getByGroupId($rr['id']);
5488 if ($type == "xml") {
5489 $user_element = "users";
5491 foreach ($members as $member) {
5492 $user = api_get_user($a, $member['nurl']);
5493 $users[$k++.":user"] = $user;
5496 $user_element = "user";
5497 foreach ($members as $member) {
5498 $user = api_get_user($a, $member['nurl']);
5502 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5504 return api_format_data("groups", $type, ['group' => $grps]);
5506 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5510 * Delete the specified group of the user.
5512 * @param string $type Return type (atom, rss, xml, json)
5514 * @return array|string
5516 function api_friendica_group_delete($type)
5520 if (api_user() === false) {
5521 throw new ForbiddenException();
5525 $user_info = api_get_user($a);
5526 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5527 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5528 $uid = $user_info['uid'];
5530 // error if no gid specified
5531 if ($gid == 0 || $name == "") {
5532 throw new BadRequestException('gid or name not specified');
5535 // get data of the specified group id
5537 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5541 // error message if specified gid is not in database
5542 if (!DBM::is_result($r)) {
5543 throw new BadRequestException('gid not available');
5546 // get data of the specified group id and group name
5548 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5553 // error message if specified gid is not in database
5554 if (!DBM::is_result($rname)) {
5555 throw new BadRequestException('wrong group name');
5559 $ret = Group::removeByName($uid, $name);
5562 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5563 return api_format_data("group_delete", $type, ['result' => $success]);
5565 throw new BadRequestException('other API error');
5568 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5573 * @param string $type Return type (atom, rss, xml, json)
5575 * @return array|string
5576 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5578 function api_lists_destroy($type)
5582 if (api_user() === false) {
5583 throw new ForbiddenException();
5587 $user_info = api_get_user($a);
5588 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5589 $uid = $user_info['uid'];
5591 // error if no gid specified
5593 throw new BadRequestException('gid not specified');
5596 // get data of the specified group id
5597 $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5598 // error message if specified gid is not in database
5600 throw new BadRequestException('gid not available');
5603 if (Group::remove($gid)) {
5605 'name' => $group['name'],
5606 'id' => intval($gid),
5607 'id_str' => (string) $gid,
5608 'user' => $user_info
5611 return api_format_data("lists", $type, ['lists' => $list]);
5614 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5617 * Add a new group to the database.
5619 * @param string $name Group name
5620 * @param int $uid User ID
5621 * @param array $users List of users to add to the group
5625 function group_create($name, $uid, $users = [])
5627 // error if no name specified
5629 throw new BadRequestException('group name not specified');
5632 // get data of the specified group name
5634 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5638 // error message if specified group name already exists
5639 if (DBM::is_result($rname)) {
5640 throw new BadRequestException('group name already exists');
5643 // check if specified group name is a deleted group
5645 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5649 // error message if specified group name already exists
5650 if (DBM::is_result($rname)) {
5651 $reactivate_group = true;
5655 $ret = Group::create($uid, $name);
5657 $gid = Group::getIdByName($uid, $name);
5659 throw new BadRequestException('other API error');
5663 $erroraddinguser = false;
5665 foreach ($users as $user) {
5666 $cid = $user['cid'];
5667 // check if user really exists as contact
5669 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5673 if (count($contact)) {
5674 Group::addMember($gid, $cid);
5676 $erroraddinguser = true;
5677 $errorusers[] = $cid;
5681 // return success message incl. missing users in array
5682 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5684 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5688 * Create the specified group with the posted array of contacts.
5690 * @param string $type Return type (atom, rss, xml, json)
5692 * @return array|string
5694 function api_friendica_group_create($type)
5698 if (api_user() === false) {
5699 throw new ForbiddenException();
5703 $user_info = api_get_user($a);
5704 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5705 $uid = $user_info['uid'];
5706 $json = json_decode($_POST['json'], true);
5707 $users = $json['user'];
5709 $success = group_create($name, $uid, $users);
5711 return api_format_data("group_create", $type, ['result' => $success]);
5713 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5716 * Create a new group.
5718 * @param string $type Return type (atom, rss, xml, json)
5720 * @return array|string
5721 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5723 function api_lists_create($type)
5727 if (api_user() === false) {
5728 throw new ForbiddenException();
5732 $user_info = api_get_user($a);
5733 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5734 $uid = $user_info['uid'];
5736 $success = group_create($name, $uid);
5737 if ($success['success']) {
5739 'name' => $success['name'],
5740 'id' => intval($success['gid']),
5741 'id_str' => (string) $success['gid'],
5742 'user' => $user_info
5745 return api_format_data("lists", $type, ['lists'=>$grp]);
5748 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5751 * Update the specified group with the posted array of contacts.
5753 * @param string $type Return type (atom, rss, xml, json)
5755 * @return array|string
5757 function api_friendica_group_update($type)
5761 if (api_user() === false) {
5762 throw new ForbiddenException();
5766 $user_info = api_get_user($a);
5767 $uid = $user_info['uid'];
5768 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5769 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5770 $json = json_decode($_POST['json'], true);
5771 $users = $json['user'];
5773 // error if no name specified
5775 throw new BadRequestException('group name not specified');
5778 // error if no gid specified
5780 throw new BadRequestException('gid not specified');
5784 $members = Contact::getByGroupId($gid);
5785 foreach ($members as $member) {
5786 $cid = $member['id'];
5787 foreach ($users as $user) {
5788 $found = ($user['cid'] == $cid ? true : false);
5790 if (!isset($found) || !$found) {
5791 Group::removeMemberByName($uid, $name, $cid);
5796 $erroraddinguser = false;
5798 foreach ($users as $user) {
5799 $cid = $user['cid'];
5800 // check if user really exists as contact
5802 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5807 if (count($contact)) {
5808 Group::addMember($gid, $cid);
5810 $erroraddinguser = true;
5811 $errorusers[] = $cid;
5815 // return success message incl. missing users in array
5816 $status = ($erroraddinguser ? "missing user" : "ok");
5817 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5818 return api_format_data("group_update", $type, ['result' => $success]);
5821 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5824 * Update information about a group.
5826 * @param string $type Return type (atom, rss, xml, json)
5828 * @return array|string
5829 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5831 function api_lists_update($type)
5835 if (api_user() === false) {
5836 throw new ForbiddenException();
5840 $user_info = api_get_user($a);
5841 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5842 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5843 $uid = $user_info['uid'];
5845 // error if no gid specified
5847 throw new BadRequestException('gid not specified');
5850 // get data of the specified group id
5851 $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5852 // error message if specified gid is not in database
5854 throw new BadRequestException('gid not available');
5857 if (Group::update($gid, $name)) {
5860 'id' => intval($gid),
5861 'id_str' => (string) $gid,
5862 'user' => $user_info
5865 return api_format_data("lists", $type, ['lists' => $list]);
5869 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5873 * @param string $type Return type (atom, rss, xml, json)
5875 * @return array|string
5877 function api_friendica_activity($type)
5881 if (api_user() === false) {
5882 throw new ForbiddenException();
5884 $verb = strtolower($a->argv[3]);
5885 $verb = preg_replace("|\..*$|", "", $verb);
5887 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5889 $res = Item::performLike($id, $verb);
5892 if ($type == "xml") {
5897 return api_format_data('ok', $type, ['ok' => $ok]);
5899 throw new BadRequestException('Error adding activity');
5903 /// @TODO move to top of file or somewhere better
5904 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5905 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5906 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5907 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5908 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5909 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5910 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5911 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5912 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5913 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5916 * @brief Returns notifications
5918 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5919 * @return string|array
5921 function api_friendica_notification($type)
5925 if (api_user() === false) {
5926 throw new ForbiddenException();
5929 throw new BadRequestException("Invalid argument count");
5931 $nm = new NotificationsManager();
5933 $notes = $nm->getAll([], "+seen -date", 50);
5935 if ($type == "xml") {
5937 foreach ($notes as $note) {
5938 $xmlnotes[] = ["@attributes" => $note];
5944 return api_format_data("notes", $type, ['note' => $notes]);
5948 * POST request with 'id' param as notification id
5950 * @brief Set notification as seen and returns associated item (if possible)
5952 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5953 * @return string|array
5955 function api_friendica_notification_seen($type)
5958 $user_info = api_get_user($a);
5960 if (api_user() === false || $user_info === false) {
5961 throw new ForbiddenException();
5964 throw new BadRequestException("Invalid argument count");
5967 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5969 $nm = new NotificationsManager();
5970 $note = $nm->getByID($id);
5971 if (is_null($note)) {
5972 throw new BadRequestException("Invalid argument");
5975 $nm->setSeen($note);
5976 if ($note['otype']=='item') {
5977 // would be really better with an ItemsManager and $im->getByID() :-P
5979 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5980 intval($note['iid']),
5981 intval(local_user())
5984 // we found the item, return it to the user
5985 $ret = api_format_items($r, $user_info, false, $type);
5986 $data = ['status' => $ret];
5987 return api_format_data("status", $type, $data);
5989 // the item can't be found, but we set the note as seen, so we count this as a success
5991 return api_format_data('result', $type, ['result' => "success"]);
5994 /// @TODO move to top of file or somewhere better
5995 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5996 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5999 * @brief update a direct_message to seen state
6001 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6002 * @return string|array (success result=ok, error result=error with error message)
6004 function api_friendica_direct_messages_setseen($type)
6007 if (api_user() === false) {
6008 throw new ForbiddenException();
6012 $user_info = api_get_user($a);
6013 $uid = $user_info['uid'];
6014 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
6016 // return error if id is zero
6018 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6019 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6022 // get data of the specified message id
6024 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
6029 // error message if specified id is not in database
6030 if (!DBM::is_result($r)) {
6031 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6032 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6035 // update seen indicator
6037 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
6044 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6045 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6047 $answer = ['result' => 'error', 'message' => 'unknown error'];
6048 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6052 /// @TODO move to top of file or somewhere better
6053 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6056 * @brief search for direct_messages containing a searchstring through api
6058 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6059 * @param string $box
6060 * @return string|array (success: success=true if found and search_result contains found messages,
6061 * success=false if nothing was found, search_result='nothing found',
6062 * error: result=error with error message)
6064 function api_friendica_direct_messages_search($type, $box = "")
6068 if (api_user() === false) {
6069 throw new ForbiddenException();
6073 $user_info = api_get_user($a);
6074 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
6075 $uid = $user_info['uid'];
6077 // error if no searchstring specified
6078 if ($searchstring == "") {
6079 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6080 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6083 // get data for the specified searchstring
6085 "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",
6087 dbesc('%'.$searchstring.'%')
6090 $profile_url = $user_info["url"];
6092 // message if nothing was found
6093 if (!DBM::is_result($r)) {
6094 $success = ['success' => false, 'search_results' => 'problem with query'];
6095 } elseif (count($r) == 0) {
6096 $success = ['success' => false, 'search_results' => 'nothing found'];
6099 foreach ($r as $item) {
6100 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6101 $recipient = $user_info;
6102 $sender = api_get_user($a, normalise_link($item['contact-url']));
6103 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6104 $recipient = api_get_user($a, normalise_link($item['contact-url']));
6105 $sender = $user_info;
6108 if (isset($recipient) && isset($sender)) {
6109 $ret[] = api_format_messages($item, $recipient, $sender);
6112 $success = ['success' => true, 'search_results' => $ret];
6115 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6118 /// @TODO move to top of file or somewhere better
6119 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6122 * @brief return data of all the profiles a user has to the client
6124 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6125 * @return string|array
6127 function api_friendica_profile_show($type)
6131 if (api_user() === false) {
6132 throw new ForbiddenException();
6136 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
6138 // retrieve general information about profiles for user
6139 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6140 $directory = Config::get('system', 'directory');
6142 // get data of the specified profile id or all profiles of the user if not specified
6143 if ($profileid != 0) {
6145 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
6150 // error message if specified gid is not in database
6151 if (!DBM::is_result($r)) {
6152 throw new BadRequestException("profile_id not available");
6156 "SELECT * FROM `profile` WHERE `uid` = %d",
6160 // loop through all returned profiles and retrieve data and users
6163 foreach ($r as $rr) {
6164 $profile = api_format_items_profiles($rr);
6166 // select all users from contact table, loop and prepare standard return for user data
6169 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
6171 intval($rr['profile_id'])
6174 foreach ($nurls as $nurl) {
6175 $user = api_get_user($a, $nurl['nurl']);
6176 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6178 $profile['users'] = $users;
6180 // add prepared profile data to array for final return
6181 if ($type == "xml") {
6182 $profiles[$k++ . ":profile"] = $profile;
6184 $profiles[] = $profile;
6188 // return settings, authenticated user and profiles data
6189 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
6191 $result = ['multi_profiles' => $multi_profiles ? true : false,
6192 'global_dir' => $directory,
6193 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
6194 'profiles' => $profiles];
6195 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6197 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6200 * Returns a list of saved searches.
6202 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6204 * @param string $type Return format: json or xml
6206 * @return string|array
6208 function api_saved_searches_list($type)
6210 $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
6213 while ($term = $terms->fetch()) {
6215 'created_at' => api_date(time()),
6216 'id' => intval($term['id']),
6217 'id_str' => $term['id'],
6218 'name' => $term['term'],
6220 'query' => $term['term']
6226 return api_format_data("terms", $type, ['terms' => $result]);
6229 /// @TODO move to top of file or somewhere better
6230 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6233 @TODO Maybe open to implement?
6235 [pagename] => api/1.1/statuses/lookup.json
6236 [id] => 605138389168451584
6237 [include_cards] => true
6238 [cards_platform] => Android-12
6239 [include_entities] => true
6240 [include_my_retweet] => 1
6242 [include_reply_count] => true
6243 [include_descendent_reply_count] => true
6247 Not implemented by now:
6248 statuses/retweets_of_me
6253 account/update_location
6254 account/update_profile_background_image
6257 friendica/profile/update
6258 friendica/profile/create
6259 friendica/profile/delete
6261 Not implemented in status.net:
6262 statuses/retweeted_to_me
6263 statuses/retweeted_by_me
6264 direct_messages/destroy
6266 account/update_delivery_device
6267 notifications/follow