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\Authentication;
15 use Friendica\Core\Config;
16 use Friendica\Core\Hook;
17 use Friendica\Core\L10n;
18 use Friendica\Core\Logger;
19 use Friendica\Core\NotificationsManager;
20 use Friendica\Core\PConfig;
21 use Friendica\Core\Protocol;
22 use Friendica\Core\System;
23 use Friendica\Core\Worker;
24 use Friendica\Database\DBA;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Group;
27 use Friendica\Model\Item;
28 use Friendica\Model\Mail;
29 use Friendica\Model\Photo;
30 use Friendica\Model\User;
31 use Friendica\Network\FKOAuth1;
32 use Friendica\Network\HTTPException;
33 use Friendica\Network\HTTPException\BadRequestException;
34 use Friendica\Network\HTTPException\ForbiddenException;
35 use Friendica\Network\HTTPException\InternalServerErrorException;
36 use Friendica\Network\HTTPException\MethodNotAllowedException;
37 use Friendica\Network\HTTPException\NotFoundException;
38 use Friendica\Network\HTTPException\NotImplementedException;
39 use Friendica\Network\HTTPException\TooManyRequestsException;
40 use Friendica\Network\HTTPException\UnauthorizedException;
41 use Friendica\Object\Image;
42 use Friendica\Protocol\Diaspora;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\Network;
45 use Friendica\Util\Proxy as ProxyUtils;
46 use Friendica\Util\Strings;
47 use Friendica\Util\XML;
49 require_once 'mod/share.php';
50 require_once 'mod/item.php';
51 require_once 'mod/wall_upload.php';
53 define('API_METHOD_ANY', '*');
54 define('API_METHOD_GET', 'GET');
55 define('API_METHOD_POST', 'POST,PUT');
56 define('API_METHOD_DELETE', 'POST,DELETE');
62 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
63 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
64 * into a page, and visitors will post something without noticing it).
66 * @brief Auth API user
70 if (!empty($_SESSION['allow_api'])) {
78 * Clients can send 'source' parameter to be show in post metadata
79 * as "sent via <source>".
80 * Some clients doesn't send a source param, we support ones we know
83 * @brief Get source name from API client
86 * Client source name, default to "api" if unset/unknown
90 if (requestdata('source')) {
91 return requestdata('source');
94 // Support for known clients that doesn't send a source name
95 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
96 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
100 Logger::log("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], Logger::DEBUG);
102 Logger::log("Empty user-agent", Logger::DEBUG);
109 * @brief Format date for API
111 * @param string $str Source date, as UTC
112 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
114 function api_date($str)
116 // Wed May 23 06:01:13 +0000 2007
117 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
121 * Register a function to be the endpoint for defined API path.
123 * @brief Register API endpoint
125 * @param string $path API URL path, relative to System::baseUrl()
126 * @param string $func Function name to call on path request
127 * @param bool $auth API need logged user
128 * @param string $method HTTP method reqiured to call this endpoint.
129 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
130 * Default to API_METHOD_ANY
132 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
142 // Workaround for hotot
143 $path = str_replace("api/", "api/1.1/", $path);
153 * Log in user via OAuth1 or Simple HTTP Auth.
154 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
156 * @brief Login API user
158 * @param object $a App
159 * @hook 'authenticate'
161 * 'username' => username from login form
162 * 'password' => password from login form
163 * 'authenticated' => return status,
164 * 'user_record' => return authenticated user record
166 * array $user logged user record
168 function api_login(App $a)
170 $oauth1 = new FKOAuth1();
173 $request = OAuthRequest::from_request();
174 list($consumer, $token) = $oauth1->verify_request($request);
175 if (!is_null($token)) {
176 $oauth1->loginUser($token->uid);
177 Hook::callAll('logged_in', $a->user);
180 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
181 var_dump($consumer, $token);
183 } catch (Exception $e) {
184 Logger::warning('API {action}: error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
187 // workaround for HTTP-auth in CGI mode
188 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
189 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
190 if (strlen($userpass)) {
191 list($name, $password) = explode(':', $userpass);
192 $_SERVER['PHP_AUTH_USER'] = $name;
193 $_SERVER['PHP_AUTH_PW'] = $password;
197 if (empty($_SERVER['PHP_AUTH_USER'])) {
198 Logger::debug('API {action}: failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
199 header('WWW-Authenticate: Basic realm="Friendica"');
200 throw new UnauthorizedException("This API requires login");
203 $user = defaults($_SERVER, 'PHP_AUTH_USER', '');
204 $password = defaults($_SERVER, 'PHP_AUTH_PW', '');
206 // allow "user@server" login (but ignore 'server' part)
207 $at = strstr($user, "@", true);
212 // next code from mod/auth.php. needs better solution
216 'username' => trim($user),
217 'password' => trim($password),
218 'authenticated' => 0,
219 'user_record' => null,
223 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
224 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
225 * and later addons should not interfere with an earlier one that succeeded.
227 Hook::callAll('authenticate', $addon_auth);
229 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
230 $record = $addon_auth['user_record'];
232 $user_id = User::authenticate(trim($user), trim($password));
233 if ($user_id !== false) {
234 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
238 if (!DBA::isResult($record)) {
239 Logger::debug('API {action}: failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
240 header('WWW-Authenticate: Basic realm="Friendica"');
241 //header('HTTP/1.0 401 Unauthorized');
242 //die('This api requires login');
243 throw new UnauthorizedException("This API requires login");
246 Authentication::setAuthenticatedSessionForUser($record);
248 $_SESSION["allow_api"] = true;
250 Hook::callAll('logged_in', $a->user);
254 * API endpoints can define which HTTP method to accept when called.
255 * This function check the current HTTP method agains endpoint
258 * @brief Check HTTP method of called API
260 * @param string $method Required methods, uppercase, separated by comma
263 function api_check_method($method)
265 if ($method == "*") {
268 return (stripos($method, defaults($_SERVER, 'REQUEST_METHOD', 'GET')) !== false);
272 * Authenticate user, call registered API function, set HTTP headers
274 * @brief Main API entry point
276 * @param object $a App
277 * @return string|array API call result
279 function api_call(App $a)
281 global $API, $called_api;
284 if (strpos($a->query_string, ".xml") > 0) {
287 if (strpos($a->query_string, ".json") > 0) {
290 if (strpos($a->query_string, ".rss") > 0) {
293 if (strpos($a->query_string, ".atom") > 0) {
298 foreach ($API as $p => $info) {
299 if (strpos($a->query_string, $p) === 0) {
300 if (!api_check_method($info['method'])) {
301 throw new MethodNotAllowedException();
304 $called_api = explode("/", $p);
305 //unset($_SERVER['PHP_AUTH_USER']);
307 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
308 if (!empty($info['auth']) && api_user() === false) {
312 Logger::info('API {action}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
313 Logger::debug('API {action} parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
315 $stamp = microtime(true);
316 $return = call_user_func($info['func'], $type);
317 $duration = (float) (microtime(true) - $stamp);
319 Logger::info('API {action} for {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
321 if (Config::get("system", "profiler")) {
322 $duration = microtime(true)-$a->performance["start"];
324 /// @TODO round() really everywhere?
326 'API {action} performance',
330 'database_read' => round($a->performance["database"] - $a->performance["database_write"], 3),
331 'database_write' => round($a->performance["database_write"], 3),
332 'cache_read' => round($a->performance["cache"], 3),
333 'cache_write' => round($a->performance["cache_write"], 3),
334 'network_io' => round($a->performance["network"], 2),
335 'file_io' => round($a->performance["file"], 2),
336 'other_io' => round($duration - ($a->performance["database"]
337 + $a->performance["cache"] + $a->performance["cache_write"]
338 + $a->performance["network"] + $a->performance["file"]), 2),
339 'total' => round($duration, 2)
343 if (Config::get("rendertime", "callstack")) {
344 $o = "Database Read:\n";
345 foreach ($a->callstack["database"] as $func => $time) {
346 $time = round($time, 3);
348 $o .= $func . ": " . $time . "\n";
351 $o .= "\nDatabase Write:\n";
352 foreach ($a->callstack["database_write"] as $func => $time) {
353 $time = round($time, 3);
355 $o .= $func . ": " . $time . "\n";
359 $o = "Cache Read:\n";
360 foreach ($a->callstack["cache"] as $func => $time) {
361 $time = round($time, 3);
363 $o .= $func . ": " . $time . "\n";
366 $o .= "\nCache Write:\n";
367 foreach ($a->callstack["cache_write"] as $func => $time) {
368 $time = round($time, 3);
370 $o .= $func . ": " . $time . "\n";
374 $o .= "\nNetwork:\n";
375 foreach ($a->callstack["network"] as $func => $time) {
376 $time = round($time, 3);
378 $o .= $func . ": " . $time . "\n";
381 Logger::debug($o, ['module' => 'api', 'action' => 'call']);
385 if (false === $return) {
387 * api function returned false withour throw an
388 * exception. This should not happend, throw a 500
390 throw new InternalServerErrorException();
395 header("Content-Type: text/xml");
398 header("Content-Type: application/json");
399 $json = json_encode(end($return));
400 if (!empty($_GET['callback'])) {
401 $json = $_GET['callback'] . "(" . $json . ")";
406 header("Content-Type: application/rss+xml");
407 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
410 header("Content-Type: application/atom+xml");
411 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
418 Logger::warning('API {action} not implemented', ['module' => 'api', 'action' => 'call']);
419 throw new NotImplementedException();
420 } catch (HTTPException $e) {
421 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
422 return api_error($type, $e);
427 * @brief Format API error string
429 * @param string $type Return type (xml, json, rss, as)
430 * @param object $e HTTPException Error object
431 * @return string|array error message formatted as $type
433 function api_error($type, $e)
437 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
438 /// @TODO: https://dev.twitter.com/overview/api/response-codes
440 $error = ["error" => $error,
441 "code" => $e->httpcode . " " . $e->httpdesc,
442 "request" => $a->query_string];
444 $return = api_format_data('status', $type, ['status' => $error]);
448 header("Content-Type: text/xml");
451 header("Content-Type: application/json");
452 $return = json_encode($return);
455 header("Content-Type: application/rss+xml");
458 header("Content-Type: application/atom+xml");
466 * @brief Set values for RSS template
469 * @param array $arr Array to be passed to template
470 * @param array $user_info User info
472 * @todo find proper type-hints
474 function api_rss_extra(App $a, $arr, $user_info)
476 if (is_null($user_info)) {
477 $user_info = api_get_user($a);
480 $arr['$user'] = $user_info;
482 'alternate' => $user_info['url'],
483 'self' => System::baseUrl() . "/" . $a->query_string,
484 'base' => System::baseUrl(),
485 'updated' => api_date(null),
486 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
487 'language' => $user_info['lang'],
488 'logo' => System::baseUrl() . "/images/friendica-32.png",
496 * @brief Unique contact to contact url.
498 * @param int $id Contact id
499 * @return bool|string
500 * Contact url or False if contact id is unknown
502 function api_unique_id_to_nurl($id)
504 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
506 if (DBA::isResult($r)) {
514 * @brief Get user info array.
516 * @param object $a App
517 * @param int|string $contact_id Contact ID or URL
519 function api_get_user(App $a, $contact_id = null)
527 Logger::info('API {action}: Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
529 // Searching for contact URL
530 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
531 $user = DBA::escape(Strings::normaliseLink($contact_id));
533 $extra_query = "AND `contact`.`nurl` = '%s' ";
534 if (api_user() !== false) {
535 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
539 // Searching for contact id with uid = 0
540 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
541 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
544 throw new BadRequestException("User ID ".$contact_id." not found.");
548 $extra_query = "AND `contact`.`nurl` = '%s' ";
549 if (api_user() !== false) {
550 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
554 if (is_null($user) && !empty($_GET['user_id'])) {
555 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
558 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
562 $extra_query = "AND `contact`.`nurl` = '%s' ";
563 if (api_user() !== false) {
564 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
567 if (is_null($user) && !empty($_GET['screen_name'])) {
568 $user = DBA::escape($_GET['screen_name']);
569 $extra_query = "AND `contact`.`nick` = '%s' ";
570 if (api_user() !== false) {
571 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
575 if (is_null($user) && !empty($_GET['profileurl'])) {
576 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
577 $extra_query = "AND `contact`.`nurl` = '%s' ";
578 if (api_user() !== false) {
579 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
583 // $called_api is the API path exploded on / and is expected to have at least 2 elements
584 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
585 $argid = count($called_api);
586 if (!empty($a->argv[$argid])) {
587 $data = explode(".", $a->argv[$argid]);
588 if (count($data) > 1) {
589 list($user, $null) = $data;
592 if (is_numeric($user)) {
593 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
597 $extra_query = "AND `contact`.`nurl` = '%s' ";
598 if (api_user() !== false) {
599 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
603 $user = DBA::escape($user);
604 $extra_query = "AND `contact`.`nick` = '%s' ";
605 if (api_user() !== false) {
606 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
611 Logger::info('API {action}: getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
614 if (api_user() === false) {
618 $user = $_SESSION['uid'];
619 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
623 Logger::info('API {action}: found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
627 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
633 // Selecting the id by priority, friendica first
634 if (is_array($uinfo)) {
635 api_best_nickname($uinfo);
638 // if the contact wasn't found, fetch it from the contacts with uid = 0
639 if (!DBA::isResult($uinfo)) {
641 throw new BadRequestException("User not found.");
644 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
646 if (DBA::isResult($contact)) {
647 // If no nick where given, extract it from the address
648 if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
649 $contact['nick'] = api_get_nick($contact["url"]);
653 'id' => $contact["id"],
654 'id_str' => (string) $contact["id"],
655 'name' => $contact["name"],
656 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
657 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url']),
658 'description' => $contact["about"],
659 'profile_image_url' => $contact["micro"],
660 'profile_image_url_https' => $contact["micro"],
661 'profile_image_url_profile_size' => $contact["thumb"],
662 'profile_image_url_large' => $contact["photo"],
663 'url' => $contact["url"],
664 'protected' => false,
665 'followers_count' => 0,
666 'friends_count' => 0,
668 'created_at' => api_date($contact["created"]),
669 'favourites_count' => 0,
671 'time_zone' => 'UTC',
672 'geo_enabled' => false,
674 'statuses_count' => 0,
676 'contributors_enabled' => false,
677 'is_translator' => false,
678 'is_translation_enabled' => false,
679 'following' => false,
680 'follow_request_sent' => false,
681 'statusnet_blocking' => false,
682 'notifications' => false,
683 'statusnet_profile_url' => $contact["url"],
685 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
686 'pid' => Contact::getIdForURL($contact["url"], 0, true),
688 'network' => $contact["network"],
693 throw new BadRequestException("User ".$url." not found.");
697 if ($uinfo[0]['self']) {
698 if ($uinfo[0]['network'] == "") {
699 $uinfo[0]['network'] = Protocol::DFRN;
702 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
703 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
710 // Add a nick if it isn't present there
711 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
712 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
715 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
717 if (!empty($profile['about'])) {
718 $description = $profile['about'];
720 $description = $uinfo[0]["about"];
723 if (!empty($usr['default-location'])) {
724 $location = $usr['default-location'];
725 } elseif (!empty($uinfo[0]["location"])) {
726 $location = $uinfo[0]["location"];
728 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
732 'id' => intval($pcontact_id),
733 'id_str' => (string) intval($pcontact_id),
734 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
735 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
736 'location' => $location,
737 'description' => $description,
738 'profile_image_url' => $uinfo[0]['micro'],
739 'profile_image_url_https' => $uinfo[0]['micro'],
740 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
741 'profile_image_url_large' => $uinfo[0]["photo"],
742 'url' => $uinfo[0]['url'],
743 'protected' => false,
744 'followers_count' => intval($countfollowers),
745 'friends_count' => intval($countfriends),
747 'created_at' => api_date($uinfo[0]['created']),
748 'favourites_count' => intval($starred),
750 'time_zone' => 'UTC',
751 'geo_enabled' => false,
753 'statuses_count' => intval($countitems),
755 'contributors_enabled' => false,
756 'is_translator' => false,
757 'is_translation_enabled' => false,
758 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
759 'follow_request_sent' => false,
760 'statusnet_blocking' => false,
761 'notifications' => false,
763 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
764 'statusnet_profile_url' => $uinfo[0]['url'],
765 'uid' => intval($uinfo[0]['uid']),
766 'cid' => intval($uinfo[0]['cid']),
767 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
768 'self' => $uinfo[0]['self'],
769 'network' => $uinfo[0]['network'],
772 // If this is a local user and it uses Frio, we can get its color preferences.
774 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
775 if ($theme_info['theme'] === 'frio') {
776 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
778 if ($schema && ($schema != '---')) {
779 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
780 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
781 require_once $schemefile;
784 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
785 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
786 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
788 if (empty($nav_bg)) {
791 if (empty($link_color)) {
792 $link_color = "#6fdbe8";
794 if (empty($bgcolor)) {
795 $bgcolor = "#ededed";
798 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
799 $ret['profile_link_color'] = str_replace('#', '', $link_color);
800 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
808 * @brief return api-formatted array for item's author and owner
810 * @param object $a App
811 * @param array $item item from db
812 * @return array(array:author, array:owner)
814 function api_item_get_user(App $a, $item)
816 $status_user = api_get_user($a, defaults($item, 'author-id', null));
818 $status_user["protected"] = defaults($item, 'private', 0);
820 if (defaults($item, 'thr-parent', '') == defaults($item, 'uri', '')) {
821 $owner_user = api_get_user($a, defaults($item, 'owner-id', null));
823 $owner_user = $status_user;
826 return ([$status_user, $owner_user]);
830 * @brief walks recursively through an array with the possibility to change value and key
832 * @param array $array The array to walk through
833 * @param string $callback The callback function
835 * @return array the transformed array
837 function api_walk_recursive(array &$array, callable $callback)
841 foreach ($array as $k => $v) {
843 if ($callback($v, $k)) {
844 $new_array[$k] = api_walk_recursive($v, $callback);
847 if ($callback($v, $k)) {
858 * @brief Callback function to transform the array in an array that can be transformed in a XML file
860 * @param mixed $item Array item value
861 * @param string $key Array key
863 * @return boolean Should the array item be deleted?
865 function api_reformat_xml(&$item, &$key)
867 if (is_bool($item)) {
868 $item = ($item ? "true" : "false");
871 if (substr($key, 0, 10) == "statusnet_") {
872 $key = "statusnet:".substr($key, 10);
873 } elseif (substr($key, 0, 10) == "friendica_") {
874 $key = "friendica:".substr($key, 10);
876 /// @TODO old-lost code?
878 // $key = "default:".$key;
884 * @brief Creates the XML from a JSON style array
886 * @param array $data JSON style array
887 * @param string $root_element Name of the root element
889 * @return string The XML data
891 function api_create_xml(array $data, $root_element)
893 $childname = key($data);
894 $data2 = array_pop($data);
896 $namespaces = ["" => "http://api.twitter.com",
897 "statusnet" => "http://status.net/schema/api/1/",
898 "friendica" => "http://friendi.ca/schema/api/1/",
899 "georss" => "http://www.georss.org/georss"];
901 /// @todo Auto detection of needed namespaces
902 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
906 if (is_array($data2)) {
908 api_walk_recursive($data2, "api_reformat_xml");
914 foreach ($data2 as $item) {
915 $data4[$i++ . ":" . $childname] = $item;
922 $data3 = [$root_element => $data2];
924 $ret = XML::fromArray($data3, $xml, false, $namespaces);
929 * @brief Formats the data according to the data type
931 * @param string $root_element Name of the root element
932 * @param string $type Return type (atom, rss, xml, json)
933 * @param array $data JSON style array
935 * @return (string|array) XML data or JSON data
937 function api_format_data($root_element, $type, $data)
943 $ret = api_create_xml($data, $root_element);
958 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
959 * returns a 401 status code and an error message if not.
960 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
962 * @param string $type Return type (atom, rss, xml, json)
964 function api_account_verify_credentials($type)
969 if (api_user() === false) {
970 throw new ForbiddenException();
973 unset($_REQUEST["user_id"]);
974 unset($_GET["user_id"]);
976 unset($_REQUEST["screen_name"]);
977 unset($_GET["screen_name"]);
979 $skip_status = defaults($_REQUEST, 'skip_status', false);
981 $user_info = api_get_user($a);
983 // "verified" isn't used here in the standard
984 unset($user_info["verified"]);
986 // - Adding last status
988 $user_info["status"] = api_status_show("raw");
989 if (!count($user_info["status"])) {
990 unset($user_info["status"]);
992 unset($user_info["status"]["user"]);
996 // "uid" and "self" are only needed for some internal stuff, so remove it from here
997 unset($user_info["uid"]);
998 unset($user_info["self"]);
1000 return api_format_data("user", $type, ['user' => $user_info]);
1003 /// @TODO move to top of file or somewhere better
1004 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1007 * Get data from $_POST or $_GET
1011 function requestdata($k)
1013 if (!empty($_POST[$k])) {
1016 if (!empty($_GET[$k])) {
1023 * Deprecated function to upload media.
1025 * @param string $type Return type (atom, rss, xml, json)
1027 * @return array|string
1029 function api_statuses_mediap($type)
1033 if (api_user() === false) {
1034 Logger::log('api_statuses_update: no user');
1035 throw new ForbiddenException();
1037 $user_info = api_get_user($a);
1039 $_REQUEST['profile_uid'] = api_user();
1040 $_REQUEST['api_source'] = true;
1041 $txt = requestdata('status');
1042 /// @TODO old-lost code?
1043 //$txt = urldecode(requestdata('status'));
1045 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1046 $txt = HTML::toBBCodeVideo($txt);
1047 $config = HTMLPurifier_Config::createDefault();
1048 $config->set('Cache.DefinitionImpl', null);
1049 $purifier = new HTMLPurifier($config);
1050 $txt = $purifier->purify($txt);
1052 $txt = HTML::toBBCode($txt);
1054 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1056 $picture = wall_upload_post($a, false);
1058 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1059 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1060 $item_id = item_post($a);
1062 // output the post that we just posted.
1063 return api_status_show($type, $item_id);
1066 /// @TODO move this to top of file or somewhere better!
1067 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1070 * Updates the user’s current status.
1072 * @param string $type Return type (atom, rss, xml, json)
1074 * @return array|string
1075 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1077 function api_statuses_update($type)
1081 if (api_user() === false) {
1082 Logger::log('api_statuses_update: no user');
1083 throw new ForbiddenException();
1088 // convert $_POST array items to the form we use for web posts.
1089 if (requestdata('htmlstatus')) {
1090 $txt = requestdata('htmlstatus');
1091 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1092 $txt = HTML::toBBCodeVideo($txt);
1094 $config = HTMLPurifier_Config::createDefault();
1095 $config->set('Cache.DefinitionImpl', null);
1097 $purifier = new HTMLPurifier($config);
1098 $txt = $purifier->purify($txt);
1100 $_REQUEST['body'] = HTML::toBBCode($txt);
1103 $_REQUEST['body'] = requestdata('status');
1106 $_REQUEST['title'] = requestdata('title');
1108 $parent = requestdata('in_reply_to_status_id');
1110 // Twidere sends "-1" if it is no reply ...
1111 if ($parent == -1) {
1115 if (ctype_digit($parent)) {
1116 $_REQUEST['parent'] = $parent;
1118 $_REQUEST['parent_uri'] = $parent;
1121 if (requestdata('lat') && requestdata('long')) {
1122 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1124 $_REQUEST['profile_uid'] = api_user();
1127 // Check for throttling (maximum posts per day, week and month)
1128 $throttle_day = Config::get('system', 'throttle_limit_day');
1129 if ($throttle_day > 0) {
1130 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1132 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1133 $posts_day = DBA::count('thread', $condition);
1135 if ($posts_day > $throttle_day) {
1136 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1137 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1138 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));
1142 $throttle_week = Config::get('system', 'throttle_limit_week');
1143 if ($throttle_week > 0) {
1144 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1146 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1147 $posts_week = DBA::count('thread', $condition);
1149 if ($posts_week > $throttle_week) {
1150 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1151 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1152 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));
1156 $throttle_month = Config::get('system', 'throttle_limit_month');
1157 if ($throttle_month > 0) {
1158 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1160 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1161 $posts_month = DBA::count('thread', $condition);
1163 if ($posts_month > $throttle_month) {
1164 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1165 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1166 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));
1171 if (!empty($_FILES['media'])) {
1172 // upload the image if we have one
1173 $picture = wall_upload_post($a, false);
1174 if (is_array($picture)) {
1175 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1179 // To-Do: Multiple IDs
1180 if (requestdata('media_ids')) {
1182 "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",
1183 intval(requestdata('media_ids')),
1186 if (DBA::isResult($r)) {
1187 $phototypes = Image::supportedTypes();
1188 $ext = $phototypes[$r[0]['type']];
1189 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1190 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1194 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1196 $_REQUEST['api_source'] = true;
1198 if (empty($_REQUEST['source'])) {
1199 $_REQUEST["source"] = api_source();
1202 // call out normal post function
1203 $item_id = item_post($a);
1205 // output the post that we just posted.
1206 return api_status_show($type, $item_id);
1209 /// @TODO move to top of file or somewhere better
1210 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1211 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1214 * Uploads an image to Friendica.
1217 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1219 function api_media_upload()
1223 if (api_user() === false) {
1224 Logger::log('no user');
1225 throw new ForbiddenException();
1230 if (empty($_FILES['media'])) {
1232 throw new BadRequestException("No media.");
1235 $media = wall_upload_post($a, false);
1238 throw new InternalServerErrorException();
1242 $returndata["media_id"] = $media["id"];
1243 $returndata["media_id_string"] = (string)$media["id"];
1244 $returndata["size"] = $media["size"];
1245 $returndata["image"] = ["w" => $media["width"],
1246 "h" => $media["height"],
1247 "image_type" => $media["type"],
1248 "friendica_preview_url" => $media["preview"]];
1250 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1252 return ["media" => $returndata];
1255 /// @TODO move to top of file or somewhere better
1256 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1260 * @param string $type Return type (atom, rss, xml, json)
1262 * @return array|string
1264 function api_status_show($type, $item_id = 0)
1268 $user_info = api_get_user($a);
1270 Logger::log('api_status_show: user_info: '.print_r($user_info, true), Logger::DEBUG);
1272 if ($type == "raw") {
1273 $privacy_sql = "AND NOT `private`";
1278 if (!empty($item_id)) {
1279 // Get the item with the given id
1280 $condition = ['id' => $item_id];
1282 // get last public wall message
1283 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1284 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1286 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1288 if (DBA::isResult($lastwall)) {
1289 $in_reply_to = api_in_reply_to($lastwall);
1291 $converted = api_convert_item($lastwall);
1293 if ($type == "xml") {
1294 $geo = "georss:point";
1300 'created_at' => api_date($lastwall['created']),
1301 'id' => intval($lastwall['id']),
1302 'id_str' => (string) $lastwall['id'],
1303 'text' => $converted["text"],
1304 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1305 'truncated' => false,
1306 'in_reply_to_status_id' => $in_reply_to['status_id'],
1307 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1308 'in_reply_to_user_id' => $in_reply_to['user_id'],
1309 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1310 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1311 'user' => $user_info,
1313 'coordinates' => '',
1315 'contributors' => '',
1316 'is_quote_status' => false,
1317 'retweet_count' => 0,
1318 'favorite_count' => 0,
1319 'favorited' => $lastwall['starred'] ? true : false,
1320 'retweeted' => false,
1321 'possibly_sensitive' => false,
1323 'statusnet_html' => $converted["html"],
1324 'statusnet_conversation_id' => $lastwall['parent'],
1325 'external_url' => System::baseUrl() . '/display/' . $lastwall['guid'],
1328 if (count($converted["attachments"]) > 0) {
1329 $status_info["attachments"] = $converted["attachments"];
1332 if (count($converted["entities"]) > 0) {
1333 $status_info["entities"] = $converted["entities"];
1336 if ($status_info["source"] == 'web') {
1337 $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1338 } elseif (ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) != $status_info["source"]) {
1339 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']).')');
1342 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1343 unset($status_info["user"]["uid"]);
1344 unset($status_info["user"]["self"]);
1346 Logger::log('status_info: '.print_r($status_info, true), Logger::DEBUG);
1348 if ($type == "raw") {
1349 return $status_info;
1352 return api_format_data("statuses", $type, ['status' => $status_info]);
1357 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1358 * The author's most recent status will be returned inline.
1360 * @param string $type Return type (atom, rss, xml, json)
1361 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1363 function api_users_show($type)
1367 $user_info = api_get_user($a);
1369 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1370 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'private' => false];
1371 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1373 if (DBA::isResult($lastwall)) {
1374 $in_reply_to = api_in_reply_to($lastwall);
1376 $converted = api_convert_item($lastwall);
1378 if ($type == "xml") {
1379 $geo = "georss:point";
1384 $user_info['status'] = [
1385 'text' => $converted["text"],
1386 'truncated' => false,
1387 'created_at' => api_date($lastwall['created']),
1388 'in_reply_to_status_id' => $in_reply_to['status_id'],
1389 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1390 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1391 'id' => intval($lastwall['contact-id']),
1392 'id_str' => (string) $lastwall['contact-id'],
1393 'in_reply_to_user_id' => $in_reply_to['user_id'],
1394 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1395 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1397 'favorited' => $lastwall['starred'] ? true : false,
1398 'statusnet_html' => $converted["html"],
1399 'statusnet_conversation_id' => $lastwall['parent'],
1400 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1403 if (count($converted["attachments"]) > 0) {
1404 $user_info["status"]["attachments"] = $converted["attachments"];
1407 if (count($converted["entities"]) > 0) {
1408 $user_info["status"]["entities"] = $converted["entities"];
1411 if ($user_info["status"]["source"] == 'web') {
1412 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1415 if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
1416 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) . ')');
1420 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1421 unset($user_info["uid"]);
1422 unset($user_info["self"]);
1424 return api_format_data("user", $type, ['user' => $user_info]);
1427 /// @TODO move to top of file or somewhere better
1428 api_register_func('api/users/show', 'api_users_show');
1429 api_register_func('api/externalprofile/show', 'api_users_show');
1432 * Search a public user account.
1434 * @param string $type Return type (atom, rss, xml, json)
1436 * @return array|string
1437 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1439 function api_users_search($type)
1445 if (!empty($_GET['q'])) {
1446 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1448 if (!DBA::isResult($r)) {
1449 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1452 if (DBA::isResult($r)) {
1454 foreach ($r as $user) {
1455 $user_info = api_get_user($a, $user["id"]);
1457 if ($type == "xml") {
1458 $userlist[$k++.":user"] = $user_info;
1460 $userlist[] = $user_info;
1463 $userlist = ["users" => $userlist];
1465 throw new BadRequestException("User ".$_GET["q"]." not found.");
1468 throw new BadRequestException("No user specified.");
1471 return api_format_data("users", $type, $userlist);
1474 /// @TODO move to top of file or somewhere better
1475 api_register_func('api/users/search', 'api_users_search');
1478 * Return user objects
1480 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1482 * @param string $type Return format: json or xml
1484 * @return array|string
1485 * @throws NotFoundException if the results are empty.
1487 function api_users_lookup($type)
1491 if (!empty($_REQUEST['user_id'])) {
1492 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1494 $users[] = api_get_user(get_app(), $id);
1499 if (empty($users)) {
1500 throw new NotFoundException;
1503 return api_format_data("users", $type, ['users' => $users]);
1506 /// @TODO move to top of file or somewhere better
1507 api_register_func('api/users/lookup', 'api_users_lookup', true);
1510 * Returns statuses that match a specified query.
1512 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1514 * @param string $type Return format: json, xml, atom, rss
1516 * @return array|string
1517 * @throws BadRequestException if the "q" parameter is missing.
1519 function api_search($type)
1522 $user_info = api_get_user($a);
1524 if (api_user() === false || $user_info === false) { throw new ForbiddenException(); }
1526 if (empty($_REQUEST['q'])) { throw new BadRequestException('q parameter is required.'); }
1528 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1531 $data['status'] = [];
1533 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1534 if (!empty($_REQUEST['rpp'])) {
1535 $count = $_REQUEST['rpp'];
1536 } elseif (!empty($_REQUEST['count'])) {
1537 $count = $_REQUEST['count'];
1540 $since_id = defaults($_REQUEST, 'since_id', 0);
1541 $max_id = defaults($_REQUEST, 'max_id', 0);
1542 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1543 $start = $page * $count;
1544 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1545 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1546 $searchTerm = $matches[1];
1547 $condition = ["`oid` > ?
1548 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1549 AND `otype` = ? AND `type` = ? AND `term` = ?",
1550 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1552 $condition[0] .= ' AND `oid` <= ?';
1553 $condition[] = $max_id;
1555 $terms = DBA::select('term', ['oid'], $condition, []);
1557 while ($term = DBA::fetch($terms)) {
1558 $itemIds[] = $term['oid'];
1562 if (empty($itemIds)) {
1563 return api_format_data('statuses', $type, $data);
1566 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1567 if ($exclude_replies) {
1568 $preCondition[] = '`id` = `parent`';
1571 $condition = [implode(' AND ', $preCondition)];
1573 $condition = ["`id` > ?
1574 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1575 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1576 AND `body` LIKE CONCAT('%',?,'%')",
1577 $since_id, api_user(), $_REQUEST['q']];
1579 $condition[0] .= ' AND `id` <= ?';
1580 $condition[] = $max_id;
1584 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1586 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1588 bindComments($data['status']);
1590 return api_format_data('statuses', $type, $data);
1593 /// @TODO move to top of file or somewhere better
1594 api_register_func('api/search/tweets', 'api_search', true);
1595 api_register_func('api/search', 'api_search', true);
1598 * Returns the most recent statuses posted by the user and the users they follow.
1600 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1602 * @param string $type Return type (atom, rss, xml, json)
1604 * @todo Optional parameters
1605 * @todo Add reply info
1607 function api_statuses_home_timeline($type)
1610 $user_info = api_get_user($a);
1612 if (api_user() === false || $user_info === false) {
1613 throw new ForbiddenException();
1616 unset($_REQUEST["user_id"]);
1617 unset($_GET["user_id"]);
1619 unset($_REQUEST["screen_name"]);
1620 unset($_GET["screen_name"]);
1622 // get last network messages
1625 $count = defaults($_REQUEST, 'count', 20);
1626 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1630 $since_id = defaults($_REQUEST, 'since_id', 0);
1631 $max_id = defaults($_REQUEST, 'max_id', 0);
1632 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1633 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1635 $start = $page * $count;
1637 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1638 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1641 $condition[0] .= " AND `item`.`id` <= ?";
1642 $condition[] = $max_id;
1644 if ($exclude_replies) {
1645 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1647 if ($conversation_id > 0) {
1648 $condition[0] .= " AND `item`.`parent` = ?";
1649 $condition[] = $conversation_id;
1652 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1653 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1655 $items = Item::inArray($statuses);
1657 $ret = api_format_items($items, $user_info, false, $type);
1659 // Set all posts from the query above to seen
1661 foreach ($items as $item) {
1662 $idarray[] = intval($item["id"]);
1665 if (!empty($idarray)) {
1666 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1668 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1674 $data = ['status' => $ret];
1679 $data = api_rss_extra($a, $data, $user_info);
1683 return api_format_data("statuses", $type, $data);
1687 /// @TODO move to top of file or somewhere better
1688 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1689 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1692 * Returns the most recent statuses from public users.
1694 * @param string $type Return type (atom, rss, xml, json)
1696 * @return array|string
1698 function api_statuses_public_timeline($type)
1701 $user_info = api_get_user($a);
1703 if (api_user() === false || $user_info === false) {
1704 throw new ForbiddenException();
1707 // get last network messages
1710 $count = defaults($_REQUEST, 'count', 20);
1711 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
1715 $since_id = defaults($_REQUEST, 'since_id', 0);
1716 $max_id = defaults($_REQUEST, 'max_id', 0);
1717 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1718 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1720 $start = $page * $count;
1722 if ($exclude_replies && !$conversation_id) {
1723 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall`",
1724 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1727 $condition[0] .= " AND `thread`.`iid` <= ?";
1728 $condition[] = $max_id;
1731 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1732 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1734 $r = Item::inArray($statuses);
1736 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin`",
1737 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1740 $condition[0] .= " AND `item`.`id` <= ?";
1741 $condition[] = $max_id;
1743 if ($conversation_id > 0) {
1744 $condition[0] .= " AND `item`.`parent` = ?";
1745 $condition[] = $conversation_id;
1748 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1749 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1751 $r = Item::inArray($statuses);
1754 $ret = api_format_items($r, $user_info, false, $type);
1758 $data = ['status' => $ret];
1763 $data = api_rss_extra($a, $data, $user_info);
1767 return api_format_data("statuses", $type, $data);
1770 /// @TODO move to top of file or somewhere better
1771 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1774 * Returns the most recent statuses posted by users this node knows about.
1776 * @brief Returns the list of public federated posts this node knows about
1778 * @param string $type Return format: json, xml, atom, rss
1779 * @return array|string
1780 * @throws ForbiddenException
1782 function api_statuses_networkpublic_timeline($type)
1785 $user_info = api_get_user($a);
1787 if (api_user() === false || $user_info === false) {
1788 throw new ForbiddenException();
1791 $since_id = defaults($_REQUEST, 'since_id', 0);
1792 $max_id = defaults($_REQUEST, 'max_id', 0);
1795 $count = defaults($_REQUEST, 'count', 20);
1796 $page = defaults($_REQUEST, 'page', 1);
1800 $start = ($page - 1) * $count;
1802 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1803 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1806 $condition[0] .= " AND `thread`.`iid` <= ?";
1807 $condition[] = $max_id;
1810 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1811 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1813 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1817 $data = ['status' => $ret];
1822 $data = api_rss_extra($a, $data, $user_info);
1826 return api_format_data("statuses", $type, $data);
1829 /// @TODO move to top of file or somewhere better
1830 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1833 * Returns a single status.
1835 * @param string $type Return type (atom, rss, xml, json)
1837 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1839 function api_statuses_show($type)
1842 $user_info = api_get_user($a);
1844 if (api_user() === false || $user_info === false) {
1845 throw new ForbiddenException();
1849 $id = intval(defaults($a->argv, 3, 0));
1852 $id = intval(defaults($_REQUEST, 'id', 0));
1857 $id = intval(defaults($a->argv, 4, 0));
1860 Logger::log('API: api_statuses_show: ' . $id);
1862 $conversation = !empty($_REQUEST['conversation']);
1864 // try to fetch the item for the local user - or the public item, if there is no local one
1865 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1866 if (!DBA::isResult($uri_item)) {
1867 throw new BadRequestException("There is no status with this id.");
1870 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1871 if (!DBA::isResult($item)) {
1872 throw new BadRequestException("There is no status with this id.");
1877 if ($conversation) {
1878 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1879 $params = ['order' => ['id' => true]];
1881 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1885 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1887 /// @TODO How about copying this to above methods which don't check $r ?
1888 if (!DBA::isResult($statuses)) {
1889 throw new BadRequestException("There is no status with this id.");
1892 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1894 if ($conversation) {
1895 $data = ['status' => $ret];
1896 return api_format_data("statuses", $type, $data);
1898 $data = ['status' => $ret[0]];
1899 return api_format_data("status", $type, $data);
1903 /// @TODO move to top of file or somewhere better
1904 api_register_func('api/statuses/show', 'api_statuses_show', true);
1908 * @param string $type Return type (atom, rss, xml, json)
1910 * @todo nothing to say?
1912 function api_conversation_show($type)
1915 $user_info = api_get_user($a);
1917 if (api_user() === false || $user_info === false) {
1918 throw new ForbiddenException();
1922 $id = intval(defaults($a->argv , 3 , 0));
1923 $since_id = intval(defaults($_REQUEST, 'since_id', 0));
1924 $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
1925 $count = intval(defaults($_REQUEST, 'count' , 20));
1926 $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
1931 $start = $page * $count;
1934 $id = intval(defaults($_REQUEST, 'id', 0));
1939 $id = intval(defaults($a->argv, 4, 0));
1942 Logger::info('API: {action} - {subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1944 // try to fetch the item for the local user - or the public item, if there is no local one
1945 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1946 if (!DBA::isResult($item)) {
1947 throw new BadRequestException("There is no status with this id.");
1950 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1951 if (!DBA::isResult($parent)) {
1952 throw new BadRequestException("There is no status with this id.");
1955 $id = $parent['id'];
1957 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1958 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1961 $condition[0] .= " AND `item`.`id` <= ?";
1962 $condition[] = $max_id;
1965 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1966 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1968 if (!DBA::isResult($statuses)) {
1969 throw new BadRequestException("There is no status with id $id.");
1972 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1974 $data = ['status' => $ret];
1975 return api_format_data("statuses", $type, $data);
1978 /// @TODO move to top of file or somewhere better
1979 api_register_func('api/conversation/show', 'api_conversation_show', true);
1980 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1985 * @param string $type Return type (atom, rss, xml, json)
1987 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1989 function api_statuses_repeat($type)
1995 if (api_user() === false) {
1996 throw new ForbiddenException();
2002 $id = intval(defaults($a->argv, 3, 0));
2005 $id = intval(defaults($_REQUEST, 'id', 0));
2010 $id = intval(defaults($a->argv, 4, 0));
2013 Logger::log('API: api_statuses_repeat: '.$id);
2015 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2016 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2018 if (DBA::isResult($item) && $item['body'] != "") {
2019 if (strpos($item['body'], "[/share]") !== false) {
2020 $pos = strpos($item['body'], "[share");
2021 $post = substr($item['body'], $pos);
2023 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2025 $post .= $item['body'];
2026 $post .= "[/share]";
2028 $_REQUEST['body'] = $post;
2029 $_REQUEST['profile_uid'] = api_user();
2030 $_REQUEST['api_source'] = true;
2032 if (empty($_REQUEST['source'])) {
2033 $_REQUEST["source"] = api_source();
2036 $item_id = item_post($a);
2038 throw new ForbiddenException();
2041 // output the post that we just posted.
2043 return api_status_show($type, $item_id);
2046 /// @TODO move to top of file or somewhere better
2047 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2050 * Destroys a specific status.
2052 * @param string $type Return type (atom, rss, xml, json)
2054 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2056 function api_statuses_destroy($type)
2060 if (api_user() === false) {
2061 throw new ForbiddenException();
2067 $id = intval(defaults($a->argv, 3, 0));
2070 $id = intval(defaults($_REQUEST, 'id', 0));
2075 $id = intval(defaults($a->argv, 4, 0));
2078 Logger::log('API: api_statuses_destroy: '.$id);
2080 $ret = api_statuses_show($type);
2082 Item::deleteForUser(['id' => $id], api_user());
2087 /// @TODO move to top of file or somewhere better
2088 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2091 * Returns the most recent mentions.
2093 * @param string $type Return type (atom, rss, xml, json)
2095 * @see http://developer.twitter.com/doc/get/statuses/mentions
2097 function api_statuses_mentions($type)
2100 $user_info = api_get_user($a);
2102 if (api_user() === false || $user_info === false) {
2103 throw new ForbiddenException();
2106 unset($_REQUEST["user_id"]);
2107 unset($_GET["user_id"]);
2109 unset($_REQUEST["screen_name"]);
2110 unset($_GET["screen_name"]);
2112 // get last network messages
2115 $since_id = defaults($_REQUEST, 'since_id', 0);
2116 $max_id = defaults($_REQUEST, 'max_id' , 0);
2117 $count = defaults($_REQUEST, 'count' , 20);
2118 $page = defaults($_REQUEST, 'page' , 1);
2123 $start = ($page - 1) * $count;
2125 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2126 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2127 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2130 $condition[0] .= " AND `item`.`id` <= ?";
2131 $condition[] = $max_id;
2134 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2135 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2137 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2139 $data = ['status' => $ret];
2144 $data = api_rss_extra($a, $data, $user_info);
2148 return api_format_data("statuses", $type, $data);
2151 /// @TODO move to top of file or somewhere better
2152 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2153 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2156 * Returns the most recent statuses posted by the user.
2158 * @brief Returns a user's public timeline
2160 * @param string $type Either "json" or "xml"
2161 * @return string|array
2162 * @throws ForbiddenException
2163 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2165 function api_statuses_user_timeline($type)
2168 $user_info = api_get_user($a);
2170 if (api_user() === false || $user_info === false) {
2171 throw new ForbiddenException();
2175 "api_statuses_user_timeline: api_user: ". api_user() .
2176 "\nuser_info: ".print_r($user_info, true) .
2177 "\n_REQUEST: ".print_r($_REQUEST, true),
2181 $since_id = defaults($_REQUEST, 'since_id', 0);
2182 $max_id = defaults($_REQUEST, 'max_id', 0);
2183 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2184 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
2187 $count = defaults($_REQUEST, 'count', 20);
2188 $page = defaults($_REQUEST, 'page', 1);
2192 $start = ($page - 1) * $count;
2194 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2195 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2197 if ($user_info['self'] == 1) {
2198 $condition[0] .= ' AND `item`.`wall` ';
2201 if ($exclude_replies) {
2202 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2205 if ($conversation_id > 0) {
2206 $condition[0] .= " AND `item`.`parent` = ?";
2207 $condition[] = $conversation_id;
2211 $condition[0] .= " AND `item`.`id` <= ?";
2212 $condition[] = $max_id;
2215 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2216 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2218 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2222 $data = ['status' => $ret];
2227 $data = api_rss_extra($a, $data, $user_info);
2231 return api_format_data("statuses", $type, $data);
2234 /// @TODO move to top of file or somewhere better
2235 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2238 * Star/unstar an item.
2239 * param: id : id of the item
2241 * @param string $type Return type (atom, rss, xml, json)
2243 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2245 function api_favorites_create_destroy($type)
2249 if (api_user() === false) {
2250 throw new ForbiddenException();
2253 // for versioned api.
2254 /// @TODO We need a better global soluton
2255 $action_argv_id = 2;
2256 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2257 $action_argv_id = 3;
2260 if ($a->argc <= $action_argv_id) {
2261 throw new BadRequestException("Invalid request.");
2263 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2264 if ($a->argc == $action_argv_id + 2) {
2265 $itemid = intval(defaults($a->argv, $action_argv_id + 1, 0));
2267 $itemid = intval(defaults($_REQUEST, 'id', 0));
2270 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2272 if (!DBA::isResult($item)) {
2273 throw new BadRequestException("Invalid item.");
2278 $item['starred'] = 1;
2281 $item['starred'] = 0;
2284 throw new BadRequestException("Invalid action ".$action);
2287 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2290 throw new InternalServerErrorException("DB error");
2294 $user_info = api_get_user($a);
2295 $rets = api_format_items([$item], $user_info, false, $type);
2298 $data = ['status' => $ret];
2303 $data = api_rss_extra($a, $data, $user_info);
2307 return api_format_data("status", $type, $data);
2310 /// @TODO move to top of file or somewhere better
2311 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2312 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2315 * Returns the most recent favorite statuses.
2317 * @param string $type Return type (atom, rss, xml, json)
2319 * @return string|array
2321 function api_favorites($type)
2326 $user_info = api_get_user($a);
2328 if (api_user() === false || $user_info === false) {
2329 throw new ForbiddenException();
2334 // in friendica starred item are private
2335 // return favorites only for self
2336 Logger::info('API: {action}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2338 if ($user_info['self'] == 0) {
2342 $since_id = defaults($_REQUEST, 'since_id', 0);
2343 $max_id = defaults($_REQUEST, 'max_id', 0);
2344 $count = defaults($_GET, 'count', 20);
2345 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
2350 $start = $page*$count;
2352 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2353 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2355 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2358 $condition[0] .= " AND `item`.`id` <= ?";
2359 $condition[] = $max_id;
2362 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2364 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2369 $data = ['status' => $ret];
2374 $data = api_rss_extra($a, $data, $user_info);
2378 return api_format_data("statuses", $type, $data);
2381 /// @TODO move to top of file or somewhere better
2382 api_register_func('api/favorites', 'api_favorites', true);
2386 * @param array $item
2387 * @param array $recipient
2388 * @param array $sender
2392 function api_format_messages($item, $recipient, $sender)
2394 // standard meta information
2396 'id' => $item['id'],
2397 'sender_id' => $sender['id'],
2399 'recipient_id' => $recipient['id'],
2400 'created_at' => api_date(defaults($item, 'created', DateTimeFormat::utcNow())),
2401 'sender_screen_name' => $sender['screen_name'],
2402 'recipient_screen_name' => $recipient['screen_name'],
2403 'sender' => $sender,
2404 'recipient' => $recipient,
2406 'friendica_seen' => defaults($item, 'seen', 0),
2407 'friendica_parent_uri' => defaults($item, 'parent-uri', ''),
2410 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2411 if (isset($ret['sender']['uid'])) {
2412 unset($ret['sender']['uid']);
2414 if (isset($ret['sender']['self'])) {
2415 unset($ret['sender']['self']);
2417 if (isset($ret['recipient']['uid'])) {
2418 unset($ret['recipient']['uid']);
2420 if (isset($ret['recipient']['self'])) {
2421 unset($ret['recipient']['self']);
2424 //don't send title to regular StatusNET requests to avoid confusing these apps
2425 if (!empty($_GET['getText'])) {
2426 $ret['title'] = $item['title'];
2427 if ($_GET['getText'] == 'html') {
2428 $ret['text'] = BBCode::convert($item['body'], false);
2429 } elseif ($_GET['getText'] == 'plain') {
2430 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2433 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2435 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2436 unset($ret['sender']);
2437 unset($ret['recipient']);
2445 * @param array $item
2449 function api_convert_item($item)
2451 $body = $item['body'];
2452 $attachments = api_get_attachments($body);
2454 // Workaround for ostatus messages where the title is identically to the body
2455 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2456 $statusbody = trim(HTML::toPlaintext($html, 0));
2458 // handle data: images
2459 $statusbody = api_format_items_embeded_images($item, $statusbody);
2461 $statustitle = trim($item['title']);
2463 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2464 $statustext = trim($statusbody);
2466 $statustext = trim($statustitle."\n\n".$statusbody);
2469 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($statustext)> 1000)) {
2470 $statustext = substr($statustext, 0, 1000) . "... \n" . defaults($item, 'plink', '');
2473 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2475 // Workaround for clients with limited HTML parser functionality
2476 $search = ["<br>", "<blockquote>", "</blockquote>",
2477 "<h1>", "</h1>", "<h2>", "</h2>",
2478 "<h3>", "</h3>", "<h4>", "</h4>",
2479 "<h5>", "</h5>", "<h6>", "</h6>"];
2480 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2481 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2482 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2483 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2484 $statushtml = str_replace($search, $replace, $statushtml);
2486 if ($item['title'] != "") {
2487 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2491 $oldtext = $statushtml;
2492 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2493 } while ($oldtext != $statushtml);
2495 if (substr($statushtml, 0, 4) == '<br>') {
2496 $statushtml = substr($statushtml, 4);
2499 if (substr($statushtml, 0, -4) == '<br>') {
2500 $statushtml = substr($statushtml, -4);
2503 // feeds without body should contain the link
2504 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2505 $statushtml .= BBCode::convert($item['plink']);
2508 $entities = api_get_entitities($statustext, $body);
2511 "text" => $statustext,
2512 "html" => $statushtml,
2513 "attachments" => $attachments,
2514 "entities" => $entities
2520 * @param string $body
2524 function api_get_attachments(&$body)
2527 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2529 $URLSearchString = "^\[\]";
2530 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2538 foreach ($images[1] as $image) {
2539 $imagedata = Image::getInfoFromURL($image);
2542 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2546 if (strstr(defaults($_SERVER, 'HTTP_USER_AGENT', ''), "AndStatus")) {
2547 foreach ($images[0] as $orig) {
2548 $body = str_replace($orig, "", $body);
2552 return $attachments;
2557 * @param string $text
2558 * @param string $bbcode
2561 * @todo Links at the first character of the post
2563 function api_get_entitities(&$text, $bbcode)
2565 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
2567 if ($include_entities != "true") {
2568 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2570 foreach ($images[1] as $image) {
2571 $replace = ProxyUtils::proxifyUrl($image);
2572 $text = str_replace($image, $replace, $text);
2577 $bbcode = BBCode::cleanPictureLinks($bbcode);
2579 // Change pure links in text to bbcode uris
2580 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2583 $entities["hashtags"] = [];
2584 $entities["symbols"] = [];
2585 $entities["urls"] = [];
2586 $entities["user_mentions"] = [];
2588 $URLSearchString = "^\[\]";
2590 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2592 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2593 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2594 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2596 $bbcode = preg_replace(
2597 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2598 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2601 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2603 $bbcode = preg_replace(
2604 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2605 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2608 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2610 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2612 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2613 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2616 foreach ($urls[1] as $id => $url) {
2617 //$start = strpos($text, $url, $offset);
2618 $start = iconv_strpos($text, $url, 0, "UTF-8");
2619 if (!($start === false)) {
2620 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2624 ksort($ordered_urls);
2627 //foreach ($urls[1] AS $id=>$url) {
2628 foreach ($ordered_urls as $url) {
2629 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2630 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2632 $display_url = $url["title"];
2634 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2635 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2637 if (strlen($display_url) > 26) {
2638 $display_url = substr($display_url, 0, 25)."…";
2642 //$start = strpos($text, $url, $offset);
2643 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2644 if (!($start === false)) {
2645 $entities["urls"][] = ["url" => $url["url"],
2646 "expanded_url" => $url["url"],
2647 "display_url" => $display_url,
2648 "indices" => [$start, $start+strlen($url["url"])]];
2649 $offset = $start + 1;
2653 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2654 $ordered_images = [];
2655 foreach ($images[1] as $image) {
2656 //$start = strpos($text, $url, $offset);
2657 $start = iconv_strpos($text, $image, 0, "UTF-8");
2658 if (!($start === false)) {
2659 $ordered_images[$start] = $image;
2662 //$entities["media"] = array();
2665 foreach ($ordered_images as $url) {
2666 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2667 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2669 if (strlen($display_url) > 26) {
2670 $display_url = substr($display_url, 0, 25)."…";
2673 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2674 if (!($start === false)) {
2675 $image = Image::getInfoFromURL($url);
2677 // If image cache is activated, then use the following sizes:
2678 // thumb (150), small (340), medium (600) and large (1024)
2679 if (!Config::get("system", "proxy_disabled")) {
2680 $media_url = ProxyUtils::proxifyUrl($url);
2683 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2684 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2686 if (($image[0] > 150) || ($image[1] > 150)) {
2687 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2688 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2691 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2692 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2694 if (($image[0] > 600) || ($image[1] > 600)) {
2695 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2696 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2700 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2703 $entities["media"][] = [
2705 "id_str" => (string)$start+1,
2706 "indices" => [$start, $start+strlen($url)],
2707 "media_url" => Strings::normaliseLink($media_url),
2708 "media_url_https" => $media_url,
2710 "display_url" => $display_url,
2711 "expanded_url" => $url,
2715 $offset = $start + 1;
2724 * @param array $item
2725 * @param string $text
2729 function api_format_items_embeded_images($item, $text)
2731 $text = preg_replace_callback(
2732 '|data:image/([^;]+)[^=]+=*|m',
2733 function () use ($item) {
2734 return System::baseUrl() . '/display/' . $item['guid'];
2742 * @brief return <a href='url'>name</a> as array
2744 * @param string $txt text
2749 function api_contactlink_to_array($txt)
2752 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2753 if ($r && count($match)==3) {
2755 'name' => $match[2],
2769 * @brief return likes, dislikes and attend status for item
2771 * @param array $item array
2772 * @param string $type Return type (atom, rss, xml, json)
2775 * likes => int count,
2776 * dislikes => int count
2778 function api_format_items_activities($item, $type = "json")
2787 'attendmaybe' => [],
2790 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2791 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2793 while ($parent_item = Item::fetch($ret)) {
2794 // not used as result should be structured like other user data
2795 //builtin_activity_puller($i, $activities);
2797 // get user data and add it to the array of the activity
2798 $user = api_get_user($a, $parent_item['author-id']);
2799 switch ($parent_item['verb']) {
2801 $activities['like'][] = $user;
2803 case ACTIVITY_DISLIKE:
2804 $activities['dislike'][] = $user;
2806 case ACTIVITY_ATTEND:
2807 $activities['attendyes'][] = $user;
2809 case ACTIVITY_ATTENDNO:
2810 $activities['attendno'][] = $user;
2812 case ACTIVITY_ATTENDMAYBE:
2813 $activities['attendmaybe'][] = $user;
2822 if ($type == "xml") {
2823 $xml_activities = [];
2824 foreach ($activities as $k => $v) {
2825 // change xml element from "like" to "friendica:like"
2826 $xml_activities["friendica:".$k] = $v;
2827 // add user data into xml output
2829 foreach ($v as $user) {
2830 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2833 $activities = $xml_activities;
2841 * @brief return data from profiles
2843 * @param array $profile_row array containing data from db table 'profile'
2846 function api_format_items_profiles($profile_row)
2849 'profile_id' => $profile_row['id'],
2850 'profile_name' => $profile_row['profile-name'],
2851 'is_default' => $profile_row['is-default'] ? true : false,
2852 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2853 'profile_photo' => $profile_row['photo'],
2854 'profile_thumb' => $profile_row['thumb'],
2855 'publish' => $profile_row['publish'] ? true : false,
2856 'net_publish' => $profile_row['net-publish'] ? true : false,
2857 'description' => $profile_row['pdesc'],
2858 'date_of_birth' => $profile_row['dob'],
2859 'address' => $profile_row['address'],
2860 'city' => $profile_row['locality'],
2861 'region' => $profile_row['region'],
2862 'postal_code' => $profile_row['postal-code'],
2863 'country' => $profile_row['country-name'],
2864 'hometown' => $profile_row['hometown'],
2865 'gender' => $profile_row['gender'],
2866 'marital' => $profile_row['marital'],
2867 'marital_with' => $profile_row['with'],
2868 'marital_since' => $profile_row['howlong'],
2869 'sexual' => $profile_row['sexual'],
2870 'politic' => $profile_row['politic'],
2871 'religion' => $profile_row['religion'],
2872 'public_keywords' => $profile_row['pub_keywords'],
2873 'private_keywords' => $profile_row['prv_keywords'],
2874 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2875 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2876 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2877 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2878 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2879 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2880 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2881 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2882 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2883 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2884 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2885 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2886 'homepage' => $profile_row['homepage'],
2893 * @brief format items to be returned by api
2895 * @param array $r array of items
2896 * @param array $user_info
2897 * @param bool $filter_user filter items by $user_info
2898 * @param string $type Return type (atom, rss, xml, json)
2900 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2906 foreach ((array)$r as $item) {
2907 localize_item($item);
2908 list($status_user, $owner_user) = api_item_get_user($a, $item);
2910 // Look if the posts are matching if they should be filtered by user id
2911 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2915 $in_reply_to = api_in_reply_to($item);
2917 $converted = api_convert_item($item);
2919 if ($type == "xml") {
2920 $geo = "georss:point";
2926 'text' => $converted["text"],
2927 'truncated' => false,
2928 'created_at'=> api_date($item['created']),
2929 'in_reply_to_status_id' => $in_reply_to['status_id'],
2930 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2931 'source' => (($item['app']) ? $item['app'] : 'web'),
2932 'id' => intval($item['id']),
2933 'id_str' => (string) intval($item['id']),
2934 'in_reply_to_user_id' => $in_reply_to['user_id'],
2935 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2936 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2938 'favorited' => $item['starred'] ? true : false,
2939 'user' => $status_user,
2940 'friendica_owner' => $owner_user,
2941 'friendica_private' => $item['private'] == 1,
2942 //'entities' => NULL,
2943 'statusnet_html' => $converted["html"],
2944 'statusnet_conversation_id' => $item['parent'],
2945 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2946 'friendica_activities' => api_format_items_activities($item, $type),
2949 if (count($converted["attachments"]) > 0) {
2950 $status["attachments"] = $converted["attachments"];
2953 if (count($converted["entities"]) > 0) {
2954 $status["entities"] = $converted["entities"];
2957 if ($status["source"] == 'web') {
2958 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
2959 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
2960 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
2963 if ($item["id"] == $item["parent"]) {
2964 $retweeted_item = api_share_as_retweet($item);
2965 if ($retweeted_item !== false) {
2966 $retweeted_status = $status;
2967 $status['user'] = $status['friendica_owner'];
2969 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
2970 } catch (BadRequestException $e) {
2971 // user not found. should be found?
2972 /// @todo check if the user should be always found
2973 $retweeted_status["user"] = [];
2976 $rt_converted = api_convert_item($retweeted_item);
2978 $retweeted_status['text'] = $rt_converted["text"];
2979 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2980 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2981 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2982 $status['retweeted_status'] = $retweeted_status;
2986 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2987 unset($status["user"]["uid"]);
2988 unset($status["user"]["self"]);
2990 if ($item["coord"] != "") {
2991 $coords = explode(' ', $item["coord"]);
2992 if (count($coords) == 2) {
2993 if ($type == "json") {
2994 $status["geo"] = ['type' => 'Point',
2995 'coordinates' => [(float) $coords[0],
2996 (float) $coords[1]]];
2997 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2998 $status["georss:point"] = $item["coord"];
3008 * Returns the remaining number of API requests available to the user before the API limit is reached.
3010 * @param string $type Return type (atom, rss, xml, json)
3012 * @return array|string
3014 function api_account_rate_limit_status($type)
3016 if ($type == "xml") {
3018 'remaining-hits' => '150',
3019 '@attributes' => ["type" => "integer"],
3020 'hourly-limit' => '150',
3021 '@attributes2' => ["type" => "integer"],
3022 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3023 '@attributes3' => ["type" => "datetime"],
3024 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3025 '@attributes4' => ["type" => "integer"],
3029 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3030 'remaining_hits' => '150',
3031 'hourly_limit' => '150',
3032 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3036 return api_format_data('hash', $type, ['hash' => $hash]);
3039 /// @TODO move to top of file or somewhere better
3040 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3043 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3045 * @param string $type Return type (atom, rss, xml, json)
3047 * @return array|string
3049 function api_help_test($type)
3051 if ($type == 'xml') {
3057 return api_format_data('ok', $type, ["ok" => $ok]);
3060 /// @TODO move to top of file or somewhere better
3061 api_register_func('api/help/test', 'api_help_test', false);
3064 * Returns all lists the user subscribes to.
3066 * @param string $type Return type (atom, rss, xml, json)
3068 * @return array|string
3069 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3071 function api_lists_list($type)
3074 /// @TODO $ret is not filled here?
3075 return api_format_data('lists', $type, ["lists_list" => $ret]);
3078 /// @TODO move to top of file or somewhere better
3079 api_register_func('api/lists/list', 'api_lists_list', true);
3080 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3083 * Returns all groups the user owns.
3085 * @param string $type Return type (atom, rss, xml, json)
3087 * @return array|string
3088 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3090 function api_lists_ownerships($type)
3094 if (api_user() === false) {
3095 throw new ForbiddenException();
3099 $user_info = api_get_user($a);
3100 $uid = $user_info['uid'];
3102 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3104 // loop through all groups
3106 foreach ($groups as $group) {
3107 if ($group['visible']) {
3113 'name' => $group['name'],
3114 'id' => intval($group['id']),
3115 'id_str' => (string) $group['id'],
3116 'user' => $user_info,
3120 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3123 /// @TODO move to top of file or somewhere better
3124 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3127 * Returns recent statuses from users in the specified group.
3129 * @param string $type Return type (atom, rss, xml, json)
3131 * @return array|string
3132 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3134 function api_lists_statuses($type)
3138 $user_info = api_get_user($a);
3139 if (api_user() === false || $user_info === false) {
3140 throw new ForbiddenException();
3143 unset($_REQUEST["user_id"]);
3144 unset($_GET["user_id"]);
3146 unset($_REQUEST["screen_name"]);
3147 unset($_GET["screen_name"]);
3149 if (empty($_REQUEST['list_id'])) {
3150 throw new BadRequestException('list_id not specified');
3154 $count = defaults($_REQUEST, 'count', 20);
3155 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
3159 $since_id = defaults($_REQUEST, 'since_id', 0);
3160 $max_id = defaults($_REQUEST, 'max_id', 0);
3161 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3162 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
3164 $start = $page * $count;
3166 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3167 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3170 $condition[0] .= " AND `item`.`id` <= ?";
3171 $condition[] = $max_id;
3173 if ($exclude_replies > 0) {
3174 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3176 if ($conversation_id > 0) {
3177 $condition[0] .= " AND `item`.`parent` = ?";
3178 $condition[] = $conversation_id;
3181 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3182 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3184 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3186 $data = ['status' => $items];
3191 $data = api_rss_extra($a, $data, $user_info);
3195 return api_format_data("statuses", $type, $data);
3198 /// @TODO move to top of file or somewhere better
3199 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3202 * Considers friends and followers lists to be private and won't return
3203 * anything if any user_id parameter is passed.
3205 * @brief Returns either the friends of the follower list
3207 * @param string $qtype Either "friends" or "followers"
3208 * @return boolean|array
3209 * @throws ForbiddenException
3211 function api_statuses_f($qtype)
3215 if (api_user() === false) {
3216 throw new ForbiddenException();
3220 $count = defaults($_GET, 'count', 20);
3221 $page = defaults($_GET, 'page', 1);
3225 $start = ($page - 1) * $count;
3227 $user_info = api_get_user($a);
3229 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3230 /* this is to stop Hotot to load friends multiple times
3231 * I'm not sure if I'm missing return something or
3232 * is a bug in hotot. Workaround, meantime
3236 return array('$users' => $ret);*/
3241 if ($qtype == 'friends') {
3242 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3243 } elseif ($qtype == 'followers') {
3244 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3247 // friends and followers only for self
3248 if ($user_info['self'] == 0) {
3249 $sql_extra = " AND false ";
3252 if ($qtype == 'blocks') {
3253 $sql_filter = 'AND `blocked` AND NOT `pending`';
3254 } elseif ($qtype == 'incoming') {
3255 $sql_filter = 'AND `pending`';
3257 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3275 foreach ($r as $cid) {
3276 $user = api_get_user($a, $cid['nurl']);
3277 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3278 unset($user["uid"]);
3279 unset($user["self"]);
3286 return ['user' => $ret];
3291 * Returns the user's friends.
3293 * @brief Returns the list of friends of the provided user
3295 * @deprecated By Twitter API in favor of friends/list
3297 * @param string $type Either "json" or "xml"
3298 * @return boolean|string|array
3300 function api_statuses_friends($type)
3302 $data = api_statuses_f("friends");
3303 if ($data === false) {
3306 return api_format_data("users", $type, $data);
3310 * Returns the user's followers.
3312 * @brief Returns the list of followers of the provided user
3314 * @deprecated By Twitter API in favor of friends/list
3316 * @param string $type Either "json" or "xml"
3317 * @return boolean|string|array
3319 function api_statuses_followers($type)
3321 $data = api_statuses_f("followers");
3322 if ($data === false) {
3325 return api_format_data("users", $type, $data);
3328 /// @TODO move to top of file or somewhere better
3329 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3330 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3333 * Returns the list of blocked users
3335 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3337 * @param string $type Either "json" or "xml"
3339 * @return boolean|string|array
3341 function api_blocks_list($type)
3343 $data = api_statuses_f('blocks');
3344 if ($data === false) {
3347 return api_format_data("users", $type, $data);
3350 /// @TODO move to top of file or somewhere better
3351 api_register_func('api/blocks/list', 'api_blocks_list', true);
3354 * Returns the list of pending users IDs
3356 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3358 * @param string $type Either "json" or "xml"
3360 * @return boolean|string|array
3362 function api_friendships_incoming($type)
3364 $data = api_statuses_f('incoming');
3365 if ($data === false) {
3370 foreach ($data['user'] as $user) {
3371 $ids[] = $user['id'];
3374 return api_format_data("ids", $type, ['id' => $ids]);
3377 /// @TODO move to top of file or somewhere better
3378 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3381 * Returns the instance's configuration information.
3383 * @param string $type Return type (atom, rss, xml, json)
3385 * @return array|string
3387 function api_statusnet_config($type)
3391 $name = Config::get('config', 'sitename');
3392 $server = $a->getHostName();
3393 $logo = System::baseUrl() . '/images/friendica-64.png';
3394 $email = Config::get('config', 'admin_email');
3395 $closed = intval(Config::get('config', 'register_policy')) === REGISTER_CLOSED ? 'true' : 'false';
3396 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3397 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3398 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3399 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3402 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3403 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3404 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3405 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3406 'shorturllength' => '30',
3408 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3409 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3410 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3411 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3416 return api_format_data('config', $type, ['config' => $config]);
3419 /// @TODO move to top of file or somewhere better
3420 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3421 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3425 * @param string $type Return type (atom, rss, xml, json)
3427 * @return array|string
3429 function api_statusnet_version($type)
3432 $fake_statusnet_version = "0.9.7";
3434 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3437 /// @TODO move to top of file or somewhere better
3438 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3439 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3443 * @param string $type Return type (atom, rss, xml, json)
3445 * @todo use api_format_data() to return data
3447 function api_ff_ids($type)
3450 throw new ForbiddenException();
3457 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3460 "SELECT `pcontact`.`id` FROM `contact`
3461 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3462 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3465 if (!DBA::isResult($r)) {
3470 foreach ($r as $rr) {
3471 if ($stringify_ids) {
3474 $ids[] = intval($rr['id']);
3478 return api_format_data("ids", $type, ['id' => $ids]);
3482 * Returns the ID of every user the user is following.
3484 * @param string $type Return type (atom, rss, xml, json)
3486 * @return array|string
3487 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3489 function api_friends_ids($type)
3491 return api_ff_ids($type);
3495 * Returns the ID of every user following the user.
3497 * @param string $type Return type (atom, rss, xml, json)
3499 * @return array|string
3500 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3502 function api_followers_ids($type)
3504 return api_ff_ids($type);
3507 /// @TODO move to top of file or somewhere better
3508 api_register_func('api/friends/ids', 'api_friends_ids', true);
3509 api_register_func('api/followers/ids', 'api_followers_ids', true);
3512 * Sends a new direct message.
3514 * @param string $type Return type (atom, rss, xml, json)
3516 * @return array|string
3517 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3519 function api_direct_messages_new($type)
3523 if (api_user() === false) {
3524 throw new ForbiddenException();
3527 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3531 $sender = api_get_user($a);
3534 if (!empty($_POST['screen_name'])) {
3536 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3538 DBA::escape($_POST['screen_name'])
3541 if (DBA::isResult($r)) {
3542 // Selecting the id by priority, friendica first
3543 api_best_nickname($r);
3545 $recipient = api_get_user($a, $r[0]['nurl']);
3548 $recipient = api_get_user($a, $_POST['user_id']);
3551 if (empty($recipient)) {
3552 throw new NotFoundException('Recipient not found');
3557 if (!empty($_REQUEST['replyto'])) {
3559 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3561 intval($_REQUEST['replyto'])
3563 $replyto = $r[0]['parent-uri'];
3564 $sub = $r[0]['title'];
3566 if (!empty($_REQUEST['title'])) {
3567 $sub = $_REQUEST['title'];
3569 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3573 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3576 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3577 $ret = api_format_messages($r[0], $recipient, $sender);
3579 $ret = ["error"=>$id];
3582 $data = ['direct_message'=>$ret];
3588 $data = api_rss_extra($a, $data, $sender);
3592 return api_format_data("direct-messages", $type, $data);
3595 /// @TODO move to top of file or somewhere better
3596 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3599 * Destroys a direct message.
3601 * @brief delete a direct_message from mail table through api
3603 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3604 * @return string|array
3605 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3607 function api_direct_messages_destroy($type)
3611 if (api_user() === false) {
3612 throw new ForbiddenException();
3616 $user_info = api_get_user($a);
3618 $id = defaults($_REQUEST, 'id', 0);
3620 $parenturi = defaults($_REQUEST, 'friendica_parenturi', "");
3621 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3622 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3624 $uid = $user_info['uid'];
3625 // error if no id or parenturi specified (for clients posting parent-uri as well)
3626 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3627 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3628 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3631 // BadRequestException if no id specified (for clients using Twitter API)
3633 throw new BadRequestException('Message id not specified');
3636 // add parent-uri to sql command if specified by calling app
3637 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3639 // get data of the specified message id
3641 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3646 // error message if specified id is not in database
3647 if (!DBA::isResult($r)) {
3648 if ($verbose == "true") {
3649 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3650 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3652 /// @todo BadRequestException ok for Twitter API clients?
3653 throw new BadRequestException('message id not in database');
3658 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3663 if ($verbose == "true") {
3666 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3667 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3669 $answer = ['result' => 'error', 'message' => 'unknown error'];
3670 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3673 /// @todo return JSON data like Twitter API not yet implemented
3676 /// @TODO move to top of file or somewhere better
3677 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3682 * @brief unfollow contact
3684 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3685 * @return string|array
3686 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3688 function api_friendships_destroy($type)
3693 if ($uid === false) {
3694 throw new ForbiddenException();
3697 $contact_id = defaults($_REQUEST, 'user_id');
3699 if (empty($contact_id)) {
3700 Logger::notice('API {action} - No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3701 throw new BadRequestException("no user_id specified");
3704 // Get Contact by given id
3705 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3707 if(!DBA::isResult($contact)) {
3708 Logger::notice('API {action} - No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3709 throw new NotFoundException("no contact found to given ID");
3712 $url = $contact["url"];
3714 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3715 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3716 Strings::normaliseLink($url), $url];
3717 $contact = DBA::selectFirst('contact', [], $condition);
3719 if (!DBA::isResult($contact)) {
3720 Logger::notice('API {action} - Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3721 throw new NotFoundException("Not following Contact");
3724 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3725 Logger::notice('API {action} - Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3726 throw new ExpectationFailedException("Not supported");
3729 $dissolve = ($contact['rel'] == Contact::SHARING);
3731 $owner = User::getOwnerDataById($uid);
3733 Contact::terminateFriendship($owner, $contact, $dissolve);
3736 Logger::notice('API {action} - No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3737 throw new NotFoundException("Error Processing Request");
3740 // Sharing-only contacts get deleted as there no relationship any more
3742 Contact::remove($contact['id']);
3744 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3747 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3748 unset($contact["uid"]);
3749 unset($contact["self"]);
3751 // Set screen_name since Twidere requests it
3752 $contact["screen_name"] = $contact["nick"];
3754 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3756 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3760 * @param string $type Return type (atom, rss, xml, json)
3761 * @param string $box
3762 * @param string $verbose
3764 * @return array|string
3766 function api_direct_messages_box($type, $box, $verbose)
3769 if (api_user() === false) {
3770 throw new ForbiddenException();
3773 $count = defaults($_GET, 'count', 20);
3774 $page = defaults($_REQUEST, 'page', 1) - 1;
3779 $since_id = defaults($_REQUEST, 'since_id', 0);
3780 $max_id = defaults($_REQUEST, 'max_id', 0);
3782 $user_id = defaults($_REQUEST, 'user_id', '');
3783 $screen_name = defaults($_REQUEST, 'screen_name', '');
3786 unset($_REQUEST["user_id"]);
3787 unset($_GET["user_id"]);
3789 unset($_REQUEST["screen_name"]);
3790 unset($_GET["screen_name"]);
3792 $user_info = api_get_user($a);
3793 if ($user_info === false) {
3794 throw new ForbiddenException();
3796 $profile_url = $user_info["url"];
3799 $start = $page * $count;
3804 if ($box=="sentbox") {
3805 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3806 } elseif ($box == "conversation") {
3807 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape(defaults($_GET, 'uri', '')) . "'";
3808 } elseif ($box == "all") {
3809 $sql_extra = "true";
3810 } elseif ($box == "inbox") {
3811 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3815 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3818 if ($user_id != "") {
3819 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3820 } elseif ($screen_name !="") {
3821 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3825 "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",
3831 if ($verbose == "true" && !DBA::isResult($r)) {
3832 $answer = ['result' => 'error', 'message' => 'no mails available'];
3833 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3837 foreach ($r as $item) {
3838 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3839 $recipient = $user_info;
3840 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3841 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3842 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3843 $sender = $user_info;
3846 if (isset($recipient) && isset($sender)) {
3847 $ret[] = api_format_messages($item, $recipient, $sender);
3852 $data = ['direct_message' => $ret];
3857 $data = api_rss_extra($a, $data, $user_info);
3861 return api_format_data("direct-messages", $type, $data);
3865 * Returns the most recent direct messages sent by the user.
3867 * @param string $type Return type (atom, rss, xml, json)
3869 * @return array|string
3870 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3872 function api_direct_messages_sentbox($type)
3874 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3875 return api_direct_messages_box($type, "sentbox", $verbose);
3879 * Returns the most recent direct messages sent to the user.
3881 * @param string $type Return type (atom, rss, xml, json)
3883 * @return array|string
3884 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3886 function api_direct_messages_inbox($type)
3888 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3889 return api_direct_messages_box($type, "inbox", $verbose);
3894 * @param string $type Return type (atom, rss, xml, json)
3896 * @return array|string
3898 function api_direct_messages_all($type)
3900 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3901 return api_direct_messages_box($type, "all", $verbose);
3906 * @param string $type Return type (atom, rss, xml, json)
3908 * @return array|string
3910 function api_direct_messages_conversation($type)
3912 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3913 return api_direct_messages_box($type, "conversation", $verbose);
3916 /// @TODO move to top of file or somewhere better
3917 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3918 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3919 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3920 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3923 * Returns an OAuth Request Token.
3925 * @see https://oauth.net/core/1.0/#auth_step1
3927 function api_oauth_request_token()
3929 $oauth1 = new FKOAuth1();
3931 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3932 } catch (Exception $e) {
3933 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3941 * Returns an OAuth Access Token.
3943 * @return array|string
3944 * @see https://oauth.net/core/1.0/#auth_step3
3946 function api_oauth_access_token()
3948 $oauth1 = new FKOAuth1();
3950 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3951 } catch (Exception $e) {
3952 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3959 /// @TODO move to top of file or somewhere better
3960 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3961 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3965 * @brief delete a complete photoalbum with all containing photos from database through api
3967 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3968 * @return string|array
3970 function api_fr_photoalbum_delete($type)
3972 if (api_user() === false) {
3973 throw new ForbiddenException();
3976 $album = defaults($_REQUEST, 'album', "");
3978 // we do not allow calls without album string
3980 throw new BadRequestException("no albumname specified");
3982 // check if album is existing
3984 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3988 if (!DBA::isResult($r)) {
3989 throw new BadRequestException("album not available");
3992 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3993 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3994 foreach ($r as $rr) {
3995 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
3996 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
3998 if (!DBA::isResult($photo_item)) {
3999 throw new InternalServerErrorException("problem with deleting items occured");
4001 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4004 // now let's delete all photos from the album
4005 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4007 // return success of deletion or error message
4009 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4010 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4012 throw new InternalServerErrorException("unknown error - deleting from database failed");
4017 * @brief update the name of the album for all photos of an album
4019 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4020 * @return string|array
4022 function api_fr_photoalbum_update($type)
4024 if (api_user() === false) {
4025 throw new ForbiddenException();
4028 $album = defaults($_REQUEST, 'album', "");
4029 $album_new = defaults($_REQUEST, 'album_new', "");
4031 // we do not allow calls without album string
4033 throw new BadRequestException("no albumname specified");
4035 if ($album_new == "") {
4036 throw new BadRequestException("no new albumname specified");
4038 // check if album is existing
4039 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4040 throw new BadRequestException("album not available");
4042 // now let's update all photos to the albumname
4043 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4045 // return success of updating or error message
4047 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4048 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4050 throw new InternalServerErrorException("unknown error - updating in database failed");
4056 * @brief list all photos of the authenticated user
4058 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4059 * @return string|array
4061 function api_fr_photos_list($type)
4063 if (api_user() === false) {
4064 throw new ForbiddenException();
4067 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4068 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4069 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4070 intval(local_user())
4073 'image/jpeg' => 'jpg',
4074 'image/png' => 'png',
4075 'image/gif' => 'gif'
4077 $data = ['photo'=>[]];
4078 if (DBA::isResult($r)) {
4079 foreach ($r as $rr) {
4081 $photo['id'] = $rr['resource-id'];
4082 $photo['album'] = $rr['album'];
4083 $photo['filename'] = $rr['filename'];
4084 $photo['type'] = $rr['type'];
4085 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4086 $photo['created'] = $rr['created'];
4087 $photo['edited'] = $rr['edited'];
4088 $photo['desc'] = $rr['desc'];
4090 if ($type == "xml") {
4091 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4093 $photo['thumb'] = $thumb;
4094 $data['photo'][] = $photo;
4098 return api_format_data("photos", $type, $data);
4102 * @brief upload a new photo or change an existing photo
4104 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4105 * @return string|array
4107 function api_fr_photo_create_update($type)
4109 if (api_user() === false) {
4110 throw new ForbiddenException();
4113 $photo_id = defaults($_REQUEST, 'photo_id', null);
4114 $desc = defaults($_REQUEST, 'desc', (array_key_exists('desc', $_REQUEST) ? "" : null)) ; // extra check necessary to distinguish between 'not provided' and 'empty string'
4115 $album = defaults($_REQUEST, 'album', null);
4116 $album_new = defaults($_REQUEST, 'album_new', null);
4117 $allow_cid = defaults($_REQUEST, 'allow_cid', (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4118 $deny_cid = defaults($_REQUEST, 'deny_cid' , (array_key_exists('deny_cid' , $_REQUEST) ? " " : null));
4119 $allow_gid = defaults($_REQUEST, 'allow_gid', (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4120 $deny_gid = defaults($_REQUEST, 'deny_gid' , (array_key_exists('deny_gid' , $_REQUEST) ? " " : null));
4121 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4123 // do several checks on input parameters
4124 // we do not allow calls without album string
4125 if ($album == null) {
4126 throw new BadRequestException("no albumname specified");
4128 // if photo_id == null --> we are uploading a new photo
4129 if ($photo_id == null) {
4132 // error if no media posted in create-mode
4133 if (empty($_FILES['media'])) {
4135 throw new BadRequestException("no media data submitted");
4138 // album_new will be ignored in create-mode
4143 // check if photo is existing in databasei
4144 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4145 throw new BadRequestException("photo not available");
4149 // checks on acl strings provided by clients
4150 $acl_input_error = false;
4151 $acl_input_error |= check_acl_input($allow_cid);
4152 $acl_input_error |= check_acl_input($deny_cid);
4153 $acl_input_error |= check_acl_input($allow_gid);
4154 $acl_input_error |= check_acl_input($deny_gid);
4155 if ($acl_input_error) {
4156 throw new BadRequestException("acl data invalid");
4158 // now let's upload the new media in create-mode
4159 if ($mode == "create") {
4160 $media = $_FILES['media'];
4161 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4163 // return success of updating or error message
4164 if (!is_null($data)) {
4165 return api_format_data("photo_create", $type, $data);
4167 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4171 // now let's do the changes in update-mode
4172 if ($mode == "update") {
4173 $updated_fields = [];
4175 if (!is_null($desc)) {
4176 $updated_fields['desc'] = $desc;
4179 if (!is_null($album_new)) {
4180 $updated_fields['album'] = $album_new;
4183 if (!is_null($allow_cid)) {
4184 $allow_cid = trim($allow_cid);
4185 $updated_fields['allow_cid'] = $allow_cid;
4188 if (!is_null($deny_cid)) {
4189 $deny_cid = trim($deny_cid);
4190 $updated_fields['deny_cid'] = $deny_cid;
4193 if (!is_null($allow_gid)) {
4194 $allow_gid = trim($allow_gid);
4195 $updated_fields['allow_gid'] = $allow_gid;
4198 if (!is_null($deny_gid)) {
4199 $deny_gid = trim($deny_gid);
4200 $updated_fields['deny_gid'] = $deny_gid;
4204 if (count($updated_fields) > 0) {
4205 $nothingtodo = false;
4206 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4208 $nothingtodo = true;
4211 if (!empty($_FILES['media'])) {
4212 $nothingtodo = false;
4213 $media = $_FILES['media'];
4214 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4215 if (!is_null($data)) {
4216 return api_format_data("photo_update", $type, $data);
4220 // return success of updating or error message
4222 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4223 return api_format_data("photo_update", $type, ['$result' => $answer]);
4226 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4227 return api_format_data("photo_update", $type, ['$result' => $answer]);
4229 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4232 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4236 * @brief delete a single photo from the database through api
4238 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4239 * @return string|array
4241 function api_fr_photo_delete($type)
4243 if (api_user() === false) {
4244 throw new ForbiddenException();
4247 $photo_id = defaults($_REQUEST, 'photo_id', null);
4249 // do several checks on input parameters
4250 // we do not allow calls without photo id
4251 if ($photo_id == null) {
4252 throw new BadRequestException("no photo_id specified");
4254 // check if photo is existing in database
4255 $r = Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()]);
4257 throw new BadRequestException("photo not available");
4259 // now we can perform on the deletion of the photo
4260 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4262 // return success of deletion or error message
4264 // retrieve the id of the parent element (the photo element)
4265 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4266 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4268 if (!DBA::isResult($photo_item)) {
4269 throw new InternalServerErrorException("problem with deleting items occured");
4271 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4272 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4273 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4275 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4276 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4278 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4284 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4286 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4287 * @return string|array
4289 function api_fr_photo_detail($type)
4291 if (api_user() === false) {
4292 throw new ForbiddenException();
4294 if (empty($_REQUEST['photo_id'])) {
4295 throw new BadRequestException("No photo id.");
4298 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4299 $photo_id = $_REQUEST['photo_id'];
4301 // prepare json/xml output with data from database for the requested photo
4302 $data = prepare_photo_data($type, $scale, $photo_id);
4304 return api_format_data("photo_detail", $type, $data);
4309 * Updates the user’s profile image.
4311 * @brief updates the profile image for the user (either a specified profile or the default profile)
4313 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4315 * @return string|array
4316 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4318 function api_account_update_profile_image($type)
4320 if (api_user() === false) {
4321 throw new ForbiddenException();
4324 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4326 // error if image data is missing
4327 if (empty($_FILES['image'])) {
4328 throw new BadRequestException("no media data submitted");
4331 // check if specified profile id is valid
4332 if ($profile_id != 0) {
4333 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4334 // error message if specified profile id is not in database
4335 if (!DBA::isResult($profile)) {
4336 throw new BadRequestException("profile_id not available");
4338 $is_default_profile = $profile['is-default'];
4340 $is_default_profile = 1;
4343 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4345 if (!empty($_FILES['image'])) {
4346 $media = $_FILES['image'];
4347 } elseif (!empty($_FILES['media'])) {
4348 $media = $_FILES['media'];
4350 // save new profile image
4351 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4354 if (is_array($media['type'])) {
4355 $filetype = $media['type'][0];
4357 $filetype = $media['type'];
4359 if ($filetype == "image/jpeg") {
4361 } elseif ($filetype == "image/png") {
4364 throw new InternalServerErrorException('Unsupported filetype');
4367 // change specified profile or all profiles to the new resource-id
4368 if ($is_default_profile) {
4369 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4370 Photo::update(['profile' => false], $condition);
4372 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype,
4373 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype];
4374 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4377 Contact::updateSelfFromUserID(api_user(), true);
4379 // Update global directory in background
4380 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4381 if ($url && strlen(Config::get('system', 'directory'))) {
4382 Worker::add(PRIORITY_LOW, "Directory", $url);
4385 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4387 // output for client
4389 return api_account_verify_credentials($type);
4391 // SaveMediaToDatabase failed for some reason
4392 throw new InternalServerErrorException("image upload failed");
4396 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4397 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4398 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4399 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4400 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4401 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4402 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4403 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4404 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4407 * Update user profile
4409 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4411 * @return array|string
4413 function api_account_update_profile($type)
4415 $local_user = api_user();
4416 $api_user = api_get_user(get_app());
4418 if (!empty($_POST['name'])) {
4419 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4420 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4421 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4422 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4425 if (isset($_POST['description'])) {
4426 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4427 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4428 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4431 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4432 // Update global directory in background
4433 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4434 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4437 return api_account_verify_credentials($type);
4440 /// @TODO move to top of file or somewhere better
4441 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4445 * @param string $acl_string
4447 function check_acl_input($acl_string)
4449 if ($acl_string == null || $acl_string == " ") {
4452 $contact_not_found = false;
4454 // split <x><y><z> into array of cid's
4455 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4457 // check for each cid if it is available on server
4458 $cid_array = $array[0];
4459 foreach ($cid_array as $cid) {
4460 $cid = str_replace("<", "", $cid);
4461 $cid = str_replace(">", "", $cid);
4462 $condition = ['id' => $cid, 'uid' => api_user()];
4463 $contact_not_found |= !DBA::exists('contact', $condition);
4465 return $contact_not_found;
4470 * @param string $mediatype
4471 * @param array $media
4472 * @param string $type
4473 * @param string $album
4474 * @param string $allow_cid
4475 * @param string $deny_cid
4476 * @param string $allow_gid
4477 * @param string $deny_gid
4478 * @param string $desc
4479 * @param integer $profile
4480 * @param boolean $visibility
4481 * @param string $photo_id
4483 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)
4491 if (is_array($media)) {
4492 if (is_array($media['tmp_name'])) {
4493 $src = $media['tmp_name'][0];
4495 $src = $media['tmp_name'];
4497 if (is_array($media['name'])) {
4498 $filename = basename($media['name'][0]);
4500 $filename = basename($media['name']);
4502 if (is_array($media['size'])) {
4503 $filesize = intval($media['size'][0]);
4505 $filesize = intval($media['size']);
4507 if (is_array($media['type'])) {
4508 $filetype = $media['type'][0];
4510 $filetype = $media['type'];
4514 if ($filetype == "") {
4515 $filetype=Image::guessType($filename);
4517 $imagedata = @getimagesize($src);
4519 $filetype = $imagedata['mime'];
4522 "File upload src: " . $src . " - filename: " . $filename .
4523 " - size: " . $filesize . " - type: " . $filetype,
4527 // check if there was a php upload error
4528 if ($filesize == 0 && $media['error'] == 1) {
4529 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4531 // check against max upload size within Friendica instance
4532 $maximagesize = Config::get('system', 'maximagesize');
4533 if ($maximagesize && ($filesize > $maximagesize)) {
4534 $formattedBytes = Strings::formatBytes($maximagesize);
4535 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4538 // create Photo instance with the data of the image
4539 $imagedata = @file_get_contents($src);
4540 $Image = new Image($imagedata, $filetype);
4541 if (!$Image->isValid()) {
4542 throw new InternalServerErrorException("unable to process image data");
4545 // check orientation of image
4546 $Image->orient($src);
4549 // check max length of images on server
4550 $max_length = Config::get('system', 'max_image_length');
4552 $max_length = MAX_IMAGE_LENGTH;
4554 if ($max_length > 0) {
4555 $Image->scaleDown($max_length);
4556 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4558 $width = $Image->getWidth();
4559 $height = $Image->getHeight();
4561 // create a new resource-id if not already provided
4562 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4564 if ($mediatype == "photo") {
4565 // upload normal image (scales 0, 1, 2)
4566 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4568 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4570 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4572 if ($width > 640 || $height > 640) {
4573 $Image->scaleDown(640);
4574 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4576 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4580 if ($width > 320 || $height > 320) {
4581 $Image->scaleDown(320);
4582 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4584 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4587 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4588 } elseif ($mediatype == "profileimage") {
4589 // upload profile image (scales 4, 5, 6)
4590 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4592 if ($width > 300 || $height > 300) {
4593 $Image->scaleDown(300);
4594 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4596 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4600 if ($width > 80 || $height > 80) {
4601 $Image->scaleDown(80);
4602 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4604 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4608 if ($width > 48 || $height > 48) {
4609 $Image->scaleDown(48);
4610 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4612 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4615 $Image->__destruct();
4616 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4619 if (isset($r) && $r) {
4620 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4621 if ($photo_id == null && $mediatype == "photo") {
4622 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4624 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4625 return prepare_photo_data($type, false, $hash);
4627 throw new InternalServerErrorException("image upload failed");
4633 * @param string $hash
4634 * @param string $allow_cid
4635 * @param string $deny_cid
4636 * @param string $allow_gid
4637 * @param string $deny_gid
4638 * @param string $filetype
4639 * @param boolean $visibility
4641 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4643 // get data about the api authenticated user
4644 $uri = Item::newURI(intval(api_user()));
4645 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4648 $arr['guid'] = System::createUUID();
4649 $arr['uid'] = intval(api_user());
4651 $arr['parent-uri'] = $uri;
4652 $arr['type'] = 'photo';
4654 $arr['resource-id'] = $hash;
4655 $arr['contact-id'] = $owner_record['id'];
4656 $arr['owner-name'] = $owner_record['name'];
4657 $arr['owner-link'] = $owner_record['url'];
4658 $arr['owner-avatar'] = $owner_record['thumb'];
4659 $arr['author-name'] = $owner_record['name'];
4660 $arr['author-link'] = $owner_record['url'];
4661 $arr['author-avatar'] = $owner_record['thumb'];
4663 $arr['allow_cid'] = $allow_cid;
4664 $arr['allow_gid'] = $allow_gid;
4665 $arr['deny_cid'] = $deny_cid;
4666 $arr['deny_gid'] = $deny_gid;
4667 $arr['visible'] = $visibility;
4671 'image/jpeg' => 'jpg',
4672 'image/png' => 'png',
4673 'image/gif' => 'gif'
4676 // adds link to the thumbnail scale photo
4677 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4678 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4681 // do the magic for storing the item in the database and trigger the federation to other contacts
4687 * @param string $type
4689 * @param string $photo_id
4693 function prepare_photo_data($type, $scale, $photo_id)
4696 $user_info = api_get_user($a);
4698 if ($user_info === false) {
4699 throw new ForbiddenException();
4702 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4703 $data_sql = ($scale === false ? "" : "data, ");
4705 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4706 // clients needs to convert this in their way for further processing
4708 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4709 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4710 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4711 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4713 intval(local_user()),
4714 DBA::escape($photo_id),
4719 'image/jpeg' => 'jpg',
4720 'image/png' => 'png',
4721 'image/gif' => 'gif'
4724 // prepare output data for photo
4725 if (DBA::isResult($r)) {
4726 $data = ['photo' => $r[0]];
4727 $data['photo']['id'] = $data['photo']['resource-id'];
4728 if ($scale !== false) {
4729 $data['photo']['data'] = base64_encode($data['photo']['data']);
4731 unset($data['photo']['datasize']); //needed only with scale param
4733 if ($type == "xml") {
4734 $data['photo']['links'] = [];
4735 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4736 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4738 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4741 $data['photo']['link'] = [];
4742 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4744 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4745 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4749 unset($data['photo']['resource-id']);
4750 unset($data['photo']['minscale']);
4751 unset($data['photo']['maxscale']);
4753 throw new NotFoundException();
4756 // retrieve item element for getting activities (like, dislike etc.) related to photo
4757 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4758 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4760 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4762 // retrieve comments on photo
4763 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4764 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4766 $statuses = Item::selectForUser(api_user(), [], $condition);
4768 // prepare output of comments
4769 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
4771 if ($type == "xml") {
4773 foreach ($commentData as $comment) {
4774 $comments[$k++ . ":comment"] = $comment;
4777 foreach ($commentData as $comment) {
4778 $comments[] = $comment;
4781 $data['photo']['friendica_comments'] = $comments;
4783 // include info if rights on photo and rights on item are mismatching
4784 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4785 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4786 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4787 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4788 $data['photo']['rights_mismatch'] = $rights_mismatch;
4795 * Similar as /mod/redir.php
4796 * redirect to 'url' after dfrn auth
4798 * Why this when there is mod/redir.php already?
4799 * This use api_user() and api_login()
4802 * c_url: url of remote contact to auth to
4803 * url: string, url to redirect after auth
4805 function api_friendica_remoteauth()
4807 $url = defaults($_GET, 'url', '');
4808 $c_url = defaults($_GET, 'c_url', '');
4810 if ($url === '' || $c_url === '') {
4811 throw new BadRequestException("Wrong parameters.");
4814 $c_url = Strings::normaliseLink($c_url);
4818 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4820 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
4821 throw new BadRequestException("Unknown contact");
4824 $cid = $contact['id'];
4826 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4828 if ($contact['duplex'] && $contact['issued-id']) {
4829 $orig_id = $contact['issued-id'];
4830 $dfrn_id = '1:' . $orig_id;
4832 if ($contact['duplex'] && $contact['dfrn-id']) {
4833 $orig_id = $contact['dfrn-id'];
4834 $dfrn_id = '0:' . $orig_id;
4837 $sec = Strings::getRandomHex();
4839 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4840 'sec' => $sec, 'expire' => time() + 45];
4841 DBA::insert('profile_check', $fields);
4844 Logger::info('API: {action}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
4845 $dest = ($url ? '&destination_url=' . $url : '');
4847 System::externalRedirect(
4848 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4849 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4850 . '&type=profile&sec=' . $sec . $dest
4853 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4856 * @brief Return the item shared, if the item contains only the [share] tag
4858 * @param array $item Sharer item
4859 * @return array|false Shared item or false if not a reshare
4861 function api_share_as_retweet(&$item)
4863 $body = trim($item["body"]);
4865 if (Diaspora::isReshare($body, false) === false) {
4866 if ($item['author-id'] == $item['owner-id']) {
4869 // Reshares from OStatus, ActivityPub and Twitter
4870 $reshared_item = $item;
4871 $reshared_item['owner-id'] = $reshared_item['author-id'];
4872 $reshared_item['owner-link'] = $reshared_item['author-link'];
4873 $reshared_item['owner-name'] = $reshared_item['author-name'];
4874 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
4875 return $reshared_item;
4879 /// @TODO "$1" should maybe mean '$1' ?
4880 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4882 * Skip if there is no shared message in there
4883 * we already checked this in diaspora::isReshare()
4884 * but better one more than one less...
4886 if (($body == $attributes) || empty($attributes)) {
4890 // build the fake reshared item
4891 $reshared_item = $item;
4894 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4895 if (!empty($matches[1])) {
4896 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4899 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4900 if (!empty($matches[1])) {
4901 $author = $matches[1];
4905 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4906 if (!empty($matches[1])) {
4907 $profile = $matches[1];
4910 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4911 if (!empty($matches[1])) {
4912 $profile = $matches[1];
4916 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4917 if (!empty($matches[1])) {
4918 $avatar = $matches[1];
4921 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4922 if (!empty($matches[1])) {
4923 $avatar = $matches[1];
4927 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4928 if (!empty($matches[1])) {
4929 $link = $matches[1];
4932 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4933 if (!empty($matches[1])) {
4934 $link = $matches[1];
4938 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4939 if (!empty($matches[1])) {
4940 $posted = $matches[1];
4943 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4944 if (!empty($matches[1])) {
4945 $posted = $matches[1];
4948 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4950 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4954 $reshared_item["body"] = $shared_body;
4955 $reshared_item["author-id"] = Contact::getIdForURL($profile, 0, true);
4956 $reshared_item["author-name"] = $author;
4957 $reshared_item["author-link"] = $profile;
4958 $reshared_item["author-avatar"] = $avatar;
4959 $reshared_item["plink"] = $link;
4960 $reshared_item["created"] = $posted;
4961 $reshared_item["edited"] = $posted;
4963 return $reshared_item;
4968 * @param string $profile
4970 * @return string|false
4971 * @todo remove trailing junk from profile url
4972 * @todo pump.io check has to check the website
4974 function api_get_nick($profile)
4979 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4980 DBA::escape(Strings::normaliseLink($profile))
4983 if (DBA::isResult($r)) {
4984 $nick = $r[0]["nick"];
4989 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4990 DBA::escape(Strings::normaliseLink($profile))
4993 if (DBA::isResult($r)) {
4994 $nick = $r[0]["nick"];
4999 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5000 if ($friendica != $profile) {
5006 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5007 if ($diaspora != $profile) {
5013 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5014 if ($twitter != $profile) {
5021 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5022 if ($StatusnetHost != $profile) {
5023 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5024 if ($StatusnetUser != $profile) {
5025 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5026 $user = json_decode($UserData);
5028 $nick = $user->screen_name;
5034 // To-Do: look at the page if its really a pumpio site
5035 //if (!$nick == "") {
5036 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5037 // if ($pumpio != $profile)
5039 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5052 * @param array $item
5056 function api_in_reply_to($item)
5060 $in_reply_to['status_id'] = null;
5061 $in_reply_to['user_id'] = null;
5062 $in_reply_to['status_id_str'] = null;
5063 $in_reply_to['user_id_str'] = null;
5064 $in_reply_to['screen_name'] = null;
5066 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5067 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5068 if (DBA::isResult($parent)) {
5069 $in_reply_to['status_id'] = intval($parent['id']);
5071 $in_reply_to['status_id'] = intval($item['parent']);
5074 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5076 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5077 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5079 if (DBA::isResult($parent)) {
5080 if ($parent['author-nick'] == "") {
5081 $parent['author-nick'] = api_get_nick($parent['author-link']);
5084 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5085 $in_reply_to['user_id'] = intval($parent['author-id']);
5086 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5089 // There seems to be situation, where both fields are identical:
5090 // https://github.com/friendica/friendica/issues/1010
5091 // This is a bugfix for that.
5092 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5094 Logger::warning('API {action}: ID {id} is similar to reply-to {reply-to}', ['module' => 'api', 'action' => 'in_reply_to', 'id' => $item['id'], 'reply-to' => $in_reply_to['status_id']]);
5095 $in_reply_to['status_id'] = null;
5096 $in_reply_to['user_id'] = null;
5097 $in_reply_to['status_id_str'] = null;
5098 $in_reply_to['user_id_str'] = null;
5099 $in_reply_to['screen_name'] = null;
5103 return $in_reply_to;
5108 * @param string $text
5112 function api_clean_plain_items($text)
5114 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
5116 $text = BBCode::cleanPictureLinks($text);
5117 $URLSearchString = "^\[\]";
5119 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5121 if ($include_entities == "true") {
5122 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5125 // Simplify "attachment" element
5126 $text = api_clean_attachments($text);
5132 * @brief Removes most sharing information for API text export
5134 * @param string $body The original body
5136 * @return string Cleaned body
5138 function api_clean_attachments($body)
5140 $data = BBCode::getAttachmentData($body);
5147 if (isset($data["text"])) {
5148 $body = $data["text"];
5150 if (($body == "") && isset($data["title"])) {
5151 $body = $data["title"];
5153 if (isset($data["url"])) {
5154 $body .= "\n".$data["url"];
5156 $body .= $data["after"];
5163 * @param array $contacts
5167 function api_best_nickname(&$contacts)
5171 if (count($contacts) == 0) {
5175 foreach ($contacts as $contact) {
5176 if ($contact["network"] == "") {
5177 $contact["network"] = "dfrn";
5178 $best_contact = [$contact];
5182 if (sizeof($best_contact) == 0) {
5183 foreach ($contacts as $contact) {
5184 if ($contact["network"] == "dfrn") {
5185 $best_contact = [$contact];
5190 if (sizeof($best_contact) == 0) {
5191 foreach ($contacts as $contact) {
5192 if ($contact["network"] == "dspr") {
5193 $best_contact = [$contact];
5198 if (sizeof($best_contact) == 0) {
5199 foreach ($contacts as $contact) {
5200 if ($contact["network"] == "stat") {
5201 $best_contact = [$contact];
5206 if (sizeof($best_contact) == 0) {
5207 foreach ($contacts as $contact) {
5208 if ($contact["network"] == "pump") {
5209 $best_contact = [$contact];
5214 if (sizeof($best_contact) == 0) {
5215 foreach ($contacts as $contact) {
5216 if ($contact["network"] == "twit") {
5217 $best_contact = [$contact];
5222 if (sizeof($best_contact) == 1) {
5223 $contacts = $best_contact;
5225 $contacts = [$contacts[0]];
5230 * Return all or a specified group of the user with the containing contacts.
5232 * @param string $type Return type (atom, rss, xml, json)
5234 * @return array|string
5236 function api_friendica_group_show($type)
5240 if (api_user() === false) {
5241 throw new ForbiddenException();
5245 $user_info = api_get_user($a);
5246 $gid = defaults($_REQUEST, 'gid', 0);
5247 $uid = $user_info['uid'];
5249 // get data of the specified group id or all groups if not specified
5252 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5256 // error message if specified gid is not in database
5257 if (!DBA::isResult($r)) {
5258 throw new BadRequestException("gid not available");
5262 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5267 // loop through all groups and retrieve all members for adding data in the user array
5269 foreach ($r as $rr) {
5270 $members = Contact::getByGroupId($rr['id']);
5273 if ($type == "xml") {
5274 $user_element = "users";
5276 foreach ($members as $member) {
5277 $user = api_get_user($a, $member['nurl']);
5278 $users[$k++.":user"] = $user;
5281 $user_element = "user";
5282 foreach ($members as $member) {
5283 $user = api_get_user($a, $member['nurl']);
5287 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5289 return api_format_data("groups", $type, ['group' => $grps]);
5291 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5295 * Delete the specified group of the user.
5297 * @param string $type Return type (atom, rss, xml, json)
5299 * @return array|string
5301 function api_friendica_group_delete($type)
5305 if (api_user() === false) {
5306 throw new ForbiddenException();
5310 $user_info = api_get_user($a);
5311 $gid = defaults($_REQUEST, 'gid', 0);
5312 $name = defaults($_REQUEST, 'name', "");
5313 $uid = $user_info['uid'];
5315 // error if no gid specified
5316 if ($gid == 0 || $name == "") {
5317 throw new BadRequestException('gid or name not specified');
5320 // get data of the specified group id
5322 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5326 // error message if specified gid is not in database
5327 if (!DBA::isResult($r)) {
5328 throw new BadRequestException('gid not available');
5331 // get data of the specified group id and group name
5333 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5338 // error message if specified gid is not in database
5339 if (!DBA::isResult($rname)) {
5340 throw new BadRequestException('wrong group name');
5344 $ret = Group::removeByName($uid, $name);
5347 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5348 return api_format_data("group_delete", $type, ['result' => $success]);
5350 throw new BadRequestException('other API error');
5353 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5358 * @param string $type Return type (atom, rss, xml, json)
5360 * @return array|string
5361 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5363 function api_lists_destroy($type)
5367 if (api_user() === false) {
5368 throw new ForbiddenException();
5372 $user_info = api_get_user($a);
5373 $gid = defaults($_REQUEST, 'list_id', 0);
5374 $uid = $user_info['uid'];
5376 // error if no gid specified
5378 throw new BadRequestException('gid not specified');
5381 // get data of the specified group id
5382 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5383 // error message if specified gid is not in database
5385 throw new BadRequestException('gid not available');
5388 if (Group::remove($gid)) {
5390 'name' => $group['name'],
5391 'id' => intval($gid),
5392 'id_str' => (string) $gid,
5393 'user' => $user_info
5396 return api_format_data("lists", $type, ['lists' => $list]);
5399 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5402 * Add a new group to the database.
5404 * @param string $name Group name
5405 * @param int $uid User ID
5406 * @param array $users List of users to add to the group
5410 function group_create($name, $uid, $users = [])
5412 // error if no name specified
5414 throw new BadRequestException('group name not specified');
5417 // get data of the specified group name
5419 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5423 // error message if specified group name already exists
5424 if (DBA::isResult($rname)) {
5425 throw new BadRequestException('group name already exists');
5428 // check if specified group name is a deleted group
5430 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5434 // error message if specified group name already exists
5435 if (DBA::isResult($rname)) {
5436 $reactivate_group = true;
5440 $ret = Group::create($uid, $name);
5442 $gid = Group::getIdByName($uid, $name);
5444 throw new BadRequestException('other API error');
5448 $erroraddinguser = false;
5450 foreach ($users as $user) {
5451 $cid = $user['cid'];
5452 // check if user really exists as contact
5454 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5458 if (count($contact)) {
5459 Group::addMember($gid, $cid);
5461 $erroraddinguser = true;
5462 $errorusers[] = $cid;
5466 // return success message incl. missing users in array
5467 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5469 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5473 * Create the specified group with the posted array of contacts.
5475 * @param string $type Return type (atom, rss, xml, json)
5477 * @return array|string
5479 function api_friendica_group_create($type)
5483 if (api_user() === false) {
5484 throw new ForbiddenException();
5488 $user_info = api_get_user($a);
5489 $name = defaults($_REQUEST, 'name', "");
5490 $uid = $user_info['uid'];
5491 $json = json_decode($_POST['json'], true);
5492 $users = $json['user'];
5494 $success = group_create($name, $uid, $users);
5496 return api_format_data("group_create", $type, ['result' => $success]);
5498 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5501 * Create a new group.
5503 * @param string $type Return type (atom, rss, xml, json)
5505 * @return array|string
5506 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5508 function api_lists_create($type)
5512 if (api_user() === false) {
5513 throw new ForbiddenException();
5517 $user_info = api_get_user($a);
5518 $name = defaults($_REQUEST, 'name', "");
5519 $uid = $user_info['uid'];
5521 $success = group_create($name, $uid);
5522 if ($success['success']) {
5524 'name' => $success['name'],
5525 'id' => intval($success['gid']),
5526 'id_str' => (string) $success['gid'],
5527 'user' => $user_info
5530 return api_format_data("lists", $type, ['lists'=>$grp]);
5533 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5536 * Update the specified group with the posted array of contacts.
5538 * @param string $type Return type (atom, rss, xml, json)
5540 * @return array|string
5542 function api_friendica_group_update($type)
5546 if (api_user() === false) {
5547 throw new ForbiddenException();
5551 $user_info = api_get_user($a);
5552 $uid = $user_info['uid'];
5553 $gid = defaults($_REQUEST, 'gid', 0);
5554 $name = defaults($_REQUEST, 'name', "");
5555 $json = json_decode($_POST['json'], true);
5556 $users = $json['user'];
5558 // error if no name specified
5560 throw new BadRequestException('group name not specified');
5563 // error if no gid specified
5565 throw new BadRequestException('gid not specified');
5569 $members = Contact::getByGroupId($gid);
5570 foreach ($members as $member) {
5571 $cid = $member['id'];
5572 foreach ($users as $user) {
5573 $found = ($user['cid'] == $cid ? true : false);
5575 if (!isset($found) || !$found) {
5576 Group::removeMemberByName($uid, $name, $cid);
5581 $erroraddinguser = false;
5583 foreach ($users as $user) {
5584 $cid = $user['cid'];
5585 // check if user really exists as contact
5587 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5592 if (count($contact)) {
5593 Group::addMember($gid, $cid);
5595 $erroraddinguser = true;
5596 $errorusers[] = $cid;
5600 // return success message incl. missing users in array
5601 $status = ($erroraddinguser ? "missing user" : "ok");
5602 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5603 return api_format_data("group_update", $type, ['result' => $success]);
5606 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5609 * Update information about a group.
5611 * @param string $type Return type (atom, rss, xml, json)
5613 * @return array|string
5614 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5616 function api_lists_update($type)
5620 if (api_user() === false) {
5621 throw new ForbiddenException();
5625 $user_info = api_get_user($a);
5626 $gid = defaults($_REQUEST, 'list_id', 0);
5627 $name = defaults($_REQUEST, 'name', "");
5628 $uid = $user_info['uid'];
5630 // error if no gid specified
5632 throw new BadRequestException('gid not specified');
5635 // get data of the specified group id
5636 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5637 // error message if specified gid is not in database
5639 throw new BadRequestException('gid not available');
5642 if (Group::update($gid, $name)) {
5645 'id' => intval($gid),
5646 'id_str' => (string) $gid,
5647 'user' => $user_info
5650 return api_format_data("lists", $type, ['lists' => $list]);
5654 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5658 * @param string $type Return type (atom, rss, xml, json)
5660 * @return array|string
5662 function api_friendica_activity($type)
5666 if (api_user() === false) {
5667 throw new ForbiddenException();
5669 $verb = strtolower($a->argv[3]);
5670 $verb = preg_replace("|\..*$|", "", $verb);
5672 $id = defaults($_REQUEST, 'id', 0);
5674 $res = Item::performLike($id, $verb);
5677 if ($type == "xml") {
5682 return api_format_data('ok', $type, ['ok' => $ok]);
5684 throw new BadRequestException('Error adding activity');
5688 /// @TODO move to top of file or somewhere better
5689 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5690 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5691 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5692 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5693 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5694 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5695 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5696 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5697 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5698 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5701 * @brief Returns notifications
5703 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5704 * @return string|array
5706 function api_friendica_notification($type)
5710 if (api_user() === false) {
5711 throw new ForbiddenException();
5714 throw new BadRequestException("Invalid argument count");
5716 $nm = new NotificationsManager();
5718 $notes = $nm->getAll([], "+seen -date", 50);
5720 if ($type == "xml") {
5722 if (!empty($notes)) {
5723 foreach ($notes as $note) {
5724 $xmlnotes[] = ["@attributes" => $note];
5730 return api_format_data("notes", $type, ['note' => $notes]);
5734 * POST request with 'id' param as notification id
5736 * @brief Set notification as seen and returns associated item (if possible)
5738 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5739 * @return string|array
5741 function api_friendica_notification_seen($type)
5744 $user_info = api_get_user($a);
5746 if (api_user() === false || $user_info === false) {
5747 throw new ForbiddenException();
5750 throw new BadRequestException("Invalid argument count");
5753 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5755 $nm = new NotificationsManager();
5756 $note = $nm->getByID($id);
5757 if (is_null($note)) {
5758 throw new BadRequestException("Invalid argument");
5761 $nm->setSeen($note);
5762 if ($note['otype']=='item') {
5763 // would be really better with an ItemsManager and $im->getByID() :-P
5764 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5765 if (DBA::isResult($item)) {
5766 // we found the item, return it to the user
5767 $ret = api_format_items([$item], $user_info, false, $type);
5768 $data = ['status' => $ret];
5769 return api_format_data("status", $type, $data);
5771 // the item can't be found, but we set the note as seen, so we count this as a success
5773 return api_format_data('result', $type, ['result' => "success"]);
5776 /// @TODO move to top of file or somewhere better
5777 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5778 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5781 * @brief update a direct_message to seen state
5783 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5784 * @return string|array (success result=ok, error result=error with error message)
5786 function api_friendica_direct_messages_setseen($type)
5789 if (api_user() === false) {
5790 throw new ForbiddenException();
5794 $user_info = api_get_user($a);
5795 $uid = $user_info['uid'];
5796 $id = defaults($_REQUEST, 'id', 0);
5798 // return error if id is zero
5800 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5801 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5804 // error message if specified id is not in database
5805 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5806 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5807 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5810 // update seen indicator
5811 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5815 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5816 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5818 $answer = ['result' => 'error', 'message' => 'unknown error'];
5819 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5823 /// @TODO move to top of file or somewhere better
5824 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5827 * @brief search for direct_messages containing a searchstring through api
5829 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5830 * @param string $box
5831 * @return string|array (success: success=true if found and search_result contains found messages,
5832 * success=false if nothing was found, search_result='nothing found',
5833 * error: result=error with error message)
5835 function api_friendica_direct_messages_search($type, $box = "")
5839 if (api_user() === false) {
5840 throw new ForbiddenException();
5844 $user_info = api_get_user($a);
5845 $searchstring = defaults($_REQUEST, 'searchstring', "");
5846 $uid = $user_info['uid'];
5848 // error if no searchstring specified
5849 if ($searchstring == "") {
5850 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5851 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5854 // get data for the specified searchstring
5856 "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",
5858 DBA::escape('%'.$searchstring.'%')
5861 $profile_url = $user_info["url"];
5863 // message if nothing was found
5864 if (!DBA::isResult($r)) {
5865 $success = ['success' => false, 'search_results' => 'problem with query'];
5866 } elseif (count($r) == 0) {
5867 $success = ['success' => false, 'search_results' => 'nothing found'];
5870 foreach ($r as $item) {
5871 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5872 $recipient = $user_info;
5873 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5874 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5875 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5876 $sender = $user_info;
5879 if (isset($recipient) && isset($sender)) {
5880 $ret[] = api_format_messages($item, $recipient, $sender);
5883 $success = ['success' => true, 'search_results' => $ret];
5886 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5889 /// @TODO move to top of file or somewhere better
5890 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5893 * @brief return data of all the profiles a user has to the client
5895 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5896 * @return string|array
5898 function api_friendica_profile_show($type)
5902 if (api_user() === false) {
5903 throw new ForbiddenException();
5907 $profile_id = defaults($_REQUEST, 'profile_id', 0);
5909 // retrieve general information about profiles for user
5910 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5911 $directory = Config::get('system', 'directory');
5913 // get data of the specified profile id or all profiles of the user if not specified
5914 if ($profile_id != 0) {
5916 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5921 // error message if specified gid is not in database
5922 if (!DBA::isResult($r)) {
5923 throw new BadRequestException("profile_id not available");
5927 "SELECT * FROM `profile` WHERE `uid` = %d",
5931 // loop through all returned profiles and retrieve data and users
5934 foreach ($r as $rr) {
5935 $profile = api_format_items_profiles($rr);
5937 // select all users from contact table, loop and prepare standard return for user data
5940 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5945 foreach ($nurls as $nurl) {
5946 $user = api_get_user($a, $nurl['nurl']);
5947 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5949 $profile['users'] = $users;
5951 // add prepared profile data to array for final return
5952 if ($type == "xml") {
5953 $profiles[$k++ . ":profile"] = $profile;
5955 $profiles[] = $profile;
5959 // return settings, authenticated user and profiles data
5960 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
5962 $result = ['multi_profiles' => $multi_profiles ? true : false,
5963 'global_dir' => $directory,
5964 'friendica_owner' => api_get_user($a, $self['nurl']),
5965 'profiles' => $profiles];
5966 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5968 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5971 * Returns a list of saved searches.
5973 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5975 * @param string $type Return format: json or xml
5977 * @return string|array
5979 function api_saved_searches_list($type)
5981 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
5984 while ($term = $terms->fetch()) {
5986 'created_at' => api_date(time()),
5987 'id' => intval($term['id']),
5988 'id_str' => $term['id'],
5989 'name' => $term['term'],
5991 'query' => $term['term']
5997 return api_format_data("terms", $type, ['terms' => $result]);
6000 /// @TODO move to top of file or somewhere better
6001 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6004 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6006 * @brief Number of comments
6008 * @param object $data [Status, Status]
6012 function bindComments(&$data)
6014 if (count($data) == 0) {
6020 foreach ($data as $item) {
6021 $ids[] = $item['id'];
6024 $idStr = DBA::escape(implode(', ', $ids));
6025 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6026 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6027 $itemsData = DBA::toArray($items);
6029 foreach ($itemsData as $item) {
6030 $comments[$item['parent']] = $item['comments'];
6033 foreach ($data as $idx => $item) {
6035 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6040 @TODO Maybe open to implement?
6042 [pagename] => api/1.1/statuses/lookup.json
6043 [id] => 605138389168451584
6044 [include_cards] => true
6045 [cards_platform] => Android-12
6046 [include_entities] => true
6047 [include_my_retweet] => 1
6049 [include_reply_count] => true
6050 [include_descendent_reply_count] => true
6054 Not implemented by now:
6055 statuses/retweets_of_me
6060 account/update_location
6061 account/update_profile_background_image
6064 friendica/profile/update
6065 friendica/profile/create
6066 friendica/profile/delete
6068 Not implemented in status.net:
6069 statuses/retweeted_to_me
6070 statuses/retweeted_by_me
6071 direct_messages/destroy
6073 account/update_delivery_device
6074 notifications/follow