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));
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 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 foreach ($return as $rr) {
391 $json = json_encode($rr);
393 if (x($_GET, 'callback')) {
394 $json = $_GET['callback'] . "(" . $json . ")";
399 header("Content-Type: application/rss+xml");
400 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
403 header("Content-Type: application/atom+xml");
404 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
411 logger('API call not implemented: ' . $a->query_string);
412 throw new NotImplementedException();
413 } catch (HTTPException $e) {
414 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
415 return api_error($type, $e);
420 * @brief Format API error string
422 * @param string $type Return type (xml, json, rss, as)
423 * @param object $e HTTPException Error object
424 * @return string error message formatted as $type
426 function api_error($type, $e)
430 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
431 /// @TODO: https://dev.twitter.com/overview/api/response-codes
433 $error = ["error" => $error,
434 "code" => $e->httpcode . " " . $e->httpdesc,
435 "request" => $a->query_string];
437 $return = api_format_data('status', $type, ['status' => $error]);
441 header("Content-Type: text/xml");
444 header("Content-Type: application/json");
445 $return = json_encode($return);
448 header("Content-Type: application/rss+xml");
451 header("Content-Type: application/atom+xml");
459 * @brief Set values for RSS template
462 * @param array $arr Array to be passed to template
463 * @param array $user_info User info
465 * @todo find proper type-hints
467 function api_rss_extra(App $a, $arr, $user_info)
469 if (is_null($user_info)) {
470 $user_info = api_get_user($a);
473 $arr['$user'] = $user_info;
475 'alternate' => $user_info['url'],
476 'self' => System::baseUrl() . "/" . $a->query_string,
477 'base' => System::baseUrl(),
478 'updated' => api_date(null),
479 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
480 'language' => $user_info['language'],
481 'logo' => System::baseUrl() . "/images/friendica-32.png",
489 * @brief Unique contact to contact url.
491 * @param int $id Contact id
492 * @return bool|string
493 * Contact url or False if contact id is unknown
495 function api_unique_id_to_nurl($id)
497 $r = dba::selectFirst('contact', ['nurl'], ['uid' => 0, 'id' => $id]);
499 if (DBM::is_result($r)) {
507 * @brief Get user info array.
509 * @param object $a App
510 * @param int|string $contact_id Contact ID or URL
512 function api_get_user(App $a, $contact_id = null)
520 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
522 // Searching for contact URL
523 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
524 $user = dbesc(normalise_link($contact_id));
526 $extra_query = "AND `contact`.`nurl` = '%s' ";
527 if (api_user() !== false) {
528 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
532 // Searching for contact id with uid = 0
533 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
534 $user = dbesc(api_unique_id_to_nurl($contact_id));
537 throw new BadRequestException("User not found.");
541 $extra_query = "AND `contact`.`nurl` = '%s' ";
542 if (api_user() !== false) {
543 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
547 if (is_null($user) && x($_GET, 'user_id')) {
548 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
551 throw new BadRequestException("User not found.");
555 $extra_query = "AND `contact`.`nurl` = '%s' ";
556 if (api_user() !== false) {
557 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
560 if (is_null($user) && x($_GET, 'screen_name')) {
561 $user = dbesc($_GET['screen_name']);
562 $extra_query = "AND `contact`.`nick` = '%s' ";
563 if (api_user() !== false) {
564 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
568 if (is_null($user) && x($_GET, 'profileurl')) {
569 $user = dbesc(normalise_link($_GET['profileurl']));
570 $extra_query = "AND `contact`.`nurl` = '%s' ";
571 if (api_user() !== false) {
572 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
576 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
577 $argid = count($called_api);
578 list($user, $null) = explode(".", $a->argv[$argid]);
579 if (is_numeric($user)) {
580 $user = dbesc(api_unique_id_to_nurl($user));
587 $extra_query = "AND `contact`.`nurl` = '%s' ";
588 if (api_user() !== false) {
589 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
592 $user = dbesc($user);
593 $extra_query = "AND `contact`.`nick` = '%s' ";
594 if (api_user() !== false) {
595 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
600 logger("api_get_user: user ".$user, LOGGER_DEBUG);
603 if (api_user() === false) {
607 $user = $_SESSION['uid'];
608 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
612 logger('api_user: ' . $extra_query . ', user: ' . $user);
616 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
622 // Selecting the id by priority, friendica first
623 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);
1007 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
1008 * returns a 401 status code and an error message if not.
1009 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
1011 * @param string $type Return type (atom, rss, xml, json)
1013 function api_account_verify_credentials($type)
1018 if (api_user() === false) {
1019 throw new ForbiddenException();
1022 unset($_REQUEST["user_id"]);
1023 unset($_GET["user_id"]);
1025 unset($_REQUEST["screen_name"]);
1026 unset($_GET["screen_name"]);
1028 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
1030 $user_info = api_get_user($a);
1032 // "verified" isn't used here in the standard
1033 unset($user_info["verified"]);
1035 // - Adding last status
1036 if (!$skip_status) {
1037 $user_info["status"] = api_status_show("raw");
1038 if (!count($user_info["status"])) {
1039 unset($user_info["status"]);
1041 unset($user_info["status"]["user"]);
1045 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1046 unset($user_info["uid"]);
1047 unset($user_info["self"]);
1049 return api_format_data("user", $type, ['user' => $user_info]);
1052 /// @TODO move to top of file or somewhere better
1053 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1056 * Get data from $_POST or $_GET
1060 function requestdata($k)
1062 if (x($_POST, $k)) {
1072 * Waitman Gobble Mod
1074 * @param string $type Return type (atom, rss, xml, json)
1076 * @return array|string
1078 function api_statuses_mediap($type)
1082 if (api_user() === false) {
1083 logger('api_statuses_update: no user');
1084 throw new ForbiddenException();
1086 $user_info = api_get_user($a);
1088 $_REQUEST['type'] = 'wall';
1089 $_REQUEST['profile_uid'] = api_user();
1090 $_REQUEST['api_source'] = true;
1091 $txt = requestdata('status');
1092 /// @TODO old-lost code?
1093 //$txt = urldecode(requestdata('status'));
1095 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1096 $txt = html2bb_video($txt);
1097 $config = HTMLPurifier_Config::createDefault();
1098 $config->set('Cache.DefinitionImpl', null);
1099 $purifier = new HTMLPurifier($config);
1100 $txt = $purifier->purify($txt);
1102 $txt = HTML::toBBCode($txt);
1104 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1106 // tell wall_upload function to return img info instead of echo
1107 $_REQUEST['hush'] = 'yeah';
1108 $bebop = wall_upload_post($a);
1110 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1111 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1114 // this should output the last post (the one we just posted).
1115 return api_status_show($type);
1118 /// @TODO move this to top of file or somewhere better!
1119 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1122 * Updates the user’s current status.
1124 * @param string $type Return type (atom, rss, xml, json)
1126 * @return array|string
1127 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1129 function api_statuses_update($type)
1134 if (api_user() === false) {
1135 logger('api_statuses_update: no user');
1136 throw new ForbiddenException();
1141 // convert $_POST array items to the form we use for web posts.
1142 if (requestdata('htmlstatus')) {
1143 $txt = requestdata('htmlstatus');
1144 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1145 $txt = html2bb_video($txt);
1147 $config = HTMLPurifier_Config::createDefault();
1148 $config->set('Cache.DefinitionImpl', null);
1150 $purifier = new HTMLPurifier($config);
1151 $txt = $purifier->purify($txt);
1153 $_REQUEST['body'] = HTML::toBBCode($txt);
1156 $_REQUEST['body'] = requestdata('status');
1159 $_REQUEST['title'] = requestdata('title');
1161 $parent = requestdata('in_reply_to_status_id');
1163 // Twidere sends "-1" if it is no reply ...
1164 if ($parent == -1) {
1168 if (ctype_digit($parent)) {
1169 $_REQUEST['parent'] = $parent;
1171 $_REQUEST['parent_uri'] = $parent;
1174 if (requestdata('lat') && requestdata('long')) {
1175 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1177 $_REQUEST['profile_uid'] = api_user();
1180 $_REQUEST['type'] = 'net-comment';
1182 // Check for throttling (maximum posts per day, week and month)
1183 $throttle_day = Config::get('system', 'throttle_limit_day');
1184 if ($throttle_day > 0) {
1185 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1188 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1189 AND `created` > '%s' AND `id` = `parent`",
1194 if (DBM::is_result($r)) {
1195 $posts_day = $r[0]["posts_day"];
1200 if ($posts_day > $throttle_day) {
1201 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1202 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1203 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));
1207 $throttle_week = Config::get('system', 'throttle_limit_week');
1208 if ($throttle_week > 0) {
1209 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1212 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1213 AND `created` > '%s' AND `id` = `parent`",
1218 if (DBM::is_result($r)) {
1219 $posts_week = $r[0]["posts_week"];
1224 if ($posts_week > $throttle_week) {
1225 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1226 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1227 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));
1231 $throttle_month = Config::get('system', 'throttle_limit_month');
1232 if ($throttle_month > 0) {
1233 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1236 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1237 AND `created` > '%s' AND `id` = `parent`",
1242 if (DBM::is_result($r)) {
1243 $posts_month = $r[0]["posts_month"];
1248 if ($posts_month > $throttle_month) {
1249 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1250 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1251 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));
1255 $_REQUEST['type'] = 'wall';
1258 if (x($_FILES, 'media')) {
1259 // upload the image if we have one
1260 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1261 $media = wall_upload_post($a);
1262 if (strlen($media) > 0) {
1263 $_REQUEST['body'] .= "\n\n" . $media;
1267 // To-Do: Multiple IDs
1268 if (requestdata('media_ids')) {
1270 "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",
1271 intval(requestdata('media_ids')),
1274 if (DBM::is_result($r)) {
1275 $phototypes = Image::supportedTypes();
1276 $ext = $phototypes[$r[0]['type']];
1277 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1278 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1282 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1284 $_REQUEST['api_source'] = true;
1286 if (!x($_REQUEST, "source")) {
1287 $_REQUEST["source"] = api_source();
1290 // call out normal post function
1293 // this should output the last post (the one we just posted).
1294 return api_status_show($type);
1297 /// @TODO move to top of file or somewhere better
1298 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1299 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1302 * Uploads an image to Friendica.
1305 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1307 function api_media_upload()
1311 if (api_user() === false) {
1313 throw new ForbiddenException();
1318 if (!x($_FILES, 'media')) {
1320 throw new BadRequestException("No media.");
1323 $media = wall_upload_post($a, false);
1326 throw new InternalServerErrorException();
1330 $returndata["media_id"] = $media["id"];
1331 $returndata["media_id_string"] = (string)$media["id"];
1332 $returndata["size"] = $media["size"];
1333 $returndata["image"] = ["w" => $media["width"],
1334 "h" => $media["height"],
1335 "image_type" => $media["type"]];
1337 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1339 return ["media" => $returndata];
1342 /// @TODO move to top of file or somewhere better
1343 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1347 * @param string $type Return type (atom, rss, xml, json)
1349 * @return array|string
1351 function api_status_show($type)
1355 $user_info = api_get_user($a);
1357 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1359 if ($type == "raw") {
1360 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1365 // get last public wall message
1369 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1370 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1371 AND `item`.`type` != 'activity' $privacy_sql
1372 ORDER BY `item`.`id` DESC
1374 intval($user_info['cid']),
1376 dbesc($user_info['url']),
1377 dbesc(normalise_link($user_info['url'])),
1378 dbesc($user_info['url']),
1379 dbesc(normalise_link($user_info['url']))
1382 if (DBM::is_result($lastwall)) {
1383 $lastwall = $lastwall[0];
1385 $in_reply_to = api_in_reply_to($lastwall);
1387 $converted = api_convert_item($lastwall);
1389 if ($type == "xml") {
1390 $geo = "georss:point";
1396 'created_at' => api_date($lastwall['created']),
1397 'id' => intval($lastwall['id']),
1398 'id_str' => (string) $lastwall['id'],
1399 'text' => $converted["text"],
1400 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1401 'truncated' => false,
1402 'in_reply_to_status_id' => $in_reply_to['status_id'],
1403 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1404 'in_reply_to_user_id' => $in_reply_to['user_id'],
1405 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1406 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1407 'user' => $user_info,
1409 'coordinates' => "",
1411 'contributors' => "",
1412 'is_quote_status' => false,
1413 'retweet_count' => 0,
1414 'favorite_count' => 0,
1415 'favorited' => $lastwall['starred'] ? true : false,
1416 'retweeted' => false,
1417 'possibly_sensitive' => false,
1419 'statusnet_html' => $converted["html"],
1420 'statusnet_conversation_id' => $lastwall['parent'],
1421 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1424 if (count($converted["attachments"]) > 0) {
1425 $status_info["attachments"] = $converted["attachments"];
1428 if (count($converted["entities"]) > 0) {
1429 $status_info["entities"] = $converted["entities"];
1432 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1433 $status_info["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1434 } elseif (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1435 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['item_network'], $user_info['url']).')');
1438 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1439 unset($status_info["user"]["uid"]);
1440 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]);
1453 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1454 * The author's most recent status will be returned inline.
1456 * @param string $type Return type (atom, rss, xml, json)
1457 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1459 function api_users_show($type)
1463 $user_info = api_get_user($a);
1467 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1468 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1469 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1470 AND `type`!='activity'
1471 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1475 dbesc(ACTIVITY_POST),
1476 intval($user_info['cid']),
1477 dbesc($user_info['url']),
1478 dbesc(normalise_link($user_info['url'])),
1479 dbesc($user_info['url']),
1480 dbesc(normalise_link($user_info['url']))
1483 if (DBM::is_result($lastwall)) {
1484 $lastwall = $lastwall[0];
1486 $in_reply_to = api_in_reply_to($lastwall);
1488 $converted = api_convert_item($lastwall);
1490 if ($type == "xml") {
1491 $geo = "georss:point";
1496 $user_info['status'] = [
1497 'text' => $converted["text"],
1498 'truncated' => false,
1499 'created_at' => api_date($lastwall['created']),
1500 'in_reply_to_status_id' => $in_reply_to['status_id'],
1501 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1502 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1503 'id' => intval($lastwall['contact-id']),
1504 'id_str' => (string) $lastwall['contact-id'],
1505 'in_reply_to_user_id' => $in_reply_to['user_id'],
1506 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1507 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1509 'favorited' => $lastwall['starred'] ? true : false,
1510 'statusnet_html' => $converted["html"],
1511 'statusnet_conversation_id' => $lastwall['parent'],
1512 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1515 if (count($converted["attachments"]) > 0) {
1516 $user_info["status"]["attachments"] = $converted["attachments"];
1519 if (count($converted["entities"]) > 0) {
1520 $user_info["status"]["entities"] = $converted["entities"];
1523 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1524 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1527 if (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1528 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) . ')');
1532 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1533 unset($user_info["uid"]);
1534 unset($user_info["self"]);
1536 return api_format_data("user", $type, ['user' => $user_info]);
1539 /// @TODO move to top of file or somewhere better
1540 api_register_func('api/users/show', 'api_users_show');
1541 api_register_func('api/externalprofile/show', 'api_users_show');
1544 * Search a public user account.
1546 * @param string $type Return type (atom, rss, xml, json)
1548 * @return array|string
1549 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1551 function api_users_search($type)
1557 if (x($_GET, 'q')) {
1558 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1560 if (!DBM::is_result($r)) {
1561 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1564 if (DBM::is_result($r)) {
1566 foreach ($r as $user) {
1567 $user_info = api_get_user($a, $user["id"]);
1569 if ($type == "xml") {
1570 $userlist[$k++.":user"] = $user_info;
1572 $userlist[] = $user_info;
1575 $userlist = ["users" => $userlist];
1577 throw new BadRequestException("User not found.");
1580 throw new BadRequestException("User not found.");
1583 return api_format_data("users", $type, $userlist);
1586 /// @TODO move to top of file or somewhere better
1587 api_register_func('api/users/search', 'api_users_search');
1590 * Return user objects
1592 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1594 * @param string $type Return format: json or xml
1596 * @return array|string
1597 * @throws NotFoundException if the results are empty.
1599 function api_users_lookup($type)
1603 if (x($_REQUEST['user_id'])) {
1604 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1606 $users[] = api_get_user(get_app(), $id);
1611 if (empty($users)) {
1612 throw new NotFoundException;
1615 return api_format_data("users", $type, ['users' => $users]);
1618 /// @TODO move to top of file or somewhere better
1619 api_register_func('api/users/lookup', 'api_users_lookup', true);
1622 * Returns statuses that match a specified query.
1624 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1626 * @param string $type Return format: json, xml, atom, rss
1628 * @return array|string
1629 * @throws BadRequestException if the "q" parameter is missing.
1631 function api_search($type)
1634 $user_info = api_get_user($a);
1636 if (api_user() === false || $user_info === false) {
1637 throw new ForbiddenException();
1643 if (!x($_REQUEST, 'q')) {
1644 throw new BadRequestException("q parameter is required.");
1647 if (x($_REQUEST, 'rpp')) {
1648 $count = $_REQUEST['rpp'];
1649 } elseif (x($_REQUEST, 'count')) {
1650 $count = $_REQUEST['count'];
1655 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1656 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1657 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1659 $start = $page * $count;
1662 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1666 "SELECT ".item_fieldlists()."
1667 FROM `item` ".item_joins()."
1668 WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1669 AND `item`.`body` LIKE CONCAT('%',?,'%')
1672 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
1678 $data['status'] = api_format_items(dba::inArray($r), $user_info);
1680 return api_format_data("statuses", $type, $data);
1683 /// @TODO move to top of file or somewhere better
1684 api_register_func('api/search/tweets', 'api_search', true);
1685 api_register_func('api/search', 'api_search', true);
1688 * Returns the most recent statuses posted by the user and the users they follow.
1690 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1692 * @param string $type Return type (atom, rss, xml, json)
1694 * @todo Optional parameters
1695 * @todo Add reply info
1697 function api_statuses_home_timeline($type)
1700 $user_info = api_get_user($a);
1702 if (api_user() === false || $user_info === false) {
1703 throw new ForbiddenException();
1706 unset($_REQUEST["user_id"]);
1707 unset($_GET["user_id"]);
1709 unset($_REQUEST["screen_name"]);
1710 unset($_GET["screen_name"]);
1712 // get last network messages
1715 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1716 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1720 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1721 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1722 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1723 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1724 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1726 $start = $page * $count;
1730 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1732 if ($exclude_replies > 0) {
1733 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1735 if ($conversation_id > 0) {
1736 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1740 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1741 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1742 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1743 `contact`.`id` AS `cid`
1745 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1746 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1747 WHERE `item`.`uid` = %d AND `verb` = '%s'
1748 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1751 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1753 dbesc(ACTIVITY_POST),
1759 $ret = api_format_items($r, $user_info, false, $type);
1761 // Set all posts from the query above to seen
1763 foreach ($r as $item) {
1764 $idarray[] = intval($item["id"]);
1767 $idlist = implode(",", $idarray);
1769 if ($idlist != "") {
1770 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1773 q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1777 $data = ['status' => $ret];
1781 $data = api_rss_extra($a, $data, $user_info);
1785 return api_format_data("statuses", $type, $data);
1788 /// @TODO move to top of file or somewhere better
1789 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1790 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1793 * Returns the most recent statuses from public users.
1795 * @param string $type Return type (atom, rss, xml, json)
1797 * @return array|string
1799 function api_statuses_public_timeline($type)
1802 $user_info = api_get_user($a);
1804 if (api_user() === false || $user_info === false) {
1805 throw new ForbiddenException();
1808 // get last network messages
1811 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1812 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1816 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1817 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1818 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1819 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1820 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1822 $start = $page * $count;
1825 if ($exclude_replies && !$conversation_id) {
1827 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1831 "SELECT " . item_fieldlists() . "
1833 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1834 " . item_joins() . "
1835 STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1836 AND NOT `user`.`hidewall`
1838 AND NOT `thread`.`private`
1840 AND `thread`.`visible`
1841 AND NOT `thread`.`deleted`
1842 AND NOT `thread`.`moderated`
1843 AND `thread`.`iid` > ?
1845 ORDER BY `thread`.`iid` DESC
1846 LIMIT " . intval($start) . ", " . intval($count),
1851 $r = dba::inArray($r);
1854 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1856 if ($conversation_id > 0) {
1857 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1861 "SELECT " . item_fieldlists() . "
1863 " . item_joins() . "
1864 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1865 AND NOT `user`.`hidewall`
1867 AND NOT `item`.`private`
1869 AND `item`.`visible`
1870 AND NOT `item`.`deleted`
1871 AND NOT `item`.`moderated`
1874 ORDER BY `item`.`id` DESC
1875 LIMIT " . intval($start) . ", " . intval($count),
1880 $r = dba::inArray($r);
1883 $ret = api_format_items($r, $user_info, false, $type);
1885 $data = ['status' => $ret];
1889 $data = api_rss_extra($a, $data, $user_info);
1893 return api_format_data("statuses", $type, $data);
1896 /// @TODO move to top of file or somewhere better
1897 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1900 * Returns the most recent statuses posted by users this node knows about.
1902 * @brief Returns the list of public federated posts this node knows about
1904 * @param string $type Return format: json, xml, atom, rss
1905 * @return array|string
1906 * @throws ForbiddenException
1908 function api_statuses_networkpublic_timeline($type)
1911 $user_info = api_get_user($a);
1913 if (api_user() === false || $user_info === false) {
1914 throw new ForbiddenException();
1917 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1918 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1921 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1922 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1926 $start = ($page - 1) * $count;
1930 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1934 "SELECT " . item_fieldlists() . "
1936 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1937 " . item_joins() . "
1938 WHERE `thread`.`uid` = 0
1940 AND NOT `thread`.`private`
1941 AND `thread`.`visible`
1942 AND NOT `thread`.`deleted`
1943 AND NOT `thread`.`moderated`
1944 AND `thread`.`iid` > ?
1946 ORDER BY `thread`.`iid` DESC
1947 LIMIT " . intval($start) . ", " . intval($count),
1952 $r = dba::inArray($r);
1954 $ret = api_format_items($r, $user_info, false, $type);
1956 $data = ['status' => $ret];
1960 $data = api_rss_extra($a, $data, $user_info);
1964 return api_format_data("statuses", $type, $data);
1967 /// @TODO move to top of file or somewhere better
1968 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1971 * Returns a single status.
1973 * @param string $type Return type (atom, rss, xml, json)
1975 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1977 function api_statuses_show($type)
1980 $user_info = api_get_user($a);
1982 if (api_user() === false || $user_info === false) {
1983 throw new ForbiddenException();
1987 $id = intval($a->argv[3]);
1990 $id = intval($_REQUEST["id"]);
1995 $id = intval($a->argv[4]);
1998 logger('API: api_statuses_show: ' . $id);
2000 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
2003 if ($conversation) {
2004 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
2006 $sql_extra .= " AND `item`.`id` = %d";
2010 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2011 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2012 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2013 `contact`.`id` AS `cid`
2015 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2016 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2017 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2018 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2021 dbesc(ACTIVITY_POST),
2025 /// @TODO How about copying this to above methods which don't check $r ?
2026 if (!DBM::is_result($r)) {
2027 throw new BadRequestException("There is no status with this id.");
2030 $ret = api_format_items($r, $user_info, false, $type);
2032 if ($conversation) {
2033 $data = ['status' => $ret];
2034 return api_format_data("statuses", $type, $data);
2036 $data = ['status' => $ret[0]];
2037 return api_format_data("status", $type, $data);
2041 /// @TODO move to top of file or somewhere better
2042 api_register_func('api/statuses/show', 'api_statuses_show', true);
2046 * @param string $type Return type (atom, rss, xml, json)
2048 * @todo nothing to say?
2050 function api_conversation_show($type)
2053 $user_info = api_get_user($a);
2055 if (api_user() === false || $user_info === false) {
2056 throw new ForbiddenException();
2060 $id = intval($a->argv[3]);
2061 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2062 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
2066 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2067 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2069 $start = $page*$count;
2072 $id = intval($_REQUEST["id"]);
2077 $id = intval($a->argv[4]);
2080 logger('API: api_conversation_show: '.$id);
2082 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
2083 if (DBM::is_result($r)) {
2084 $id = $r[0]["parent"];
2090 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2093 // Not sure why this query was so complicated. We should keep it here for a while,
2094 // just to make sure that we really don't need it.
2095 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
2096 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
2099 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2100 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2101 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2102 `contact`.`id` AS `cid`
2104 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2105 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2106 WHERE `item`.`parent` = %d AND `item`.`visible`
2107 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2108 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2109 AND `item`.`id`>%d $sql_extra
2110 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2113 dbesc(ACTIVITY_POST),
2119 if (!DBM::is_result($r)) {
2120 throw new BadRequestException("There is no status with this id.");
2123 $ret = api_format_items($r, $user_info, false, $type);
2125 $data = ['status' => $ret];
2126 return api_format_data("statuses", $type, $data);
2129 /// @TODO move to top of file or somewhere better
2130 api_register_func('api/conversation/show', 'api_conversation_show', true);
2131 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2136 * @param string $type Return type (atom, rss, xml, json)
2138 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2140 function api_statuses_repeat($type)
2146 if (api_user() === false) {
2147 throw new ForbiddenException();
2153 $id = intval($a->argv[3]);
2156 $id = intval($_REQUEST["id"]);
2161 $id = intval($a->argv[4]);
2164 logger('API: api_statuses_repeat: '.$id);
2167 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2168 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2169 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2170 `contact`.`id` AS `cid`
2172 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2173 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2174 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2175 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2176 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2177 AND `item`.`id`=%d",
2181 /// @TODO other style than above functions!
2182 if (DBM::is_result($r) && $r[0]['body'] != "") {
2183 if (strpos($r[0]['body'], "[/share]") !== false) {
2184 $pos = strpos($r[0]['body'], "[share");
2185 $post = substr($r[0]['body'], $pos);
2187 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2189 $post .= $r[0]['body'];
2190 $post .= "[/share]";
2192 $_REQUEST['body'] = $post;
2193 $_REQUEST['profile_uid'] = api_user();
2194 $_REQUEST['type'] = 'wall';
2195 $_REQUEST['api_source'] = true;
2197 if (!x($_REQUEST, "source")) {
2198 $_REQUEST["source"] = api_source();
2203 throw new ForbiddenException();
2206 // this should output the last post (the one we just posted).
2208 return api_status_show($type);
2211 /// @TODO move to top of file or somewhere better
2212 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2215 * Destroys a specific status.
2217 * @param string $type Return type (atom, rss, xml, json)
2219 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2221 function api_statuses_destroy($type)
2225 if (api_user() === false) {
2226 throw new ForbiddenException();
2232 $id = intval($a->argv[3]);
2235 $id = intval($_REQUEST["id"]);
2240 $id = intval($a->argv[4]);
2243 logger('API: api_statuses_destroy: '.$id);
2245 $ret = api_statuses_show($type);
2247 Item::deleteById($id);
2252 /// @TODO move to top of file or somewhere better
2253 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2256 * Returns the most recent mentions.
2258 * @param string $type Return type (atom, rss, xml, json)
2260 * @see http://developer.twitter.com/doc/get/statuses/mentions
2262 function api_statuses_mentions($type)
2265 $user_info = api_get_user($a);
2267 if (api_user() === false || $user_info === false) {
2268 throw new ForbiddenException();
2271 unset($_REQUEST["user_id"]);
2272 unset($_GET["user_id"]);
2274 unset($_REQUEST["screen_name"]);
2275 unset($_GET["screen_name"]);
2277 // get last network messages
2280 $since_id = defaults($_REQUEST, 'since_id', 0);
2281 $max_id = defaults($_REQUEST, 'max_id' , 0);
2282 $count = defaults($_REQUEST, 'count' , 20);
2283 $page = defaults($_REQUEST, 'page' , 1);
2288 $start = ($page - 1) * $count;
2290 // Ugly code - should be changed
2291 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2292 $myurl = substr($myurl, strpos($myurl, '://') + 3);
2293 $myurl = str_replace('www.', '', $myurl);
2298 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2302 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2303 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2304 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2305 `contact`.`id` AS `cid`
2306 FROM `item` FORCE INDEX (`uid_id`)
2307 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2308 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2309 WHERE `item`.`uid` = %d AND `verb` = '%s'
2310 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2311 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2312 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2315 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2317 dbesc(ACTIVITY_POST),
2318 dbesc(protect_sprintf($myurl)),
2319 dbesc(protect_sprintf($myurl)),
2326 $ret = api_format_items($r, $user_info, false, $type);
2328 $data = ['status' => $ret];
2332 $data = api_rss_extra($a, $data, $user_info);
2336 return api_format_data("statuses", $type, $data);
2339 /// @TODO move to top of file or somewhere better
2340 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2341 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2344 * Returns the most recent statuses posted by the user.
2346 * @brief Returns a user's public timeline
2348 * @param string $type Either "json" or "xml"
2349 * @return string|array
2350 * @throws ForbiddenException
2351 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2353 function api_statuses_user_timeline($type)
2356 $user_info = api_get_user($a);
2358 if (api_user() === false || $user_info === false) {
2359 throw new ForbiddenException();
2363 "api_statuses_user_timeline: api_user: ". api_user() .
2364 "\nuser_info: ".print_r($user_info, true) .
2365 "\n_REQUEST: ".print_r($_REQUEST, true),
2369 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2370 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2371 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2372 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2375 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2376 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2380 $start = ($page - 1) * $count;
2383 if ($user_info['self'] == 1) {
2384 $sql_extra .= " AND `item`.`wall` = 1 ";
2387 if ($exclude_replies > 0) {
2388 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2391 if ($conversation_id > 0) {
2392 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2396 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2400 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2401 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2402 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2403 `contact`.`id` AS `cid`
2404 FROM `item` FORCE INDEX (`uid_contactid_id`)
2405 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2406 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2407 WHERE `item`.`uid` = %d AND `verb` = '%s'
2408 AND `item`.`contact-id` = %d
2409 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2411 AND `item`.`id` > %d
2412 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2414 dbesc(ACTIVITY_POST),
2415 intval($user_info['cid']),
2421 $ret = api_format_items($r, $user_info, true, $type);
2423 $data = ['status' => $ret];
2427 $data = api_rss_extra($a, $data, $user_info);
2431 return api_format_data("statuses", $type, $data);
2434 /// @TODO move to top of file or somewhere better
2435 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2438 * Star/unstar an item.
2439 * param: id : id of the item
2441 * @param string $type Return type (atom, rss, xml, json)
2443 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2445 function api_favorites_create_destroy($type)
2449 if (api_user() === false) {
2450 throw new ForbiddenException();
2453 // for versioned api.
2454 /// @TODO We need a better global soluton
2455 $action_argv_id = 2;
2456 if ($a->argv[1] == "1.1") {
2457 $action_argv_id = 3;
2460 if ($a->argc <= $action_argv_id) {
2461 throw new BadRequestException("Invalid request.");
2463 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2464 if ($a->argc == $action_argv_id + 2) {
2465 $itemid = intval($a->argv[$action_argv_id + 1]);
2467 /// @TODO use x() to check if _REQUEST contains 'id'
2468 $itemid = intval($_REQUEST['id']);
2471 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2473 if (!DBM::is_result($item) || count($item) == 0) {
2474 throw new BadRequestException("Invalid item.");
2479 $item[0]['starred'] = 1;
2482 $item[0]['starred'] = 0;
2485 throw new BadRequestException("Invalid action ".$action);
2488 $r = Item::update(['starred' => $item[0]['starred']], ['id' => $itemid]);
2491 throw new InternalServerErrorException("DB error");
2495 $user_info = api_get_user($a);
2496 $rets = api_format_items($item, $user_info, false, $type);
2499 $data = ['status' => $ret];
2503 $data = api_rss_extra($a, $data, $user_info);
2506 return api_format_data("status", $type, $data);
2509 /// @TODO move to top of file or somewhere better
2510 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2511 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2514 * Returns the most recent favorite statuses.
2516 * @param string $type Return type (atom, rss, xml, json)
2518 * @return string|array
2520 function api_favorites($type)
2525 $user_info = api_get_user($a);
2527 if (api_user() === false || $user_info === false) {
2528 throw new ForbiddenException();
2533 // in friendica starred item are private
2534 // return favorites only for self
2535 logger('api_favorites: self:' . $user_info['self']);
2537 if ($user_info['self'] == 0) {
2543 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2544 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2545 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2546 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2551 $start = $page*$count;
2554 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2558 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2559 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2560 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2561 `contact`.`id` AS `cid`
2562 FROM `item`, `contact`
2563 WHERE `item`.`uid` = %d
2564 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2565 AND `item`.`starred` = 1
2566 AND `contact`.`id` = `item`.`contact-id`
2567 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2570 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2577 $ret = api_format_items($r, $user_info, false, $type);
2580 $data = ['status' => $ret];
2584 $data = api_rss_extra($a, $data, $user_info);
2587 return api_format_data("statuses", $type, $data);
2590 /// @TODO move to top of file or somewhere better
2591 api_register_func('api/favorites', 'api_favorites', true);
2595 * @param array $item
2596 * @param array $recipient
2597 * @param array $sender
2601 function api_format_messages($item, $recipient, $sender)
2603 // standard meta information
2605 'id' => $item['id'],
2606 'sender_id' => $sender['id'] ,
2608 'recipient_id' => $recipient['id'],
2609 'created_at' => api_date($item['created']),
2610 'sender_screen_name' => $sender['screen_name'],
2611 'recipient_screen_name' => $recipient['screen_name'],
2612 'sender' => $sender,
2613 'recipient' => $recipient,
2615 'friendica_seen' => $item['seen'],
2616 'friendica_parent_uri' => $item['parent-uri'],
2619 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2620 unset($ret["sender"]["uid"]);
2621 unset($ret["sender"]["self"]);
2622 unset($ret["recipient"]["uid"]);
2623 unset($ret["recipient"]["self"]);
2625 //don't send title to regular StatusNET requests to avoid confusing these apps
2626 if (x($_GET, 'getText')) {
2627 $ret['title'] = $item['title'];
2628 if ($_GET['getText'] == 'html') {
2629 $ret['text'] = BBCode::convert($item['body'], false);
2630 } elseif ($_GET['getText'] == 'plain') {
2631 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2634 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2636 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2637 unset($ret['sender']);
2638 unset($ret['recipient']);
2646 * @param array $item
2650 function api_convert_item($item)
2652 $body = $item['body'];
2653 $attachments = api_get_attachments($body);
2655 // Workaround for ostatus messages where the title is identically to the body
2656 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2657 $statusbody = trim(HTML::toPlaintext($html, 0));
2659 // handle data: images
2660 $statusbody = api_format_items_embeded_images($item, $statusbody);
2662 $statustitle = trim($item['title']);
2664 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2665 $statustext = trim($statusbody);
2667 $statustext = trim($statustitle."\n\n".$statusbody);
2670 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2671 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2674 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2676 // Workaround for clients with limited HTML parser functionality
2677 $search = ["<br>", "<blockquote>", "</blockquote>",
2678 "<h1>", "</h1>", "<h2>", "</h2>",
2679 "<h3>", "</h3>", "<h4>", "</h4>",
2680 "<h5>", "</h5>", "<h6>", "</h6>"];
2681 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2682 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2683 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2684 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2685 $statushtml = str_replace($search, $replace, $statushtml);
2687 if ($item['title'] != "") {
2688 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2692 $oldtext = $statushtml;
2693 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2694 } while ($oldtext != $statushtml);
2696 if (substr($statushtml, 0, 4) == '<br>') {
2697 $statushtml = substr($statushtml, 4);
2700 if (substr($statushtml, 0, -4) == '<br>') {
2701 $statushtml = substr($statushtml, -4);
2704 // feeds without body should contain the link
2705 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2706 $statushtml .= BBCode::convert($item['plink']);
2709 $entities = api_get_entitities($statustext, $body);
2712 "text" => $statustext,
2713 "html" => $statushtml,
2714 "attachments" => $attachments,
2715 "entities" => $entities
2721 * @param string $body
2723 * @return array|false
2725 function api_get_attachments(&$body)
2728 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2730 $URLSearchString = "^\[\]";
2731 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2739 foreach ($images[1] as $image) {
2740 $imagedata = Image::getInfoFromURL($image);
2743 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2747 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2748 foreach ($images[0] as $orig) {
2749 $body = str_replace($orig, "", $body);
2753 return $attachments;
2758 * @param string $text
2759 * @param string $bbcode
2762 * @todo Links at the first character of the post
2764 function api_get_entitities(&$text, $bbcode)
2766 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2768 if ($include_entities != "true") {
2769 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2771 foreach ($images[1] as $image) {
2772 $replace = proxy_url($image);
2773 $text = str_replace($image, $replace, $text);
2778 $bbcode = BBCode::cleanPictureLinks($bbcode);
2780 // Change pure links in text to bbcode uris
2781 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2784 $entities["hashtags"] = [];
2785 $entities["symbols"] = [];
2786 $entities["urls"] = [];
2787 $entities["user_mentions"] = [];
2789 $URLSearchString = "^\[\]";
2791 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2793 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2794 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2795 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2797 $bbcode = preg_replace(
2798 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2799 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2802 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2804 $bbcode = preg_replace(
2805 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2806 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2809 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2811 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2813 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2814 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2817 foreach ($urls[1] as $id => $url) {
2818 //$start = strpos($text, $url, $offset);
2819 $start = iconv_strpos($text, $url, 0, "UTF-8");
2820 if (!($start === false)) {
2821 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2825 ksort($ordered_urls);
2828 //foreach ($urls[1] AS $id=>$url) {
2829 foreach ($ordered_urls as $url) {
2830 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2831 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2833 $display_url = $url["title"];
2835 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2836 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2838 if (strlen($display_url) > 26) {
2839 $display_url = substr($display_url, 0, 25)."…";
2843 //$start = strpos($text, $url, $offset);
2844 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2845 if (!($start === false)) {
2846 $entities["urls"][] = ["url" => $url["url"],
2847 "expanded_url" => $url["url"],
2848 "display_url" => $display_url,
2849 "indices" => [$start, $start+strlen($url["url"])]];
2850 $offset = $start + 1;
2854 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2855 $ordered_images = [];
2856 foreach ($images[1] as $image) {
2857 //$start = strpos($text, $url, $offset);
2858 $start = iconv_strpos($text, $image, 0, "UTF-8");
2859 if (!($start === false)) {
2860 $ordered_images[$start] = $image;
2863 //$entities["media"] = array();
2866 foreach ($ordered_images as $url) {
2867 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2868 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2870 if (strlen($display_url) > 26) {
2871 $display_url = substr($display_url, 0, 25)."…";
2874 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2875 if (!($start === false)) {
2876 $image = Image::getInfoFromURL($url);
2878 // If image cache is activated, then use the following sizes:
2879 // thumb (150), small (340), medium (600) and large (1024)
2880 if (!Config::get("system", "proxy_disabled")) {
2881 $media_url = proxy_url($url);
2884 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2885 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2887 if (($image[0] > 150) || ($image[1] > 150)) {
2888 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2889 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2892 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2893 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2895 if (($image[0] > 600) || ($image[1] > 600)) {
2896 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2897 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2901 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2904 $entities["media"][] = [
2906 "id_str" => (string)$start+1,
2907 "indices" => [$start, $start+strlen($url)],
2908 "media_url" => normalise_link($media_url),
2909 "media_url_https" => $media_url,
2911 "display_url" => $display_url,
2912 "expanded_url" => $url,
2916 $offset = $start + 1;
2925 * @param array $item
2926 * @param string $text
2930 function api_format_items_embeded_images($item, $text)
2932 $text = preg_replace_callback(
2933 '|data:image/([^;]+)[^=]+=*|m',
2934 function () use ($item) {
2935 return System::baseUrl() . '/display/' . $item['guid'];
2943 * @brief return <a href='url'>name</a> as array
2945 * @param string $txt text
2950 function api_contactlink_to_array($txt)
2953 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2954 if ($r && count($match)==3) {
2956 'name' => $match[2],
2970 * @brief return likes, dislikes and attend status for item
2972 * @param array $item array
2973 * @param string $type Return type (atom, rss, xml, json)
2976 * likes => int count,
2977 * dislikes => int count
2979 function api_format_items_activities(&$item, $type = "json")
2988 'attendmaybe' => [],
2993 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2994 intval($item['uid']),
2998 foreach ($items as $i) {
2999 // not used as result should be structured like other user data
3000 //builtin_activity_puller($i, $activities);
3002 // get user data and add it to the array of the activity
3003 $user = api_get_user($a, $i['author-link']);
3004 switch ($i['verb']) {
3006 $activities['like'][] = $user;
3008 case ACTIVITY_DISLIKE:
3009 $activities['dislike'][] = $user;
3011 case ACTIVITY_ATTEND:
3012 $activities['attendyes'][] = $user;
3014 case ACTIVITY_ATTENDNO:
3015 $activities['attendno'][] = $user;
3017 case ACTIVITY_ATTENDMAYBE:
3018 $activities['attendmaybe'][] = $user;
3025 if ($type == "xml") {
3026 $xml_activities = [];
3027 foreach ($activities as $k => $v) {
3028 // change xml element from "like" to "friendica:like"
3029 $xml_activities["friendica:".$k] = $v;
3030 // add user data into xml output
3032 foreach ($v as $user) {
3033 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
3036 $activities = $xml_activities;
3044 * @brief return data from profiles
3046 * @param array $profile_row array containing data from db table 'profile'
3049 function api_format_items_profiles($profile_row)
3052 'profile_id' => $profile_row['id'],
3053 'profile_name' => $profile_row['profile-name'],
3054 'is_default' => $profile_row['is-default'] ? true : false,
3055 'hide_friends' => $profile_row['hide-friends'] ? true : false,
3056 'profile_photo' => $profile_row['photo'],
3057 'profile_thumb' => $profile_row['thumb'],
3058 'publish' => $profile_row['publish'] ? true : false,
3059 'net_publish' => $profile_row['net-publish'] ? true : false,
3060 'description' => $profile_row['pdesc'],
3061 'date_of_birth' => $profile_row['dob'],
3062 'address' => $profile_row['address'],
3063 'city' => $profile_row['locality'],
3064 'region' => $profile_row['region'],
3065 'postal_code' => $profile_row['postal-code'],
3066 'country' => $profile_row['country-name'],
3067 'hometown' => $profile_row['hometown'],
3068 'gender' => $profile_row['gender'],
3069 'marital' => $profile_row['marital'],
3070 'marital_with' => $profile_row['with'],
3071 'marital_since' => $profile_row['howlong'],
3072 'sexual' => $profile_row['sexual'],
3073 'politic' => $profile_row['politic'],
3074 'religion' => $profile_row['religion'],
3075 'public_keywords' => $profile_row['pub_keywords'],
3076 'private_keywords' => $profile_row['prv_keywords'],
3077 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
3078 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
3079 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
3080 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
3081 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
3082 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
3083 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
3084 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
3085 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
3086 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
3087 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
3088 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
3089 'homepage' => $profile_row['homepage'],
3096 * @brief format items to be returned by api
3098 * @param array $r array of items
3099 * @param array $user_info
3100 * @param bool $filter_user filter items by $user_info
3101 * @param string $type Return type (atom, rss, xml, json)
3103 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
3109 foreach ($r as $item) {
3110 localize_item($item);
3111 list($status_user, $owner_user) = api_item_get_user($a, $item);
3113 // Look if the posts are matching if they should be filtered by user id
3114 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3118 $in_reply_to = api_in_reply_to($item);
3120 $converted = api_convert_item($item);
3122 if ($type == "xml") {
3123 $geo = "georss:point";
3129 'text' => $converted["text"],
3130 'truncated' => false,
3131 'created_at'=> api_date($item['created']),
3132 'in_reply_to_status_id' => $in_reply_to['status_id'],
3133 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3134 'source' => (($item['app']) ? $item['app'] : 'web'),
3135 'id' => intval($item['id']),
3136 'id_str' => (string) intval($item['id']),
3137 'in_reply_to_user_id' => $in_reply_to['user_id'],
3138 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3139 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3141 'favorited' => $item['starred'] ? true : false,
3142 'user' => $status_user ,
3143 'friendica_owner' => $owner_user,
3144 //'entities' => NULL,
3145 'statusnet_html' => $converted["html"],
3146 'statusnet_conversation_id' => $item['parent'],
3147 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3148 'friendica_activities' => api_format_items_activities($item, $type),
3151 if (count($converted["attachments"]) > 0) {
3152 $status["attachments"] = $converted["attachments"];
3155 if (count($converted["entities"]) > 0) {
3156 $status["entities"] = $converted["entities"];
3159 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
3160 $status["source"] = ContactSelector::networkToName($item['item_network'], $user_info['url']);
3161 } elseif (($item['item_network'] != "") && (ContactSelector::networkToName($item['item_network'], $user_info['url']) != $status["source"])) {
3162 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['item_network'], $user_info['url']).')');
3166 // Retweets are only valid for top postings
3167 // It doesn't work reliable with the link if its a feed
3168 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
3170 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
3173 if ($item["id"] == $item["parent"]) {
3174 $retweeted_item = api_share_as_retweet($item);
3175 if ($retweeted_item !== false) {
3176 $retweeted_status = $status;
3178 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
3179 } catch (BadRequestException $e) {
3180 // user not found. should be found?
3181 /// @todo check if the user should be always found
3182 $retweeted_status["user"] = [];
3185 $rt_converted = api_convert_item($retweeted_item);
3187 $retweeted_status['text'] = $rt_converted["text"];
3188 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3189 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3190 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3191 $status['retweeted_status'] = $retweeted_status;
3195 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3196 unset($status["user"]["uid"]);
3197 unset($status["user"]["self"]);
3199 if ($item["coord"] != "") {
3200 $coords = explode(' ', $item["coord"]);
3201 if (count($coords) == 2) {
3202 if ($type == "json") {
3203 $status["geo"] = ['type' => 'Point',
3204 'coordinates' => [(float) $coords[0],
3205 (float) $coords[1]]];
3206 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3207 $status["georss:point"] = $item["coord"];
3217 * Returns the remaining number of API requests available to the user before the API limit is reached.
3219 * @param string $type Return type (atom, rss, xml, json)
3221 * @return array|string
3223 function api_account_rate_limit_status($type)
3225 if ($type == "xml") {
3227 'remaining-hits' => '150',
3228 '@attributes' => ["type" => "integer"],
3229 'hourly-limit' => '150',
3230 '@attributes2' => ["type" => "integer"],
3231 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3232 '@attributes3' => ["type" => "datetime"],
3233 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3234 '@attributes4' => ["type" => "integer"],
3238 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3239 'remaining_hits' => '150',
3240 'hourly_limit' => '150',
3241 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3245 return api_format_data('hash', $type, ['hash' => $hash]);
3248 /// @TODO move to top of file or somewhere better
3249 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3252 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3254 * @param string $type Return type (atom, rss, xml, json)
3256 * @return array|string
3258 function api_help_test($type)
3260 if ($type == 'xml') {
3266 return api_format_data('ok', $type, ["ok" => $ok]);
3269 /// @TODO move to top of file or somewhere better
3270 api_register_func('api/help/test', 'api_help_test', false);
3273 * Returns all lists the user subscribes to.
3275 * @param string $type Return type (atom, rss, xml, json)
3277 * @return array|string
3278 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3280 function api_lists_list($type)
3283 /// @TODO $ret is not filled here?
3284 return api_format_data('lists', $type, ["lists_list" => $ret]);
3287 /// @TODO move to top of file or somewhere better
3288 api_register_func('api/lists/list', 'api_lists_list', true);
3289 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3292 * Returns all groups the user owns.
3294 * @param string $type Return type (atom, rss, xml, json)
3296 * @return array|string
3297 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3299 function api_lists_ownerships($type)
3303 if (api_user() === false) {
3304 throw new ForbiddenException();
3308 $user_info = api_get_user($a);
3309 $uid = $user_info['uid'];
3311 $groups = dba::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3313 // loop through all groups
3315 foreach ($groups as $group) {
3316 if ($group['visible']) {
3322 'name' => $group['name'],
3323 'id' => intval($group['id']),
3324 'id_str' => (string) $group['id'],
3325 'user' => $user_info,
3329 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3332 /// @TODO move to top of file or somewhere better
3333 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3336 * Returns recent statuses from users in the specified group.
3338 * @param string $type Return type (atom, rss, xml, json)
3340 * @return array|string
3341 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3343 function api_lists_statuses($type)
3347 $user_info = api_get_user($a);
3348 if (api_user() === false || $user_info === false) {
3349 throw new ForbiddenException();
3352 unset($_REQUEST["user_id"]);
3353 unset($_GET["user_id"]);
3355 unset($_REQUEST["screen_name"]);
3356 unset($_GET["screen_name"]);
3358 if (empty($_REQUEST['list_id'])) {
3359 throw new BadRequestException('list_id not specified');
3363 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
3364 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
3368 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3369 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3370 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
3371 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
3373 $start = $page * $count;
3377 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
3379 if ($exclude_replies > 0) {
3380 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
3382 if ($conversation_id > 0) {
3383 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
3387 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
3388 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
3389 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
3390 `contact`.`id` AS `cid`, `group_member`.`gid`
3392 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
3393 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
3394 STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = `item`.`contact-id`
3395 WHERE `item`.`uid` = ? AND `verb` = ?
3396 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
3399 AND `group_member`.`gid` = ?
3400 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count),
3404 $_REQUEST['list_id']
3407 $items = api_format_items(dba::inArray($statuses), $user_info, false, $type);
3409 $data = ['status' => $items];
3413 $data = api_rss_extra($a, $data, $user_info);
3417 return api_format_data("statuses", $type, $data);
3420 /// @TODO move to top of file or somewhere better
3421 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3424 * Considers friends and followers lists to be private and won't return
3425 * anything if any user_id parameter is passed.
3427 * @brief Returns either the friends of the follower list
3429 * @param string $qtype Either "friends" or "followers"
3430 * @return boolean|array
3431 * @throws ForbiddenException
3433 function api_statuses_f($qtype)
3437 if (api_user() === false) {
3438 throw new ForbiddenException();
3442 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3443 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3447 $start = ($page - 1) * $count;
3449 $user_info = api_get_user($a);
3451 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3452 /* this is to stop Hotot to load friends multiple times
3453 * I'm not sure if I'm missing return something or
3454 * is a bug in hotot. Workaround, meantime
3458 return array('$users' => $ret);*/
3463 if ($qtype == 'friends') {
3464 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3465 } elseif ($qtype == 'followers') {
3466 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3469 // friends and followers only for self
3470 if ($user_info['self'] == 0) {
3471 $sql_extra = " AND false ";
3474 if ($qtype == 'blocks') {
3475 $sql_filter = 'AND `blocked` AND NOT `pending`';
3476 } elseif ($qtype == 'incoming') {
3477 $sql_filter = 'AND `pending`';
3479 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3497 foreach ($r as $cid) {
3498 $user = api_get_user($a, $cid['nurl']);
3499 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3500 unset($user["uid"]);
3501 unset($user["self"]);
3508 return ['user' => $ret];
3513 * Returns the user's friends.
3515 * @brief Returns the list of friends of the provided user
3517 * @deprecated By Twitter API in favor of friends/list
3519 * @param string $type Either "json" or "xml"
3520 * @return boolean|string|array
3522 function api_statuses_friends($type)
3524 $data = api_statuses_f("friends");
3525 if ($data === false) {
3528 return api_format_data("users", $type, $data);
3532 * Returns the user's followers.
3534 * @brief Returns the list of followers of the provided user
3536 * @deprecated By Twitter API in favor of friends/list
3538 * @param string $type Either "json" or "xml"
3539 * @return boolean|string|array
3541 function api_statuses_followers($type)
3543 $data = api_statuses_f("followers");
3544 if ($data === false) {
3547 return api_format_data("users", $type, $data);
3550 /// @TODO move to top of file or somewhere better
3551 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3552 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3555 * Returns the list of blocked users
3557 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3559 * @param string $type Either "json" or "xml"
3561 * @return boolean|string|array
3563 function api_blocks_list($type)
3565 $data = api_statuses_f('blocks');
3566 if ($data === false) {
3569 return api_format_data("users", $type, $data);
3572 /// @TODO move to top of file or somewhere better
3573 api_register_func('api/blocks/list', 'api_blocks_list', true);
3576 * Returns the list of pending users IDs
3578 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3580 * @param string $type Either "json" or "xml"
3582 * @return boolean|string|array
3584 function api_friendships_incoming($type)
3586 $data = api_statuses_f('incoming');
3587 if ($data === false) {
3592 foreach ($data['user'] as $user) {
3593 $ids[] = $user['id'];
3596 return api_format_data("ids", $type, ['id' => $ids]);
3599 /// @TODO move to top of file or somewhere better
3600 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3603 * Returns the instance's configuration information.
3605 * @param string $type Return type (atom, rss, xml, json)
3607 * @return array|string
3609 function api_statusnet_config($type)
3613 $name = $a->config['sitename'];
3614 $server = $a->get_hostname();
3615 $logo = System::baseUrl() . '/images/friendica-64.png';
3616 $email = $a->config['admin_email'];
3617 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3618 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3619 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3620 if ($a->config['api_import_size']) {
3621 $textlimit = (string) $a->config['api_import_size'];
3623 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3624 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3627 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3628 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3629 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3630 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3631 'shorturllength' => '30',
3633 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3634 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3635 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3636 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3641 return api_format_data('config', $type, ['config' => $config]);
3644 /// @TODO move to top of file or somewhere better
3645 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3646 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3650 * @param string $type Return type (atom, rss, xml, json)
3652 * @return array|string
3654 function api_statusnet_version($type)
3657 $fake_statusnet_version = "0.9.7";
3659 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3662 /// @TODO move to top of file or somewhere better
3663 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3664 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3668 * @param string $type Return type (atom, rss, xml, json)
3670 * @todo use api_format_data() to return data
3672 function api_ff_ids($type)
3675 throw new ForbiddenException();
3682 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3685 "SELECT `pcontact`.`id` FROM `contact`
3686 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3687 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3690 if (!DBM::is_result($r)) {
3695 foreach ($r as $rr) {
3696 if ($stringify_ids) {
3699 $ids[] = intval($rr['id']);
3703 return api_format_data("ids", $type, ['id' => $ids]);
3707 * Returns the ID of every user the user is following.
3709 * @param string $type Return type (atom, rss, xml, json)
3711 * @return array|string
3712 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3714 function api_friends_ids($type)
3716 return api_ff_ids($type);
3720 * Returns the ID of every user following the user.
3722 * @param string $type Return type (atom, rss, xml, json)
3724 * @return array|string
3725 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3727 function api_followers_ids($type)
3729 return api_ff_ids($type);
3732 /// @TODO move to top of file or somewhere better
3733 api_register_func('api/friends/ids', 'api_friends_ids', true);
3734 api_register_func('api/followers/ids', 'api_followers_ids', true);
3737 * Sends a new direct message.
3739 * @param string $type Return type (atom, rss, xml, json)
3741 * @return array|string
3742 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3744 function api_direct_messages_new($type)
3749 if (api_user() === false) {
3750 throw new ForbiddenException();
3753 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3757 $sender = api_get_user($a);
3759 if ($_POST['screen_name']) {
3761 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3763 dbesc($_POST['screen_name'])
3766 // Selecting the id by priority, friendica first
3767 api_best_nickname($r);
3769 $recipient = api_get_user($a, $r[0]['nurl']);
3771 $recipient = api_get_user($a, $_POST['user_id']);
3776 if (x($_REQUEST, 'replyto')) {
3778 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3780 intval($_REQUEST['replyto'])
3782 $replyto = $r[0]['parent-uri'];
3783 $sub = $r[0]['title'];
3785 if (x($_REQUEST, 'title')) {
3786 $sub = $_REQUEST['title'];
3788 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3792 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3795 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3796 $ret = api_format_messages($r[0], $recipient, $sender);
3798 $ret = ["error"=>$id];
3801 $data = ['direct_message'=>$ret];
3806 $data = api_rss_extra($a, $data, $sender);
3809 return api_format_data("direct-messages", $type, $data);
3812 /// @TODO move to top of file or somewhere better
3813 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3816 * Destroys a direct message.
3818 * @brief delete a direct_message from mail table through api
3820 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3822 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3824 function api_direct_messages_destroy($type)
3828 if (api_user() === false) {
3829 throw new ForbiddenException();
3833 $user_info = api_get_user($a);
3835 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3837 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3838 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3839 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3841 $uid = $user_info['uid'];
3842 // error if no id or parenturi specified (for clients posting parent-uri as well)
3843 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3844 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3845 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3848 // BadRequestException if no id specified (for clients using Twitter API)
3850 throw new BadRequestException('Message id not specified');
3853 // add parent-uri to sql command if specified by calling app
3854 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3856 // get data of the specified message id
3858 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3863 // error message if specified id is not in database
3864 if (!DBM::is_result($r)) {
3865 if ($verbose == "true") {
3866 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3867 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3869 /// @todo BadRequestException ok for Twitter API clients?
3870 throw new BadRequestException('message id not in database');
3875 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3880 if ($verbose == "true") {
3883 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3884 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3886 $answer = ['result' => 'error', 'message' => 'unknown error'];
3887 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3890 /// @todo return JSON data like Twitter API not yet implemented
3893 /// @TODO move to top of file or somewhere better
3894 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3898 * @param string $type Return type (atom, rss, xml, json)
3899 * @param string $box
3900 * @param string $verbose
3902 * @return array|string
3904 function api_direct_messages_box($type, $box, $verbose)
3907 $user_info = api_get_user($a);
3909 if (api_user() === false || $user_info === false) {
3910 throw new ForbiddenException();
3914 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3915 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3920 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3921 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3923 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3924 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3927 unset($_REQUEST["user_id"]);
3928 unset($_GET["user_id"]);
3930 unset($_REQUEST["screen_name"]);
3931 unset($_GET["screen_name"]);
3933 $profile_url = $user_info["url"];
3936 $start = $page * $count;
3941 if ($box=="sentbox") {
3942 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3943 } elseif ($box == "conversation") {
3944 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3945 } elseif ($box == "all") {
3946 $sql_extra = "true";
3947 } elseif ($box == "inbox") {
3948 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3952 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3955 if ($user_id != "") {
3956 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3957 } elseif ($screen_name !="") {
3958 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3962 "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",
3968 if ($verbose == "true" && !DBM::is_result($r)) {
3969 $answer = ['result' => 'error', 'message' => 'no mails available'];
3970 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3974 foreach ($r as $item) {
3975 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3976 $recipient = $user_info;
3977 $sender = api_get_user($a, normalise_link($item['contact-url']));
3978 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3979 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3980 $sender = $user_info;
3983 $ret[] = api_format_messages($item, $recipient, $sender);
3987 $data = ['direct_message' => $ret];
3991 $data = api_rss_extra($a, $data, $user_info);
3994 return api_format_data("direct-messages", $type, $data);
3998 * Returns the most recent direct messages sent by the user.
4000 * @param string $type Return type (atom, rss, xml, json)
4002 * @return array|string
4003 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4005 function api_direct_messages_sentbox($type)
4007 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
4008 return api_direct_messages_box($type, "sentbox", $verbose);
4012 * Returns the most recent direct messages sent to the user.
4014 * @param string $type Return type (atom, rss, xml, json)
4016 * @return array|string
4017 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4019 function api_direct_messages_inbox($type)
4021 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
4022 return api_direct_messages_box($type, "inbox", $verbose);
4027 * @param string $type Return type (atom, rss, xml, json)
4029 * @return array|string
4031 function api_direct_messages_all($type)
4033 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
4034 return api_direct_messages_box($type, "all", $verbose);
4039 * @param string $type Return type (atom, rss, xml, json)
4041 * @return array|string
4043 function api_direct_messages_conversation($type)
4045 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
4046 return api_direct_messages_box($type, "conversation", $verbose);
4049 /// @TODO move to top of file or somewhere better
4050 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4051 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4052 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4053 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4056 * Returns an OAuth Request Token.
4058 * @see https://oauth.net/core/1.0/#auth_step1
4060 function api_oauth_request_token()
4062 $oauth1 = new FKOAuth1();
4064 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4065 } catch (Exception $e) {
4066 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4074 * Returns an OAuth Access Token.
4076 * @return array|string
4077 * @see https://oauth.net/core/1.0/#auth_step3
4079 function api_oauth_access_token()
4081 $oauth1 = new FKOAuth1();
4083 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4084 } catch (Exception $e) {
4085 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4092 /// @TODO move to top of file or somewhere better
4093 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4094 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4098 * @brief delete a complete photoalbum with all containing photos from database through api
4100 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4103 function api_fr_photoalbum_delete($type)
4105 if (api_user() === false) {
4106 throw new ForbiddenException();
4109 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
4111 // we do not allow calls without album string
4113 throw new BadRequestException("no albumname specified");
4115 // check if album is existing
4117 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4121 if (!DBM::is_result($r)) {
4122 throw new BadRequestException("album not available");
4125 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4126 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4127 foreach ($r as $rr) {
4129 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4130 intval(local_user()),
4131 dbesc($rr['resource-id'])
4134 if (!DBM::is_result($photo_item)) {
4135 throw new InternalServerErrorException("problem with deleting items occured");
4137 Item::deleteById($photo_item[0]['id']);
4140 // now let's delete all photos from the album
4141 $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
4143 // return success of deletion or error message
4145 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4146 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4148 throw new InternalServerErrorException("unknown error - deleting from database failed");
4153 * @brief update the name of the album for all photos of an album
4155 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4158 function api_fr_photoalbum_update($type)
4160 if (api_user() === false) {
4161 throw new ForbiddenException();
4164 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
4165 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
4167 // we do not allow calls without album string
4169 throw new BadRequestException("no albumname specified");
4171 if ($album_new == "") {
4172 throw new BadRequestException("no new albumname specified");
4174 // check if album is existing
4176 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4180 if (!DBM::is_result($r)) {
4181 throw new BadRequestException("album not available");
4183 // now let's update all photos to the albumname
4185 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
4191 // return success of updating or error message
4193 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4194 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4196 throw new InternalServerErrorException("unknown error - updating in database failed");
4202 * @brief list all photos of the authenticated user
4204 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4207 function api_fr_photos_list($type)
4209 if (api_user() === false) {
4210 throw new ForbiddenException();
4213 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4214 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4215 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4216 intval(local_user())
4219 'image/jpeg' => 'jpg',
4220 'image/png' => 'png',
4221 'image/gif' => 'gif'
4223 $data = ['photo'=>[]];
4224 if (DBM::is_result($r)) {
4225 foreach ($r as $rr) {
4227 $photo['id'] = $rr['resource-id'];
4228 $photo['album'] = $rr['album'];
4229 $photo['filename'] = $rr['filename'];
4230 $photo['type'] = $rr['type'];
4231 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4232 $photo['created'] = $rr['created'];
4233 $photo['edited'] = $rr['edited'];
4234 $photo['desc'] = $rr['desc'];
4236 if ($type == "xml") {
4237 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4239 $photo['thumb'] = $thumb;
4240 $data['photo'][] = $photo;
4244 return api_format_data("photos", $type, $data);
4248 * @brief upload a new photo or change an existing photo
4250 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4253 function api_fr_photo_create_update($type)
4255 if (api_user() === false) {
4256 throw new ForbiddenException();
4259 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4260 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4261 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4262 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4263 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4264 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4265 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4266 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4267 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4269 // do several checks on input parameters
4270 // we do not allow calls without album string
4271 if ($album == null) {
4272 throw new BadRequestException("no albumname specified");
4274 // if photo_id == null --> we are uploading a new photo
4275 if ($photo_id == null) {
4278 // error if no media posted in create-mode
4279 if (!x($_FILES, 'media')) {
4281 throw new BadRequestException("no media data submitted");
4284 // album_new will be ignored in create-mode
4289 // check if photo is existing in database
4291 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4296 if (!DBM::is_result($r)) {
4297 throw new BadRequestException("photo not available");
4301 // checks on acl strings provided by clients
4302 $acl_input_error = false;
4303 $acl_input_error |= check_acl_input($allow_cid);
4304 $acl_input_error |= check_acl_input($deny_cid);
4305 $acl_input_error |= check_acl_input($allow_gid);
4306 $acl_input_error |= check_acl_input($deny_gid);
4307 if ($acl_input_error) {
4308 throw new BadRequestException("acl data invalid");
4310 // now let's upload the new media in create-mode
4311 if ($mode == "create") {
4312 $media = $_FILES['media'];
4313 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4315 // return success of updating or error message
4316 if (!is_null($data)) {
4317 return api_format_data("photo_create", $type, $data);
4319 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4323 // now let's do the changes in update-mode
4324 if ($mode == "update") {
4327 if (!is_null($desc)) {
4328 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4331 if (!is_null($album_new)) {
4332 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4335 if (!is_null($allow_cid)) {
4336 $allow_cid = trim($allow_cid);
4337 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4340 if (!is_null($deny_cid)) {
4341 $deny_cid = trim($deny_cid);
4342 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4345 if (!is_null($allow_gid)) {
4346 $allow_gid = trim($allow_gid);
4347 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4350 if (!is_null($deny_gid)) {
4351 $deny_gid = trim($deny_gid);
4352 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4356 if ($sql_extra != "") {
4357 $nothingtodo = false;
4359 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4361 DateTimeFormat::utcNow(), // update edited timestamp
4367 $nothingtodo = true;
4370 if (x($_FILES, 'media')) {
4371 $nothingtodo = false;
4372 $media = $_FILES['media'];
4373 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4374 if (!is_null($data)) {
4375 return api_format_data("photo_update", $type, $data);
4379 // return success of updating or error message
4381 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4382 return api_format_data("photo_update", $type, ['$result' => $answer]);
4385 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4386 return api_format_data("photo_update", $type, ['$result' => $answer]);
4388 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4391 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4396 * @brief delete a single photo from the database through api
4398 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4401 function api_fr_photo_delete($type)
4403 if (api_user() === false) {
4404 throw new ForbiddenException();
4407 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4409 // do several checks on input parameters
4410 // we do not allow calls without photo id
4411 if ($photo_id == null) {
4412 throw new BadRequestException("no photo_id specified");
4414 // check if photo is existing in database
4416 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4420 if (!DBM::is_result($r)) {
4421 throw new BadRequestException("photo not available");
4423 // now we can perform on the deletion of the photo
4424 $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4426 // return success of deletion or error message
4428 // retrieve the id of the parent element (the photo element)
4430 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4431 intval(local_user()),
4435 if (!DBM::is_result($photo_item)) {
4436 throw new InternalServerErrorException("problem with deleting items occured");
4438 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4439 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4440 Item::deleteById($photo_item[0]['id']);
4442 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4443 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4445 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4451 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4453 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4454 * @return string|array
4456 function api_fr_photo_detail($type)
4458 if (api_user() === false) {
4459 throw new ForbiddenException();
4461 if (!x($_REQUEST, 'photo_id')) {
4462 throw new BadRequestException("No photo id.");
4465 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4466 $photo_id = $_REQUEST['photo_id'];
4468 // prepare json/xml output with data from database for the requested photo
4469 $data = prepare_photo_data($type, $scale, $photo_id);
4471 return api_format_data("photo_detail", $type, $data);
4476 * Updates the user’s profile image.
4478 * @brief updates the profile image for the user (either a specified profile or the default profile)
4480 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4483 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4485 function api_account_update_profile_image($type)
4487 if (api_user() === false) {
4488 throw new ForbiddenException();
4491 $profileid = defaults($_REQUEST, 'profile_id', 0);
4493 // error if image data is missing
4494 if (!x($_FILES, 'image')) {
4495 throw new BadRequestException("no media data submitted");
4498 // check if specified profile id is valid
4499 if ($profileid != 0) {
4501 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4505 // error message if specified profile id is not in database
4506 if (!DBM::is_result($r)) {
4507 throw new BadRequestException("profile_id not available");
4509 $is_default_profile = $r['profile'];
4511 $is_default_profile = 1;
4514 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4516 if (x($_FILES, 'image')) {
4517 $media = $_FILES['image'];
4518 } elseif (x($_FILES, 'media')) {
4519 $media = $_FILES['media'];
4521 // save new profile image
4522 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4525 if (is_array($media['type'])) {
4526 $filetype = $media['type'][0];
4528 $filetype = $media['type'];
4530 if ($filetype == "image/jpeg") {
4532 } elseif ($filetype == "image/png") {
4535 // change specified profile or all profiles to the new resource-id
4536 if ($is_default_profile) {
4538 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4539 dbesc($data['photo']['id']),
4540 intval(local_user())
4544 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
4545 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4546 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4547 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4548 intval(local_user())
4552 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4553 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4554 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4555 intval($_REQUEST['profile']),
4556 intval(local_user())
4560 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4561 // so that browsers will do a cache update unconditionally
4564 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4565 dbesc(DateTimeFormat::utcNow()),
4566 intval(local_user())
4569 // Update global directory in background
4570 //$user = api_get_user(get_app());
4571 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4572 if ($url && strlen(Config::get('system', 'directory'))) {
4573 Worker::add(PRIORITY_LOW, "Directory", $url);
4576 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4578 // output for client
4580 return api_account_verify_credentials($type);
4582 // SaveMediaToDatabase failed for some reason
4583 throw new InternalServerErrorException("image upload failed");
4587 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4588 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4589 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4590 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4591 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4592 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4593 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4594 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4595 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4598 * Update user profile
4600 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4602 * @return array|string
4604 function api_account_update_profile($type)
4606 $local_user = api_user();
4607 $api_user = api_get_user(get_app());
4609 if (!empty($_POST['name'])) {
4610 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4611 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4612 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4613 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4616 if (isset($_POST['description'])) {
4617 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4618 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4619 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4622 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4623 // Update global directory in background
4624 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4625 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4628 return api_account_verify_credentials($type);
4631 /// @TODO move to top of file or somewhere better
4632 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4636 * @param string $acl_string
4638 function check_acl_input($acl_string)
4640 if ($acl_string == null || $acl_string == " ") {
4643 $contact_not_found = false;
4645 // split <x><y><z> into array of cid's
4646 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4648 // check for each cid if it is available on server
4649 $cid_array = $array[0];
4650 foreach ($cid_array as $cid) {
4651 $cid = str_replace("<", "", $cid);
4652 $cid = str_replace(">", "", $cid);
4654 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4658 $contact_not_found |= !DBM::is_result($contact);
4660 return $contact_not_found;
4665 * @param string $mediatype
4666 * @param array $media
4667 * @param string $type
4668 * @param string $album
4669 * @param string $allow_cid
4670 * @param string $deny_cid
4671 * @param string $allow_gid
4672 * @param string $deny_gid
4673 * @param string $desc
4674 * @param integer $profile
4675 * @param boolean $visibility
4676 * @param string $photo_id
4678 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)
4686 if (is_array($media)) {
4687 if (is_array($media['tmp_name'])) {
4688 $src = $media['tmp_name'][0];
4690 $src = $media['tmp_name'];
4692 if (is_array($media['name'])) {
4693 $filename = basename($media['name'][0]);
4695 $filename = basename($media['name']);
4697 if (is_array($media['size'])) {
4698 $filesize = intval($media['size'][0]);
4700 $filesize = intval($media['size']);
4702 if (is_array($media['type'])) {
4703 $filetype = $media['type'][0];
4705 $filetype = $media['type'];
4709 if ($filetype == "") {
4710 $filetype=Image::guessType($filename);
4712 $imagedata = getimagesize($src);
4714 $filetype = $imagedata['mime'];
4717 "File upload src: " . $src . " - filename: " . $filename .
4718 " - size: " . $filesize . " - type: " . $filetype,
4722 // check if there was a php upload error
4723 if ($filesize == 0 && $media['error'] == 1) {
4724 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4726 // check against max upload size within Friendica instance
4727 $maximagesize = Config::get('system', 'maximagesize');
4728 if ($maximagesize && ($filesize > $maximagesize)) {
4729 $formattedBytes = formatBytes($maximagesize);
4730 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4733 // create Photo instance with the data of the image
4734 $imagedata = @file_get_contents($src);
4735 $Image = new Image($imagedata, $filetype);
4736 if (! $Image->isValid()) {
4737 throw new InternalServerErrorException("unable to process image data");
4740 // check orientation of image
4741 $Image->orient($src);
4744 // check max length of images on server
4745 $max_length = Config::get('system', 'max_image_length');
4746 if (! $max_length) {
4747 $max_length = MAX_IMAGE_LENGTH;
4749 if ($max_length > 0) {
4750 $Image->scaleDown($max_length);
4751 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4753 $width = $Image->getWidth();
4754 $height = $Image->getHeight();
4756 // create a new resource-id if not already provided
4757 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4759 if ($mediatype == "photo") {
4760 // upload normal image (scales 0, 1, 2)
4761 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4763 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4765 logger("photo upload: image upload with scale 0 (original size) failed");
4767 if ($width > 640 || $height > 640) {
4768 $Image->scaleDown(640);
4769 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4771 logger("photo upload: image upload with scale 1 (640x640) failed");
4775 if ($width > 320 || $height > 320) {
4776 $Image->scaleDown(320);
4777 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4779 logger("photo upload: image upload with scale 2 (320x320) failed");
4782 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4783 } elseif ($mediatype == "profileimage") {
4784 // upload profile image (scales 4, 5, 6)
4785 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4787 if ($width > 175 || $height > 175) {
4788 $Image->scaleDown(175);
4789 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4791 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4795 if ($width > 80 || $height > 80) {
4796 $Image->scaleDown(80);
4797 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4799 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4803 if ($width > 48 || $height > 48) {
4804 $Image->scaleDown(48);
4805 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4807 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4810 $Image->__destruct();
4811 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4815 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4816 if ($photo_id == null && $mediatype == "photo") {
4817 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4819 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4820 return prepare_photo_data($type, false, $hash);
4822 throw new InternalServerErrorException("image upload failed");
4828 * @param string $hash
4829 * @param string $allow_cid
4830 * @param string $deny_cid
4831 * @param string $allow_gid
4832 * @param string $deny_gid
4833 * @param string $filetype
4834 * @param boolean $visibility
4836 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4838 // get data about the api authenticated user
4839 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4840 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4843 $arr['guid'] = get_guid(32);
4844 $arr['uid'] = intval(api_user());
4846 $arr['parent-uri'] = $uri;
4847 $arr['type'] = 'photo';
4849 $arr['resource-id'] = $hash;
4850 $arr['contact-id'] = $owner_record[0]['id'];
4851 $arr['owner-name'] = $owner_record[0]['name'];
4852 $arr['owner-link'] = $owner_record[0]['url'];
4853 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4854 $arr['author-name'] = $owner_record[0]['name'];
4855 $arr['author-link'] = $owner_record[0]['url'];
4856 $arr['author-avatar'] = $owner_record[0]['thumb'];
4858 $arr['allow_cid'] = $allow_cid;
4859 $arr['allow_gid'] = $allow_gid;
4860 $arr['deny_cid'] = $deny_cid;
4861 $arr['deny_gid'] = $deny_gid;
4862 $arr['visible'] = $visibility;
4866 'image/jpeg' => 'jpg',
4867 'image/png' => 'png',
4868 'image/gif' => 'gif'
4871 // adds link to the thumbnail scale photo
4872 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4873 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4876 // do the magic for storing the item in the database and trigger the federation to other contacts
4882 * @param string $type
4884 * @param string $photo_id
4888 function prepare_photo_data($type, $scale, $photo_id)
4891 $user_info = api_get_user($a);
4893 if ($user_info === false) {
4894 throw new ForbiddenException();
4897 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4898 $data_sql = ($scale === false ? "" : "data, ");
4900 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4901 // clients needs to convert this in their way for further processing
4903 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4904 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4905 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4906 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4908 intval(local_user()),
4914 'image/jpeg' => 'jpg',
4915 'image/png' => 'png',
4916 'image/gif' => 'gif'
4919 // prepare output data for photo
4920 if (DBM::is_result($r)) {
4921 $data = ['photo' => $r[0]];
4922 $data['photo']['id'] = $data['photo']['resource-id'];
4923 if ($scale !== false) {
4924 $data['photo']['data'] = base64_encode($data['photo']['data']);
4926 unset($data['photo']['datasize']); //needed only with scale param
4928 if ($type == "xml") {
4929 $data['photo']['links'] = [];
4930 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4931 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4933 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4936 $data['photo']['link'] = [];
4937 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4939 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4940 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4944 unset($data['photo']['resource-id']);
4945 unset($data['photo']['minscale']);
4946 unset($data['photo']['maxscale']);
4948 throw new NotFoundException();
4951 // retrieve item element for getting activities (like, dislike etc.) related to photo
4953 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4954 intval(local_user()),
4957 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4959 // retrieve comments on photo
4961 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4962 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4963 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4964 `contact`.`id` AS `cid`
4966 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4967 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4968 WHERE `item`.`parent` = %d AND `item`.`visible`
4969 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4970 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4971 intval($item[0]['parent']),
4973 dbesc(ACTIVITY_POST)
4976 // prepare output of comments
4977 $commentData = api_format_items($r, $user_info, false, $type);
4979 if ($type == "xml") {
4981 foreach ($commentData as $comment) {
4982 $comments[$k++ . ":comment"] = $comment;
4985 foreach ($commentData as $comment) {
4986 $comments[] = $comment;
4989 $data['photo']['friendica_comments'] = $comments;
4991 // include info if rights on photo and rights on item are mismatching
4992 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4993 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4994 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4995 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4996 $data['photo']['rights_mismatch'] = $rights_mismatch;
5003 * Similar as /mod/redir.php
5004 * redirect to 'url' after dfrn auth
5006 * Why this when there is mod/redir.php already?
5007 * This use api_user() and api_login()
5010 * c_url: url of remote contact to auth to
5011 * url: string, url to redirect after auth
5013 function api_friendica_remoteauth()
5015 $url = (x($_GET, 'url') ? $_GET['url'] : '');
5016 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
5018 if ($url === '' || $c_url === '') {
5019 throw new BadRequestException("Wrong parameters.");
5022 $c_url = normalise_link($c_url);
5026 $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5028 if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
5029 throw new BadRequestException("Unknown contact");
5032 $cid = $contact['id'];
5034 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
5036 if ($contact['duplex'] && $contact['issued-id']) {
5037 $orig_id = $contact['issued-id'];
5038 $dfrn_id = '1:' . $orig_id;
5040 if ($contact['duplex'] && $contact['dfrn-id']) {
5041 $orig_id = $contact['dfrn-id'];
5042 $dfrn_id = '0:' . $orig_id;
5045 $sec = random_string();
5048 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
5049 VALUES( %d, %s, '%s', '%s', %d )",
5057 logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
5058 $dest = ($url ? '&destination_url=' . $url : '');
5060 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5061 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5062 . '&type=profile&sec=' . $sec . $dest
5065 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5068 * @brief Return the item shared, if the item contains only the [share] tag
5070 * @param array $item Sharer item
5071 * @return array|false Shared item or false if not a reshare
5073 function api_share_as_retweet(&$item)
5075 $body = trim($item["body"]);
5077 if (Diaspora::isReshare($body, false)===false) {
5081 /// @TODO "$1" should maybe mean '$1' ?
5082 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
5084 * Skip if there is no shared message in there
5085 * we already checked this in diaspora::isReshare()
5086 * but better one more than one less...
5088 if ($body == $attributes) {
5093 // build the fake reshared item
5094 $reshared_item = $item;
5097 preg_match("/author='(.*?)'/ism", $attributes, $matches);
5098 if ($matches[1] != "") {
5099 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
5102 preg_match('/author="(.*?)"/ism', $attributes, $matches);
5103 if ($matches[1] != "") {
5104 $author = $matches[1];
5108 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
5109 if ($matches[1] != "") {
5110 $profile = $matches[1];
5113 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
5114 if ($matches[1] != "") {
5115 $profile = $matches[1];
5119 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
5120 if ($matches[1] != "") {
5121 $avatar = $matches[1];
5124 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
5125 if ($matches[1] != "") {
5126 $avatar = $matches[1];
5130 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5131 if ($matches[1] != "") {
5132 $link = $matches[1];
5135 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5136 if ($matches[1] != "") {
5137 $link = $matches[1];
5141 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5142 if ($matches[1] != "") {
5143 $posted = $matches[1];
5146 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5147 if ($matches[1] != "") {
5148 $posted = $matches[1];
5151 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5153 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5157 $reshared_item["body"] = $shared_body;
5158 $reshared_item["author-name"] = $author;
5159 $reshared_item["author-link"] = $profile;
5160 $reshared_item["author-avatar"] = $avatar;
5161 $reshared_item["plink"] = $link;
5162 $reshared_item["created"] = $posted;
5163 $reshared_item["edited"] = $posted;
5165 return $reshared_item;
5170 * @param string $profile
5172 * @return string|false
5173 * @todo remove trailing junk from profile url
5174 * @todo pump.io check has to check the website
5176 function api_get_nick($profile)
5181 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5182 dbesc(normalise_link($profile))
5185 if (DBM::is_result($r)) {
5186 $nick = $r[0]["nick"];
5191 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5192 dbesc(normalise_link($profile))
5195 if (DBM::is_result($r)) {
5196 $nick = $r[0]["nick"];
5201 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5202 if ($friendica != $profile) {
5208 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5209 if ($diaspora != $profile) {
5215 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5216 if ($twitter != $profile) {
5223 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5224 if ($StatusnetHost != $profile) {
5225 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5226 if ($StatusnetUser != $profile) {
5227 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5228 $user = json_decode($UserData);
5230 $nick = $user->screen_name;
5236 // To-Do: look at the page if its really a pumpio site
5237 //if (!$nick == "") {
5238 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5239 // if ($pumpio != $profile)
5241 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5254 * @param array $item
5258 function api_in_reply_to($item)
5262 $in_reply_to['status_id'] = null;
5263 $in_reply_to['user_id'] = null;
5264 $in_reply_to['status_id_str'] = null;
5265 $in_reply_to['user_id_str'] = null;
5266 $in_reply_to['screen_name'] = null;
5268 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5270 "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
5271 intval($item['uid']),
5272 dbesc($item['thr-parent'])
5275 if (DBM::is_result($r)) {
5276 $in_reply_to['status_id'] = intval($r[0]['id']);
5278 $in_reply_to['status_id'] = intval($item['parent']);
5281 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5284 "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
5285 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
5286 WHERE `item`.`id` = %d LIMIT 1",
5287 intval($in_reply_to['status_id'])
5290 if (DBM::is_result($r)) {
5291 if ($r[0]['nick'] == "") {
5292 $r[0]['nick'] = api_get_nick($r[0]["url"]);
5295 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
5296 $in_reply_to['user_id'] = intval($r[0]['id']);
5297 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
5300 // There seems to be situation, where both fields are identical:
5301 // https://github.com/friendica/friendica/issues/1010
5302 // This is a bugfix for that.
5303 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5304 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
5305 $in_reply_to['status_id'] = null;
5306 $in_reply_to['user_id'] = null;
5307 $in_reply_to['status_id_str'] = null;
5308 $in_reply_to['user_id_str'] = null;
5309 $in_reply_to['screen_name'] = null;
5313 return $in_reply_to;
5318 * @param string $Text
5322 function api_clean_plain_items($Text)
5324 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5326 $Text = BBCode::cleanPictureLinks($Text);
5327 $URLSearchString = "^\[\]";
5329 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
5331 if ($include_entities == "true") {
5332 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
5335 // Simplify "attachment" element
5336 $Text = api_clean_attachments($Text);
5342 * @brief Removes most sharing information for API text export
5344 * @param string $body The original body
5346 * @return string Cleaned body
5348 function api_clean_attachments($body)
5350 $data = BBCode::getAttachmentData($body);
5357 if (isset($data["text"])) {
5358 $body = $data["text"];
5360 if (($body == "") && isset($data["title"])) {
5361 $body = $data["title"];
5363 if (isset($data["url"])) {
5364 $body .= "\n".$data["url"];
5366 $body .= $data["after"];
5373 * @param array $contacts
5377 function api_best_nickname(&$contacts)
5381 if (count($contacts) == 0) {
5385 foreach ($contacts as $contact) {
5386 if ($contact["network"] == "") {
5387 $contact["network"] = "dfrn";
5388 $best_contact = [$contact];
5392 if (sizeof($best_contact) == 0) {
5393 foreach ($contacts as $contact) {
5394 if ($contact["network"] == "dfrn") {
5395 $best_contact = [$contact];
5400 if (sizeof($best_contact) == 0) {
5401 foreach ($contacts as $contact) {
5402 if ($contact["network"] == "dspr") {
5403 $best_contact = [$contact];
5408 if (sizeof($best_contact) == 0) {
5409 foreach ($contacts as $contact) {
5410 if ($contact["network"] == "stat") {
5411 $best_contact = [$contact];
5416 if (sizeof($best_contact) == 0) {
5417 foreach ($contacts as $contact) {
5418 if ($contact["network"] == "pump") {
5419 $best_contact = [$contact];
5424 if (sizeof($best_contact) == 0) {
5425 foreach ($contacts as $contact) {
5426 if ($contact["network"] == "twit") {
5427 $best_contact = [$contact];
5432 if (sizeof($best_contact) == 1) {
5433 $contacts = $best_contact;
5435 $contacts = [$contacts[0]];
5440 * Return all or a specified group of the user with the containing contacts.
5442 * @param string $type Return type (atom, rss, xml, json)
5444 * @return array|string
5446 function api_friendica_group_show($type)
5450 if (api_user() === false) {
5451 throw new ForbiddenException();
5455 $user_info = api_get_user($a);
5456 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5457 $uid = $user_info['uid'];
5459 // get data of the specified group id or all groups if not specified
5462 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5466 // error message if specified gid is not in database
5467 if (!DBM::is_result($r)) {
5468 throw new BadRequestException("gid not available");
5472 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5477 // loop through all groups and retrieve all members for adding data in the user array
5478 foreach ($r as $rr) {
5479 $members = Contact::getByGroupId($rr['id']);
5482 if ($type == "xml") {
5483 $user_element = "users";
5485 foreach ($members as $member) {
5486 $user = api_get_user($a, $member['nurl']);
5487 $users[$k++.":user"] = $user;
5490 $user_element = "user";
5491 foreach ($members as $member) {
5492 $user = api_get_user($a, $member['nurl']);
5496 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5498 return api_format_data("groups", $type, ['group' => $grps]);
5500 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5504 * Delete the specified group of the user.
5506 * @param string $type Return type (atom, rss, xml, json)
5508 * @return array|string
5510 function api_friendica_group_delete($type)
5514 if (api_user() === false) {
5515 throw new ForbiddenException();
5519 $user_info = api_get_user($a);
5520 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5521 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5522 $uid = $user_info['uid'];
5524 // error if no gid specified
5525 if ($gid == 0 || $name == "") {
5526 throw new BadRequestException('gid or name not specified');
5529 // get data of the specified group id
5531 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5535 // error message if specified gid is not in database
5536 if (!DBM::is_result($r)) {
5537 throw new BadRequestException('gid not available');
5540 // get data of the specified group id and group name
5542 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5547 // error message if specified gid is not in database
5548 if (!DBM::is_result($rname)) {
5549 throw new BadRequestException('wrong group name');
5553 $ret = Group::removeByName($uid, $name);
5556 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5557 return api_format_data("group_delete", $type, ['result' => $success]);
5559 throw new BadRequestException('other API error');
5562 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5567 * @param string $type Return type (atom, rss, xml, json)
5569 * @return array|string
5570 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5572 function api_lists_destroy($type)
5576 if (api_user() === false) {
5577 throw new ForbiddenException();
5581 $user_info = api_get_user($a);
5582 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5583 $uid = $user_info['uid'];
5585 // error if no gid specified
5587 throw new BadRequestException('gid not specified');
5590 // get data of the specified group id
5591 $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5592 // error message if specified gid is not in database
5594 throw new BadRequestException('gid not available');
5597 if (Group::remove($gid)) {
5599 'name' => $group['name'],
5600 'id' => intval($gid),
5601 'id_str' => (string) $gid,
5602 'user' => $user_info
5605 return api_format_data("lists", $type, ['lists' => $list]);
5608 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5611 * Add a new group to the database.
5613 * @param string $name Group name
5614 * @param int $uid User ID
5615 * @param array $users List of users to add to the group
5619 function group_create($name, $uid, $users = [])
5621 // error if no name specified
5623 throw new BadRequestException('group name not specified');
5626 // get data of the specified group name
5628 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5632 // error message if specified group name already exists
5633 if (DBM::is_result($rname)) {
5634 throw new BadRequestException('group name already exists');
5637 // check if specified group name is a deleted group
5639 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5643 // error message if specified group name already exists
5644 if (DBM::is_result($rname)) {
5645 $reactivate_group = true;
5649 $ret = Group::create($uid, $name);
5651 $gid = Group::getIdByName($uid, $name);
5653 throw new BadRequestException('other API error');
5657 $erroraddinguser = false;
5659 foreach ($users as $user) {
5660 $cid = $user['cid'];
5661 // check if user really exists as contact
5663 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5667 if (count($contact)) {
5668 Group::addMember($gid, $cid);
5670 $erroraddinguser = true;
5671 $errorusers[] = $cid;
5675 // return success message incl. missing users in array
5676 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
5678 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5682 * Create the specified group with the posted array of contacts.
5684 * @param string $type Return type (atom, rss, xml, json)
5686 * @return array|string
5688 function api_friendica_group_create($type)
5692 if (api_user() === false) {
5693 throw new ForbiddenException();
5697 $user_info = api_get_user($a);
5698 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5699 $uid = $user_info['uid'];
5700 $json = json_decode($_POST['json'], true);
5701 $users = $json['user'];
5703 $success = group_create($name, $uid, $users);
5705 return api_format_data("group_create", $type, ['result' => $success]);
5707 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5710 * Create a new group.
5712 * @param string $type Return type (atom, rss, xml, json)
5714 * @return array|string
5715 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5717 function api_lists_create($type)
5721 if (api_user() === false) {
5722 throw new ForbiddenException();
5726 $user_info = api_get_user($a);
5727 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5728 $uid = $user_info['uid'];
5730 $success = group_create($name, $uid);
5731 if ($success['success']) {
5733 'name' => $success['name'],
5734 'id' => intval($success['gid']),
5735 'id_str' => (string) $success['gid'],
5736 'user' => $user_info
5739 return api_format_data("lists", $type, ['lists'=>$grp]);
5742 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5745 * Update the specified group with the posted array of contacts.
5747 * @param string $type Return type (atom, rss, xml, json)
5749 * @return array|string
5751 function api_friendica_group_update($type)
5755 if (api_user() === false) {
5756 throw new ForbiddenException();
5760 $user_info = api_get_user($a);
5761 $uid = $user_info['uid'];
5762 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5763 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5764 $json = json_decode($_POST['json'], true);
5765 $users = $json['user'];
5767 // error if no name specified
5769 throw new BadRequestException('group name not specified');
5772 // error if no gid specified
5774 throw new BadRequestException('gid not specified');
5778 $members = Contact::getByGroupId($gid);
5779 foreach ($members as $member) {
5780 $cid = $member['id'];
5781 foreach ($users as $user) {
5782 $found = ($user['cid'] == $cid ? true : false);
5785 Group::removeMemberByName($uid, $name, $cid);
5790 $erroraddinguser = false;
5792 foreach ($users as $user) {
5793 $cid = $user['cid'];
5794 // check if user really exists as contact
5796 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5801 if (count($contact)) {
5802 Group::addMember($gid, $cid);
5804 $erroraddinguser = true;
5805 $errorusers[] = $cid;
5809 // return success message incl. missing users in array
5810 $status = ($erroraddinguser ? "missing user" : "ok");
5811 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5812 return api_format_data("group_update", $type, ['result' => $success]);
5815 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5818 * Update information about a group.
5820 * @param string $type Return type (atom, rss, xml, json)
5822 * @return array|string
5823 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5825 function api_lists_update($type)
5829 if (api_user() === false) {
5830 throw new ForbiddenException();
5834 $user_info = api_get_user($a);
5835 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5836 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5837 $uid = $user_info['uid'];
5839 // error if no gid specified
5841 throw new BadRequestException('gid not specified');
5844 // get data of the specified group id
5845 $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5846 // error message if specified gid is not in database
5848 throw new BadRequestException('gid not available');
5851 if (Group::update($gid, $name)) {
5854 'id' => intval($gid),
5855 'id_str' => (string) $gid,
5856 'user' => $user_info
5859 return api_format_data("lists", $type, ['lists' => $list]);
5862 return api_format_data("group_update", $type, ['result' => $success]);
5865 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5869 * @param string $type Return type (atom, rss, xml, json)
5871 * @return array|string
5873 function api_friendica_activity($type)
5877 if (api_user() === false) {
5878 throw new ForbiddenException();
5880 $verb = strtolower($a->argv[3]);
5881 $verb = preg_replace("|\..*$|", "", $verb);
5883 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5885 $res = Item::performLike($id, $verb);
5888 if ($type == "xml") {
5893 return api_format_data('ok', $type, ['ok' => $ok]);
5895 throw new BadRequestException('Error adding activity');
5899 /// @TODO move to top of file or somewhere better
5900 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5901 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5902 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5903 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5904 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5905 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5906 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5907 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5908 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5909 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5912 * @brief Returns notifications
5914 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5917 function api_friendica_notification($type)
5921 if (api_user() === false) {
5922 throw new ForbiddenException();
5925 throw new BadRequestException("Invalid argument count");
5927 $nm = new NotificationsManager();
5929 $notes = $nm->getAll([], "+seen -date", 50);
5931 if ($type == "xml") {
5933 foreach ($notes as $note) {
5934 $xmlnotes[] = ["@attributes" => $note];
5940 return api_format_data("notes", $type, ['note' => $notes]);
5944 * POST request with 'id' param as notification id
5946 * @brief Set notification as seen and returns associated item (if possible)
5948 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5951 function api_friendica_notification_seen($type)
5954 $user_info = api_get_user($a);
5956 if (api_user() === false || $user_info === false) {
5957 throw new ForbiddenException();
5960 throw new BadRequestException("Invalid argument count");
5963 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5965 $nm = new NotificationsManager();
5966 $note = $nm->getByID($id);
5967 if (is_null($note)) {
5968 throw new BadRequestException("Invalid argument");
5971 $nm->setSeen($note);
5972 if ($note['otype']=='item') {
5973 // would be really better with an ItemsManager and $im->getByID() :-P
5975 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5976 intval($note['iid']),
5977 intval(local_user())
5980 // we found the item, return it to the user
5981 $ret = api_format_items($r, $user_info, false, $type);
5982 $data = ['status' => $ret];
5983 return api_format_data("status", $type, $data);
5985 // the item can't be found, but we set the note as seen, so we count this as a success
5987 return api_format_data('result', $type, ['result' => "success"]);
5990 /// @TODO move to top of file or somewhere better
5991 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5992 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5995 * @brief update a direct_message to seen state
5997 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5998 * @return string (success result=ok, error result=error with error message)
6000 function api_friendica_direct_messages_setseen($type)
6003 if (api_user() === false) {
6004 throw new ForbiddenException();
6008 $user_info = api_get_user($a);
6009 $uid = $user_info['uid'];
6010 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
6012 // return error if id is zero
6014 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6015 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6018 // get data of the specified message id
6020 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
6025 // error message if specified id is not in database
6026 if (!DBM::is_result($r)) {
6027 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6028 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6031 // update seen indicator
6033 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
6040 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6041 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6043 $answer = ['result' => 'error', 'message' => 'unknown error'];
6044 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6048 /// @TODO move to top of file or somewhere better
6049 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6052 * @brief search for direct_messages containing a searchstring through api
6054 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6055 * @param string $box
6056 * @return string (success: success=true if found and search_result contains found messages,
6057 * success=false if nothing was found, search_result='nothing found',
6058 * error: result=error with error message)
6060 function api_friendica_direct_messages_search($type, $box = "")
6064 if (api_user() === false) {
6065 throw new ForbiddenException();
6069 $user_info = api_get_user($a);
6070 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
6071 $uid = $user_info['uid'];
6073 // error if no searchstring specified
6074 if ($searchstring == "") {
6075 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6076 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6079 // get data for the specified searchstring
6081 "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",
6083 dbesc('%'.$searchstring.'%')
6086 $profile_url = $user_info["url"];
6088 // message if nothing was found
6089 if (!DBM::is_result($r)) {
6090 $success = ['success' => false, 'search_results' => 'problem with query'];
6091 } elseif (count($r) == 0) {
6092 $success = ['success' => false, 'search_results' => 'nothing found'];
6095 foreach ($r as $item) {
6096 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6097 $recipient = $user_info;
6098 $sender = api_get_user($a, normalise_link($item['contact-url']));
6099 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6100 $recipient = api_get_user($a, normalise_link($item['contact-url']));
6101 $sender = $user_info;
6104 $ret[] = api_format_messages($item, $recipient, $sender);
6106 $success = ['success' => true, 'search_results' => $ret];
6109 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6112 /// @TODO move to top of file or somewhere better
6113 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6116 * @brief return data of all the profiles a user has to the client
6118 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6121 function api_friendica_profile_show($type)
6125 if (api_user() === false) {
6126 throw new ForbiddenException();
6130 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
6132 // retrieve general information about profiles for user
6133 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6134 $directory = Config::get('system', 'directory');
6136 // get data of the specified profile id or all profiles of the user if not specified
6137 if ($profileid != 0) {
6139 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
6144 // error message if specified gid is not in database
6145 if (!DBM::is_result($r)) {
6146 throw new BadRequestException("profile_id not available");
6150 "SELECT * FROM `profile` WHERE `uid` = %d",
6154 // loop through all returned profiles and retrieve data and users
6156 foreach ($r as $rr) {
6157 $profile = api_format_items_profiles($rr);
6159 // select all users from contact table, loop and prepare standard return for user data
6162 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
6164 intval($rr['profile_id'])
6167 foreach ($r as $rr) {
6168 $user = api_get_user($a, $rr['nurl']);
6169 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6171 $profile['users'] = $users;
6173 // add prepared profile data to array for final return
6174 if ($type == "xml") {
6175 $profiles[$k++ . ":profile"] = $profile;
6177 $profiles[] = $profile;
6181 // return settings, authenticated user and profiles data
6182 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
6184 $result = ['multi_profiles' => $multi_profiles ? true : false,
6185 'global_dir' => $directory,
6186 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
6187 'profiles' => $profiles];
6188 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6190 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6193 * Returns a list of saved searches.
6195 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6197 * @param string $type Return format: json or xml
6199 * @return string|array
6201 function api_saved_searches_list($type)
6203 $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
6206 while ($term = $terms->fetch()) {
6208 'created_at' => api_date(time()),
6209 'id' => intval($term['id']),
6210 'id_str' => $term['id'],
6211 'name' => $term['term'],
6213 'query' => $term['term']
6219 return api_format_data("terms", $type, ['terms' => $result]);
6222 /// @TODO move to top of file or somewhere better
6223 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6226 @TODO Maybe open to implement?
6228 [pagename] => api/1.1/statuses/lookup.json
6229 [id] => 605138389168451584
6230 [include_cards] => true
6231 [cards_platform] => Android-12
6232 [include_entities] => true
6233 [include_my_retweet] => 1
6235 [include_reply_count] => true
6236 [include_descendent_reply_count] => true
6240 Not implemented by now:
6241 statuses/retweets_of_me
6246 account/update_location
6247 account/update_profile_background_image
6250 friendica/profile/update
6251 friendica/profile/create
6252 friendica/profile/delete
6254 Not implemented in status.net:
6255 statuses/retweeted_to_me
6256 statuses/retweeted_by_me
6257 direct_messages/destroy
6259 account/update_delivery_device
6260 notifications/follow