3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\Content\ContactSelector;
11 use Friendica\Content\Feature;
12 use Friendica\Content\Text\BBCode;
13 use Friendica\Content\Text\HTML;
14 use Friendica\Core\Addon;
15 use Friendica\Core\Authentication;
16 use Friendica\Core\Config;
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 Addon::callHooks('logged_in', $a->user);
180 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
181 var_dump($consumer, $token);
183 } catch (Exception $e) {
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::log('API_login: ' . print_r($_SERVER, true), Logger::DEBUG);
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 Addon::callHooks('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::log('API_login failure: ' . print_r($_SERVER, true), Logger::DEBUG);
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 Addon::callHooks('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::log('API call for ' . $a->user['username'] . ': ' . $a->query_string);
313 Logger::log('API parameters: ' . print_r($_REQUEST, true));
315 $stamp = microtime(true);
316 $return = call_user_func($info['func'], $type);
317 $duration = (float) (microtime(true) - $stamp);
318 Logger::log("API call duration: " . round($duration, 2) . "\t" . $a->query_string, Logger::DEBUG);
320 if (Config::get("system", "profiler")) {
321 $duration = microtime(true)-$a->performance["start"];
323 /// @TODO round() really everywhere?
325 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
326 "Database: %s/%s, Cache %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
327 round($a->performance["database"] - $a->performance["database_write"], 3),
328 round($a->performance["database_write"], 3),
329 round($a->performance["cache"], 3),
330 round($a->performance["cache_write"], 3),
331 round($a->performance["network"], 2),
332 round($a->performance["file"], 2),
333 round($duration - ($a->performance["database"]
334 + $a->performance["cache"] + $a->performance["cache_write"]
335 + $a->performance["network"] + $a->performance["file"]), 2),
341 if (Config::get("rendertime", "callstack")) {
342 $o = "Database Read:\n";
343 foreach ($a->callstack["database"] as $func => $time) {
344 $time = round($time, 3);
346 $o .= $func . ": " . $time . "\n";
349 $o .= "\nDatabase Write:\n";
350 foreach ($a->callstack["database_write"] as $func => $time) {
351 $time = round($time, 3);
353 $o .= $func . ": " . $time . "\n";
357 $o = "Cache Read:\n";
358 foreach ($a->callstack["cache"] as $func => $time) {
359 $time = round($time, 3);
361 $o .= $func . ": " . $time . "\n";
364 $o .= "\nCache Write:\n";
365 foreach ($a->callstack["cache_write"] as $func => $time) {
366 $time = round($time, 3);
368 $o .= $func . ": " . $time . "\n";
372 $o .= "\nNetwork:\n";
373 foreach ($a->callstack["network"] as $func => $time) {
374 $time = round($time, 3);
376 $o .= $func . ": " . $time . "\n";
379 Logger::log($o, Logger::DEBUG);
383 if (false === $return) {
385 * api function returned false withour throw an
386 * exception. This should not happend, throw a 500
388 throw new InternalServerErrorException();
393 header("Content-Type: text/xml");
396 header("Content-Type: application/json");
397 $json = json_encode(end($return));
398 if (!empty($_GET['callback'])) {
399 $json = $_GET['callback'] . "(" . $json . ")";
404 header("Content-Type: application/rss+xml");
405 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
408 header("Content-Type: application/atom+xml");
409 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
416 Logger::log('API call not implemented: ' . $a->query_string);
417 throw new NotImplementedException();
418 } catch (HTTPException $e) {
419 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
420 return api_error($type, $e);
425 * @brief Format API error string
427 * @param string $type Return type (xml, json, rss, as)
428 * @param object $e HTTPException Error object
429 * @return string|array error message formatted as $type
431 function api_error($type, $e)
435 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
436 /// @TODO: https://dev.twitter.com/overview/api/response-codes
438 $error = ["error" => $error,
439 "code" => $e->httpcode . " " . $e->httpdesc,
440 "request" => $a->query_string];
442 $return = api_format_data('status', $type, ['status' => $error]);
446 header("Content-Type: text/xml");
449 header("Content-Type: application/json");
450 $return = json_encode($return);
453 header("Content-Type: application/rss+xml");
456 header("Content-Type: application/atom+xml");
464 * @brief Set values for RSS template
467 * @param array $arr Array to be passed to template
468 * @param array $user_info User info
470 * @todo find proper type-hints
472 function api_rss_extra(App $a, $arr, $user_info)
474 if (is_null($user_info)) {
475 $user_info = api_get_user($a);
478 $arr['$user'] = $user_info;
480 'alternate' => $user_info['url'],
481 'self' => System::baseUrl() . "/" . $a->query_string,
482 'base' => System::baseUrl(),
483 'updated' => api_date(null),
484 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
485 'language' => $user_info['lang'],
486 'logo' => System::baseUrl() . "/images/friendica-32.png",
494 * @brief Unique contact to contact url.
496 * @param int $id Contact id
497 * @return bool|string
498 * Contact url or False if contact id is unknown
500 function api_unique_id_to_nurl($id)
502 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
504 if (DBA::isResult($r)) {
512 * @brief Get user info array.
514 * @param object $a App
515 * @param int|string $contact_id Contact ID or URL
517 function api_get_user(App $a, $contact_id = null)
525 Logger::log("api_get_user: Fetching user data for user ".$contact_id, Logger::DEBUG);
527 // Searching for contact URL
528 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
529 $user = DBA::escape(Strings::normaliseLink($contact_id));
531 $extra_query = "AND `contact`.`nurl` = '%s' ";
532 if (api_user() !== false) {
533 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
537 // Searching for contact id with uid = 0
538 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
539 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
542 throw new BadRequestException("User ID ".$contact_id." not found.");
546 $extra_query = "AND `contact`.`nurl` = '%s' ";
547 if (api_user() !== false) {
548 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
552 if (is_null($user) && !empty($_GET['user_id'])) {
553 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
556 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
560 $extra_query = "AND `contact`.`nurl` = '%s' ";
561 if (api_user() !== false) {
562 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
565 if (is_null($user) && !empty($_GET['screen_name'])) {
566 $user = DBA::escape($_GET['screen_name']);
567 $extra_query = "AND `contact`.`nick` = '%s' ";
568 if (api_user() !== false) {
569 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
573 if (is_null($user) && !empty($_GET['profileurl'])) {
574 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
575 $extra_query = "AND `contact`.`nurl` = '%s' ";
576 if (api_user() !== false) {
577 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
581 // $called_api is the API path exploded on / and is expected to have at least 2 elements
582 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
583 $argid = count($called_api);
584 if (!empty($a->argv[$argid])) {
585 $data = explode(".", $a->argv[$argid]);
586 if (count($data) > 1) {
587 list($user, $null) = $data;
590 if (is_numeric($user)) {
591 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
595 $extra_query = "AND `contact`.`nurl` = '%s' ";
596 if (api_user() !== false) {
597 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
601 $user = DBA::escape($user);
602 $extra_query = "AND `contact`.`nick` = '%s' ";
603 if (api_user() !== false) {
604 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
609 Logger::log("api_get_user: user ".$user, Logger::DEBUG);
612 if (api_user() === false) {
616 $user = $_SESSION['uid'];
617 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
621 Logger::log('api_user: ' . $extra_query . ', user: ' . $user);
625 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
631 // Selecting the id by priority, friendica first
632 if (is_array($uinfo)) {
633 api_best_nickname($uinfo);
636 // if the contact wasn't found, fetch it from the contacts with uid = 0
637 if (!DBA::isResult($uinfo)) {
639 throw new BadRequestException("User not found.");
642 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
644 if (DBA::isResult($contact)) {
645 $network_name = ContactSelector::networkToName($contact['network'], $contact['url']);
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"] : $network_name,
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 $network_name = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
717 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
719 if (!empty($profile['about'])) {
720 $description = $profile['about'];
722 $description = $uinfo[0]["about"];
725 if (!empty($usr['default-location'])) {
726 $location = $usr['default-location'];
727 } elseif (!empty($uinfo[0]["location"])) {
728 $location = $uinfo[0]["location"];
730 $location = $network_name;
734 'id' => intval($pcontact_id),
735 'id_str' => (string) intval($pcontact_id),
736 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
737 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
738 'location' => $location,
739 'description' => $description,
740 'profile_image_url' => $uinfo[0]['micro'],
741 'profile_image_url_https' => $uinfo[0]['micro'],
742 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
743 'profile_image_url_large' => $uinfo[0]["photo"],
744 'url' => $uinfo[0]['url'],
745 'protected' => false,
746 'followers_count' => intval($countfollowers),
747 'friends_count' => intval($countfriends),
749 'created_at' => api_date($uinfo[0]['created']),
750 'favourites_count' => intval($starred),
752 'time_zone' => 'UTC',
753 'geo_enabled' => false,
755 'statuses_count' => intval($countitems),
757 'contributors_enabled' => false,
758 'is_translator' => false,
759 'is_translation_enabled' => false,
760 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
761 'follow_request_sent' => false,
762 'statusnet_blocking' => false,
763 'notifications' => false,
765 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
766 'statusnet_profile_url' => $uinfo[0]['url'],
767 'uid' => intval($uinfo[0]['uid']),
768 'cid' => intval($uinfo[0]['cid']),
769 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
770 'self' => $uinfo[0]['self'],
771 'network' => $uinfo[0]['network'],
774 // If this is a local user and it uses Frio, we can get its color preferences.
776 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
777 if ($theme_info['theme'] === 'frio') {
778 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
780 if ($schema && ($schema != '---')) {
781 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
782 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
783 require_once $schemefile;
786 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
787 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
788 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
790 if (empty($nav_bg)) {
793 if (empty($link_color)) {
794 $link_color = "#6fdbe8";
796 if (empty($bgcolor)) {
797 $bgcolor = "#ededed";
800 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
801 $ret['profile_link_color'] = str_replace('#', '', $link_color);
802 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
810 * @brief return api-formatted array for item's author and owner
812 * @param object $a App
813 * @param array $item item from db
814 * @return array(array:author, array:owner)
816 function api_item_get_user(App $a, $item)
818 $status_user = api_get_user($a, defaults($item, 'author-id', null));
820 $status_user["protected"] = defaults($item, 'private', 0);
822 if (defaults($item, 'thr-parent', '') == defaults($item, 'uri', '')) {
823 $owner_user = api_get_user($a, defaults($item, 'owner-id', null));
825 $owner_user = $status_user;
828 return ([$status_user, $owner_user]);
832 * @brief walks recursively through an array with the possibility to change value and key
834 * @param array $array The array to walk through
835 * @param string $callback The callback function
837 * @return array the transformed array
839 function api_walk_recursive(array &$array, callable $callback)
843 foreach ($array as $k => $v) {
845 if ($callback($v, $k)) {
846 $new_array[$k] = api_walk_recursive($v, $callback);
849 if ($callback($v, $k)) {
860 * @brief Callback function to transform the array in an array that can be transformed in a XML file
862 * @param mixed $item Array item value
863 * @param string $key Array key
865 * @return boolean Should the array item be deleted?
867 function api_reformat_xml(&$item, &$key)
869 if (is_bool($item)) {
870 $item = ($item ? "true" : "false");
873 if (substr($key, 0, 10) == "statusnet_") {
874 $key = "statusnet:".substr($key, 10);
875 } elseif (substr($key, 0, 10) == "friendica_") {
876 $key = "friendica:".substr($key, 10);
878 /// @TODO old-lost code?
880 // $key = "default:".$key;
886 * @brief Creates the XML from a JSON style array
888 * @param array $data JSON style array
889 * @param string $root_element Name of the root element
891 * @return string The XML data
893 function api_create_xml(array $data, $root_element)
895 $childname = key($data);
896 $data2 = array_pop($data);
898 $namespaces = ["" => "http://api.twitter.com",
899 "statusnet" => "http://status.net/schema/api/1/",
900 "friendica" => "http://friendi.ca/schema/api/1/",
901 "georss" => "http://www.georss.org/georss"];
903 /// @todo Auto detection of needed namespaces
904 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
908 if (is_array($data2)) {
910 api_walk_recursive($data2, "api_reformat_xml");
916 foreach ($data2 as $item) {
917 $data4[$i++ . ":" . $childname] = $item;
924 $data3 = [$root_element => $data2];
926 $ret = XML::fromArray($data3, $xml, false, $namespaces);
931 * @brief Formats the data according to the data type
933 * @param string $root_element Name of the root element
934 * @param string $type Return type (atom, rss, xml, json)
935 * @param array $data JSON style array
937 * @return (string|array) XML data or JSON data
939 function api_format_data($root_element, $type, $data)
945 $ret = api_create_xml($data, $root_element);
961 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
962 * returns a 401 status code and an error message if not.
963 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
965 * @param string $type Return type (atom, rss, xml, json)
967 function api_account_verify_credentials($type)
972 if (api_user() === false) {
973 throw new ForbiddenException();
976 unset($_REQUEST["user_id"]);
977 unset($_GET["user_id"]);
979 unset($_REQUEST["screen_name"]);
980 unset($_GET["screen_name"]);
982 $skip_status = defaults($_REQUEST, 'skip_status', false);
984 $user_info = api_get_user($a);
986 // "verified" isn't used here in the standard
987 unset($user_info["verified"]);
989 // - Adding last status
991 $user_info["status"] = api_status_show("raw");
992 if (!count($user_info["status"])) {
993 unset($user_info["status"]);
995 unset($user_info["status"]["user"]);
999 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1000 unset($user_info["uid"]);
1001 unset($user_info["self"]);
1003 return api_format_data("user", $type, ['user' => $user_info]);
1006 /// @TODO move to top of file or somewhere better
1007 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1010 * Get data from $_POST or $_GET
1014 function requestdata($k)
1016 if (!empty($_POST[$k])) {
1019 if (!empty($_GET[$k])) {
1026 * Deprecated function to upload media.
1028 * @param string $type Return type (atom, rss, xml, json)
1030 * @return array|string
1032 function api_statuses_mediap($type)
1036 if (api_user() === false) {
1037 Logger::log('api_statuses_update: no user');
1038 throw new ForbiddenException();
1040 $user_info = api_get_user($a);
1042 $_REQUEST['profile_uid'] = api_user();
1043 $_REQUEST['api_source'] = true;
1044 $txt = requestdata('status');
1045 /// @TODO old-lost code?
1046 //$txt = urldecode(requestdata('status'));
1048 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1049 $txt = HTML::toBBCodeVideo($txt);
1050 $config = HTMLPurifier_Config::createDefault();
1051 $config->set('Cache.DefinitionImpl', null);
1052 $purifier = new HTMLPurifier($config);
1053 $txt = $purifier->purify($txt);
1055 $txt = HTML::toBBCode($txt);
1057 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1059 $picture = wall_upload_post($a, false);
1061 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1062 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1063 $item_id = item_post($a);
1065 // output the post that we just posted.
1066 return api_status_show($type, $item_id);
1069 /// @TODO move this to top of file or somewhere better!
1070 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1073 * Updates the user’s current status.
1075 * @param string $type Return type (atom, rss, xml, json)
1077 * @return array|string
1078 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1080 function api_statuses_update($type)
1084 if (api_user() === false) {
1085 Logger::log('api_statuses_update: no user');
1086 throw new ForbiddenException();
1091 // convert $_POST array items to the form we use for web posts.
1092 if (requestdata('htmlstatus')) {
1093 $txt = requestdata('htmlstatus');
1094 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1095 $txt = HTML::toBBCodeVideo($txt);
1097 $config = HTMLPurifier_Config::createDefault();
1098 $config->set('Cache.DefinitionImpl', null);
1100 $purifier = new HTMLPurifier($config);
1101 $txt = $purifier->purify($txt);
1103 $_REQUEST['body'] = HTML::toBBCode($txt);
1106 $_REQUEST['body'] = requestdata('status');
1109 $_REQUEST['title'] = requestdata('title');
1111 $parent = requestdata('in_reply_to_status_id');
1113 // Twidere sends "-1" if it is no reply ...
1114 if ($parent == -1) {
1118 if (ctype_digit($parent)) {
1119 $_REQUEST['parent'] = $parent;
1121 $_REQUEST['parent_uri'] = $parent;
1124 if (requestdata('lat') && requestdata('long')) {
1125 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1127 $_REQUEST['profile_uid'] = api_user();
1130 // Check for throttling (maximum posts per day, week and month)
1131 $throttle_day = Config::get('system', 'throttle_limit_day');
1132 if ($throttle_day > 0) {
1133 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1135 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1136 $posts_day = DBA::count('thread', $condition);
1138 if ($posts_day > $throttle_day) {
1139 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1140 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1141 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));
1145 $throttle_week = Config::get('system', 'throttle_limit_week');
1146 if ($throttle_week > 0) {
1147 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1149 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1150 $posts_week = DBA::count('thread', $condition);
1152 if ($posts_week > $throttle_week) {
1153 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1154 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1155 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));
1159 $throttle_month = Config::get('system', 'throttle_limit_month');
1160 if ($throttle_month > 0) {
1161 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1163 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1164 $posts_month = DBA::count('thread', $condition);
1166 if ($posts_month > $throttle_month) {
1167 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1168 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1169 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));
1174 if (!empty($_FILES['media'])) {
1175 // upload the image if we have one
1176 $picture = wall_upload_post($a, false);
1177 if (is_array($picture)) {
1178 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1182 // To-Do: Multiple IDs
1183 if (requestdata('media_ids')) {
1185 "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",
1186 intval(requestdata('media_ids')),
1189 if (DBA::isResult($r)) {
1190 $phototypes = Image::supportedTypes();
1191 $ext = $phototypes[$r[0]['type']];
1192 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1193 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1197 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1199 $_REQUEST['api_source'] = true;
1201 if (empty($_REQUEST['source'])) {
1202 $_REQUEST["source"] = api_source();
1205 // call out normal post function
1206 $item_id = item_post($a);
1208 // output the post that we just posted.
1209 return api_status_show($type, $item_id);
1212 /// @TODO move to top of file or somewhere better
1213 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1214 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1217 * Uploads an image to Friendica.
1220 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1222 function api_media_upload()
1226 if (api_user() === false) {
1227 Logger::log('no user');
1228 throw new ForbiddenException();
1233 if (empty($_FILES['media'])) {
1235 throw new BadRequestException("No media.");
1238 $media = wall_upload_post($a, false);
1241 throw new InternalServerErrorException();
1245 $returndata["media_id"] = $media["id"];
1246 $returndata["media_id_string"] = (string)$media["id"];
1247 $returndata["size"] = $media["size"];
1248 $returndata["image"] = ["w" => $media["width"],
1249 "h" => $media["height"],
1250 "image_type" => $media["type"]];
1252 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1254 return ["media" => $returndata];
1257 /// @TODO move to top of file or somewhere better
1258 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1262 * @param string $type Return type (atom, rss, xml, json)
1264 * @return array|string
1266 function api_status_show($type, $item_id = 0)
1270 $user_info = api_get_user($a);
1272 Logger::log('api_status_show: user_info: '.print_r($user_info, true), Logger::DEBUG);
1274 if ($type == "raw") {
1275 $privacy_sql = "AND NOT `private`";
1280 if (!empty($item_id)) {
1281 // Get the item with the given id
1282 $condition = ['id' => $item_id];
1284 // get last public wall message
1285 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1286 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1288 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1290 if (DBA::isResult($lastwall)) {
1291 $in_reply_to = api_in_reply_to($lastwall);
1293 $converted = api_convert_item($lastwall);
1295 if ($type == "xml") {
1296 $geo = "georss:point";
1302 'created_at' => api_date($lastwall['created']),
1303 'id' => intval($lastwall['id']),
1304 'id_str' => (string) $lastwall['id'],
1305 'text' => $converted["text"],
1306 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1307 'truncated' => false,
1308 'in_reply_to_status_id' => $in_reply_to['status_id'],
1309 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1310 'in_reply_to_user_id' => $in_reply_to['user_id'],
1311 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1312 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1313 'user' => $user_info,
1315 'coordinates' => '',
1317 'contributors' => '',
1318 'is_quote_status' => false,
1319 'retweet_count' => 0,
1320 'favorite_count' => 0,
1321 'favorited' => $lastwall['starred'] ? true : false,
1322 'retweeted' => false,
1323 'possibly_sensitive' => false,
1325 'statusnet_html' => $converted["html"],
1326 'statusnet_conversation_id' => $lastwall['parent'],
1327 'external_url' => System::baseUrl() . '/display/' . $lastwall['guid'],
1330 if (count($converted["attachments"]) > 0) {
1331 $status_info["attachments"] = $converted["attachments"];
1334 if (count($converted["entities"]) > 0) {
1335 $status_info["entities"] = $converted["entities"];
1338 if ($status_info["source"] == 'web') {
1339 $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1340 } elseif (ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) != $status_info["source"]) {
1341 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']).')');
1344 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1345 unset($status_info["user"]["uid"]);
1346 unset($status_info["user"]["self"]);
1348 Logger::log('status_info: '.print_r($status_info, true), Logger::DEBUG);
1350 if ($type == "raw") {
1351 return $status_info;
1354 return api_format_data("statuses", $type, ['status' => $status_info]);
1359 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1360 * The author's most recent status will be returned inline.
1362 * @param string $type Return type (atom, rss, xml, json)
1363 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1365 function api_users_show($type)
1369 $user_info = api_get_user($a);
1371 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1372 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'private' => false];
1373 $lastwall = Item::selectFirst(Item::ITEM_FIELDLIST, $condition, ['order' => ['id' => true]]);
1375 if (DBA::isResult($lastwall)) {
1376 $in_reply_to = api_in_reply_to($lastwall);
1378 $converted = api_convert_item($lastwall);
1380 if ($type == "xml") {
1381 $geo = "georss:point";
1386 $user_info['status'] = [
1387 'text' => $converted["text"],
1388 'truncated' => false,
1389 'created_at' => api_date($lastwall['created']),
1390 'in_reply_to_status_id' => $in_reply_to['status_id'],
1391 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1392 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1393 'id' => intval($lastwall['contact-id']),
1394 'id_str' => (string) $lastwall['contact-id'],
1395 'in_reply_to_user_id' => $in_reply_to['user_id'],
1396 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1397 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1399 'favorited' => $lastwall['starred'] ? true : false,
1400 'statusnet_html' => $converted["html"],
1401 'statusnet_conversation_id' => $lastwall['parent'],
1402 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1405 if (count($converted["attachments"]) > 0) {
1406 $user_info["status"]["attachments"] = $converted["attachments"];
1409 if (count($converted["entities"]) > 0) {
1410 $user_info["status"]["entities"] = $converted["entities"];
1413 if ($user_info["status"]["source"] == 'web') {
1414 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']);
1417 if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
1418 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $lastwall['author-link']) . ')');
1422 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1423 unset($user_info["uid"]);
1424 unset($user_info["self"]);
1426 return api_format_data("user", $type, ['user' => $user_info]);
1429 /// @TODO move to top of file or somewhere better
1430 api_register_func('api/users/show', 'api_users_show');
1431 api_register_func('api/externalprofile/show', 'api_users_show');
1434 * Search a public user account.
1436 * @param string $type Return type (atom, rss, xml, json)
1438 * @return array|string
1439 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1441 function api_users_search($type)
1447 if (!empty($_GET['q'])) {
1448 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1450 if (!DBA::isResult($r)) {
1451 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1454 if (DBA::isResult($r)) {
1456 foreach ($r as $user) {
1457 $user_info = api_get_user($a, $user["id"]);
1459 if ($type == "xml") {
1460 $userlist[$k++.":user"] = $user_info;
1462 $userlist[] = $user_info;
1465 $userlist = ["users" => $userlist];
1467 throw new BadRequestException("User ".$_GET["q"]." not found.");
1470 throw new BadRequestException("No user specified.");
1473 return api_format_data("users", $type, $userlist);
1476 /// @TODO move to top of file or somewhere better
1477 api_register_func('api/users/search', 'api_users_search');
1480 * Return user objects
1482 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1484 * @param string $type Return format: json or xml
1486 * @return array|string
1487 * @throws NotFoundException if the results are empty.
1489 function api_users_lookup($type)
1493 if (!empty($_REQUEST['user_id'])) {
1494 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1496 $users[] = api_get_user(get_app(), $id);
1501 if (empty($users)) {
1502 throw new NotFoundException;
1505 return api_format_data("users", $type, ['users' => $users]);
1508 /// @TODO move to top of file or somewhere better
1509 api_register_func('api/users/lookup', 'api_users_lookup', true);
1512 * Returns statuses that match a specified query.
1514 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1516 * @param string $type Return format: json, xml, atom, rss
1518 * @return array|string
1519 * @throws BadRequestException if the "q" parameter is missing.
1521 function api_search($type)
1524 $user_info = api_get_user($a);
1526 if (api_user() === false || $user_info === false) {
1527 throw new ForbiddenException();
1532 if (empty($_REQUEST['q'])) {
1533 throw new BadRequestException("q parameter is required.");
1536 if (!empty($_REQUEST['rpp'])) {
1537 $count = $_REQUEST['rpp'];
1538 } elseif (!empty($_REQUEST['count'])) {
1539 $count = $_REQUEST['count'];
1544 $since_id = defaults($_REQUEST, 'since_id', 0);
1545 $max_id = defaults($_REQUEST, 'max_id', 0);
1546 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1548 $start = $page * $count;
1550 $condition = ["`gravity` IN (?, ?) AND `item`.`id` > ?
1551 AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1552 AND `item`.`body` LIKE CONCAT('%',?,'%')",
1553 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, api_user(), $_REQUEST['q']];
1556 $condition[0] .= " AND `item`.`id` <= ?";
1557 $condition[] = $max_id;
1560 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1561 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1563 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1565 return api_format_data("statuses", $type, $data);
1568 /// @TODO move to top of file or somewhere better
1569 api_register_func('api/search/tweets', 'api_search', true);
1570 api_register_func('api/search', 'api_search', true);
1573 * Returns the most recent statuses posted by the user and the users they follow.
1575 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1577 * @param string $type Return type (atom, rss, xml, json)
1579 * @todo Optional parameters
1580 * @todo Add reply info
1582 function api_statuses_home_timeline($type)
1585 $user_info = api_get_user($a);
1587 if (api_user() === false || $user_info === false) {
1588 throw new ForbiddenException();
1591 unset($_REQUEST["user_id"]);
1592 unset($_GET["user_id"]);
1594 unset($_REQUEST["screen_name"]);
1595 unset($_GET["screen_name"]);
1597 // get last network messages
1600 $count = defaults($_REQUEST, 'count', 20);
1601 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1605 $since_id = defaults($_REQUEST, 'since_id', 0);
1606 $max_id = defaults($_REQUEST, 'max_id', 0);
1607 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1608 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1610 $start = $page * $count;
1612 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1613 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1616 $condition[0] .= " AND `item`.`id` <= ?";
1617 $condition[] = $max_id;
1619 if ($exclude_replies) {
1620 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1622 if ($conversation_id > 0) {
1623 $condition[0] .= " AND `item`.`parent` = ?";
1624 $condition[] = $conversation_id;
1627 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1628 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1630 $items = Item::inArray($statuses);
1632 $ret = api_format_items($items, $user_info, false, $type);
1634 // Set all posts from the query above to seen
1636 foreach ($items as $item) {
1637 $idarray[] = intval($item["id"]);
1640 if (!empty($idarray)) {
1641 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1643 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1647 $data = ['status' => $ret];
1652 $data = api_rss_extra($a, $data, $user_info);
1656 return api_format_data("statuses", $type, $data);
1659 /// @TODO move to top of file or somewhere better
1660 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1661 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1664 * Returns the most recent statuses from public users.
1666 * @param string $type Return type (atom, rss, xml, json)
1668 * @return array|string
1670 function api_statuses_public_timeline($type)
1673 $user_info = api_get_user($a);
1675 if (api_user() === false || $user_info === false) {
1676 throw new ForbiddenException();
1679 // get last network messages
1682 $count = defaults($_REQUEST, 'count', 20);
1683 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
1687 $since_id = defaults($_REQUEST, 'since_id', 0);
1688 $max_id = defaults($_REQUEST, 'max_id', 0);
1689 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1690 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1692 $start = $page * $count;
1694 if ($exclude_replies && !$conversation_id) {
1695 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall`",
1696 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1699 $condition[0] .= " AND `thread`.`iid` <= ?";
1700 $condition[] = $max_id;
1703 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1704 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1706 $r = Item::inArray($statuses);
1708 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin`",
1709 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1712 $condition[0] .= " AND `item`.`id` <= ?";
1713 $condition[] = $max_id;
1715 if ($conversation_id > 0) {
1716 $condition[0] .= " AND `item`.`parent` = ?";
1717 $condition[] = $conversation_id;
1720 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1721 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1723 $r = Item::inArray($statuses);
1726 $ret = api_format_items($r, $user_info, false, $type);
1728 $data = ['status' => $ret];
1733 $data = api_rss_extra($a, $data, $user_info);
1737 return api_format_data("statuses", $type, $data);
1740 /// @TODO move to top of file or somewhere better
1741 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1744 * Returns the most recent statuses posted by users this node knows about.
1746 * @brief Returns the list of public federated posts this node knows about
1748 * @param string $type Return format: json, xml, atom, rss
1749 * @return array|string
1750 * @throws ForbiddenException
1752 function api_statuses_networkpublic_timeline($type)
1755 $user_info = api_get_user($a);
1757 if (api_user() === false || $user_info === false) {
1758 throw new ForbiddenException();
1761 $since_id = defaults($_REQUEST, 'since_id', 0);
1762 $max_id = defaults($_REQUEST, 'max_id', 0);
1765 $count = defaults($_REQUEST, 'count', 20);
1766 $page = defaults($_REQUEST, 'page', 1);
1770 $start = ($page - 1) * $count;
1772 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1773 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1776 $condition[0] .= " AND `thread`.`iid` <= ?";
1777 $condition[] = $max_id;
1780 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1781 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1783 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1785 $data = ['status' => $ret];
1790 $data = api_rss_extra($a, $data, $user_info);
1794 return api_format_data("statuses", $type, $data);
1797 /// @TODO move to top of file or somewhere better
1798 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1801 * Returns a single status.
1803 * @param string $type Return type (atom, rss, xml, json)
1805 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1807 function api_statuses_show($type)
1810 $user_info = api_get_user($a);
1812 if (api_user() === false || $user_info === false) {
1813 throw new ForbiddenException();
1817 $id = intval(defaults($a->argv, 3, 0));
1820 $id = intval(defaults($_REQUEST, 'id', 0));
1825 $id = intval(defaults($a->argv, 4, 0));
1828 Logger::log('API: api_statuses_show: ' . $id);
1830 $conversation = !empty($_REQUEST['conversation']);
1832 // try to fetch the item for the local user - or the public item, if there is no local one
1833 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1834 if (!DBA::isResult($uri_item)) {
1835 throw new BadRequestException("There is no status with this id.");
1838 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1839 if (!DBA::isResult($item)) {
1840 throw new BadRequestException("There is no status with this id.");
1845 if ($conversation) {
1846 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1847 $params = ['order' => ['id' => true]];
1849 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1853 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1855 /// @TODO How about copying this to above methods which don't check $r ?
1856 if (!DBA::isResult($statuses)) {
1857 throw new BadRequestException("There is no status with this id.");
1860 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1862 if ($conversation) {
1863 $data = ['status' => $ret];
1864 return api_format_data("statuses", $type, $data);
1866 $data = ['status' => $ret[0]];
1867 return api_format_data("status", $type, $data);
1871 /// @TODO move to top of file or somewhere better
1872 api_register_func('api/statuses/show', 'api_statuses_show', true);
1876 * @param string $type Return type (atom, rss, xml, json)
1878 * @todo nothing to say?
1880 function api_conversation_show($type)
1883 $user_info = api_get_user($a);
1885 if (api_user() === false || $user_info === false) {
1886 throw new ForbiddenException();
1890 $id = intval(defaults($a->argv , 3 , 0));
1891 $since_id = intval(defaults($_REQUEST, 'since_id', 0));
1892 $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
1893 $count = intval(defaults($_REQUEST, 'count' , 20));
1894 $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
1899 $start = $page * $count;
1902 $id = intval(defaults($_REQUEST, 'id', 0));
1907 $id = intval(defaults($a->argv, 4, 0));
1910 Logger::log('API: api_conversation_show: '.$id);
1912 // try to fetch the item for the local user - or the public item, if there is no local one
1913 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1914 if (!DBA::isResult($item)) {
1915 throw new BadRequestException("There is no status with this id.");
1918 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1919 if (!DBA::isResult($parent)) {
1920 throw new BadRequestException("There is no status with this id.");
1923 $id = $parent['id'];
1925 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1926 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1929 $condition[0] .= " AND `item`.`id` <= ?";
1930 $condition[] = $max_id;
1933 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1934 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1936 if (!DBA::isResult($statuses)) {
1937 throw new BadRequestException("There is no status with id $id.");
1940 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1942 $data = ['status' => $ret];
1943 return api_format_data("statuses", $type, $data);
1946 /// @TODO move to top of file or somewhere better
1947 api_register_func('api/conversation/show', 'api_conversation_show', true);
1948 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1953 * @param string $type Return type (atom, rss, xml, json)
1955 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1957 function api_statuses_repeat($type)
1963 if (api_user() === false) {
1964 throw new ForbiddenException();
1970 $id = intval(defaults($a->argv, 3, 0));
1973 $id = intval(defaults($_REQUEST, 'id', 0));
1978 $id = intval(defaults($a->argv, 4, 0));
1981 Logger::log('API: api_statuses_repeat: '.$id);
1983 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1984 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
1986 if (DBA::isResult($item) && $item['body'] != "") {
1987 if (strpos($item['body'], "[/share]") !== false) {
1988 $pos = strpos($item['body'], "[share");
1989 $post = substr($item['body'], $pos);
1991 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
1993 $post .= $item['body'];
1994 $post .= "[/share]";
1996 $_REQUEST['body'] = $post;
1997 $_REQUEST['profile_uid'] = api_user();
1998 $_REQUEST['api_source'] = true;
2000 if (empty($_REQUEST['source'])) {
2001 $_REQUEST["source"] = api_source();
2004 $item_id = item_post($a);
2006 throw new ForbiddenException();
2009 // output the post that we just posted.
2011 return api_status_show($type, $item_id);
2014 /// @TODO move to top of file or somewhere better
2015 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2018 * Destroys a specific status.
2020 * @param string $type Return type (atom, rss, xml, json)
2022 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2024 function api_statuses_destroy($type)
2028 if (api_user() === false) {
2029 throw new ForbiddenException();
2035 $id = intval(defaults($a->argv, 3, 0));
2038 $id = intval(defaults($_REQUEST, 'id', 0));
2043 $id = intval(defaults($a->argv, 4, 0));
2046 Logger::log('API: api_statuses_destroy: '.$id);
2048 $ret = api_statuses_show($type);
2050 Item::deleteForUser(['id' => $id], api_user());
2055 /// @TODO move to top of file or somewhere better
2056 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2059 * Returns the most recent mentions.
2061 * @param string $type Return type (atom, rss, xml, json)
2063 * @see http://developer.twitter.com/doc/get/statuses/mentions
2065 function api_statuses_mentions($type)
2068 $user_info = api_get_user($a);
2070 if (api_user() === false || $user_info === false) {
2071 throw new ForbiddenException();
2074 unset($_REQUEST["user_id"]);
2075 unset($_GET["user_id"]);
2077 unset($_REQUEST["screen_name"]);
2078 unset($_GET["screen_name"]);
2080 // get last network messages
2083 $since_id = defaults($_REQUEST, 'since_id', 0);
2084 $max_id = defaults($_REQUEST, 'max_id' , 0);
2085 $count = defaults($_REQUEST, 'count' , 20);
2086 $page = defaults($_REQUEST, 'page' , 1);
2091 $start = ($page - 1) * $count;
2093 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2094 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2095 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2098 $condition[0] .= " AND `item`.`id` <= ?";
2099 $condition[] = $max_id;
2102 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2103 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2105 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2107 $data = ['status' => $ret];
2112 $data = api_rss_extra($a, $data, $user_info);
2116 return api_format_data("statuses", $type, $data);
2119 /// @TODO move to top of file or somewhere better
2120 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2121 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2124 * Returns the most recent statuses posted by the user.
2126 * @brief Returns a user's public timeline
2128 * @param string $type Either "json" or "xml"
2129 * @return string|array
2130 * @throws ForbiddenException
2131 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2133 function api_statuses_user_timeline($type)
2136 $user_info = api_get_user($a);
2138 if (api_user() === false || $user_info === false) {
2139 throw new ForbiddenException();
2143 "api_statuses_user_timeline: api_user: ". api_user() .
2144 "\nuser_info: ".print_r($user_info, true) .
2145 "\n_REQUEST: ".print_r($_REQUEST, true),
2149 $since_id = defaults($_REQUEST, 'since_id', 0);
2150 $max_id = defaults($_REQUEST, 'max_id', 0);
2151 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2152 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
2155 $count = defaults($_REQUEST, 'count', 20);
2156 $page = defaults($_REQUEST, 'page', 1);
2160 $start = ($page - 1) * $count;
2162 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2163 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2165 if ($user_info['self'] == 1) {
2166 $condition[0] .= ' AND `item`.`wall` ';
2169 if ($exclude_replies) {
2170 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2173 if ($conversation_id > 0) {
2174 $condition[0] .= " AND `item`.`parent` = ?";
2175 $condition[] = $conversation_id;
2179 $condition[0] .= " AND `item`.`id` <= ?";
2180 $condition[] = $max_id;
2183 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2184 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2186 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2188 $data = ['status' => $ret];
2193 $data = api_rss_extra($a, $data, $user_info);
2197 return api_format_data("statuses", $type, $data);
2200 /// @TODO move to top of file or somewhere better
2201 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2204 * Star/unstar an item.
2205 * param: id : id of the item
2207 * @param string $type Return type (atom, rss, xml, json)
2209 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2211 function api_favorites_create_destroy($type)
2215 if (api_user() === false) {
2216 throw new ForbiddenException();
2219 // for versioned api.
2220 /// @TODO We need a better global soluton
2221 $action_argv_id = 2;
2222 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2223 $action_argv_id = 3;
2226 if ($a->argc <= $action_argv_id) {
2227 throw new BadRequestException("Invalid request.");
2229 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2230 if ($a->argc == $action_argv_id + 2) {
2231 $itemid = intval(defaults($a->argv, $action_argv_id + 1, 0));
2233 $itemid = intval(defaults($_REQUEST, 'id', 0));
2236 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2238 if (!DBA::isResult($item)) {
2239 throw new BadRequestException("Invalid item.");
2244 $item['starred'] = 1;
2247 $item['starred'] = 0;
2250 throw new BadRequestException("Invalid action ".$action);
2253 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2256 throw new InternalServerErrorException("DB error");
2260 $user_info = api_get_user($a);
2261 $rets = api_format_items([$item], $user_info, false, $type);
2264 $data = ['status' => $ret];
2269 $data = api_rss_extra($a, $data, $user_info);
2273 return api_format_data("status", $type, $data);
2276 /// @TODO move to top of file or somewhere better
2277 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2278 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2281 * Returns the most recent favorite statuses.
2283 * @param string $type Return type (atom, rss, xml, json)
2285 * @return string|array
2287 function api_favorites($type)
2292 $user_info = api_get_user($a);
2294 if (api_user() === false || $user_info === false) {
2295 throw new ForbiddenException();
2300 // in friendica starred item are private
2301 // return favorites only for self
2302 Logger::log('api_favorites: self:' . $user_info['self']);
2304 if ($user_info['self'] == 0) {
2308 $since_id = defaults($_REQUEST, 'since_id', 0);
2309 $max_id = defaults($_REQUEST, 'max_id', 0);
2310 $count = defaults($_GET, 'count', 20);
2311 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
2316 $start = $page*$count;
2318 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2319 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2321 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2324 $condition[0] .= " AND `item`.`id` <= ?";
2325 $condition[] = $max_id;
2328 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2330 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2333 $data = ['status' => $ret];
2338 $data = api_rss_extra($a, $data, $user_info);
2342 return api_format_data("statuses", $type, $data);
2345 /// @TODO move to top of file or somewhere better
2346 api_register_func('api/favorites', 'api_favorites', true);
2350 * @param array $item
2351 * @param array $recipient
2352 * @param array $sender
2356 function api_format_messages($item, $recipient, $sender)
2358 // standard meta information
2360 'id' => $item['id'],
2361 'sender_id' => $sender['id'],
2363 'recipient_id' => $recipient['id'],
2364 'created_at' => api_date(defaults($item, 'created', DateTimeFormat::utcNow())),
2365 'sender_screen_name' => $sender['screen_name'],
2366 'recipient_screen_name' => $recipient['screen_name'],
2367 'sender' => $sender,
2368 'recipient' => $recipient,
2370 'friendica_seen' => defaults($item, 'seen', 0),
2371 'friendica_parent_uri' => defaults($item, 'parent-uri', ''),
2374 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2375 if (isset($ret['sender']['uid'])) {
2376 unset($ret['sender']['uid']);
2378 if (isset($ret['sender']['self'])) {
2379 unset($ret['sender']['self']);
2381 if (isset($ret['recipient']['uid'])) {
2382 unset($ret['recipient']['uid']);
2384 if (isset($ret['recipient']['self'])) {
2385 unset($ret['recipient']['self']);
2388 //don't send title to regular StatusNET requests to avoid confusing these apps
2389 if (!empty($_GET['getText'])) {
2390 $ret['title'] = $item['title'];
2391 if ($_GET['getText'] == 'html') {
2392 $ret['text'] = BBCode::convert($item['body'], false);
2393 } elseif ($_GET['getText'] == 'plain') {
2394 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2397 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2399 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2400 unset($ret['sender']);
2401 unset($ret['recipient']);
2409 * @param array $item
2413 function api_convert_item($item)
2415 $body = $item['body'];
2416 $attachments = api_get_attachments($body);
2418 // Workaround for ostatus messages where the title is identically to the body
2419 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2420 $statusbody = trim(HTML::toPlaintext($html, 0));
2422 // handle data: images
2423 $statusbody = api_format_items_embeded_images($item, $statusbody);
2425 $statustitle = trim($item['title']);
2427 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2428 $statustext = trim($statusbody);
2430 $statustext = trim($statustitle."\n\n".$statusbody);
2433 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($statustext)> 1000)) {
2434 $statustext = substr($statustext, 0, 1000) . "... \n" . defaults($item, 'plink', '');
2437 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2439 // Workaround for clients with limited HTML parser functionality
2440 $search = ["<br>", "<blockquote>", "</blockquote>",
2441 "<h1>", "</h1>", "<h2>", "</h2>",
2442 "<h3>", "</h3>", "<h4>", "</h4>",
2443 "<h5>", "</h5>", "<h6>", "</h6>"];
2444 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2445 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2446 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2447 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2448 $statushtml = str_replace($search, $replace, $statushtml);
2450 if ($item['title'] != "") {
2451 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2455 $oldtext = $statushtml;
2456 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2457 } while ($oldtext != $statushtml);
2459 if (substr($statushtml, 0, 4) == '<br>') {
2460 $statushtml = substr($statushtml, 4);
2463 if (substr($statushtml, 0, -4) == '<br>') {
2464 $statushtml = substr($statushtml, -4);
2467 // feeds without body should contain the link
2468 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2469 $statushtml .= BBCode::convert($item['plink']);
2472 $entities = api_get_entitities($statustext, $body);
2475 "text" => $statustext,
2476 "html" => $statushtml,
2477 "attachments" => $attachments,
2478 "entities" => $entities
2484 * @param string $body
2488 function api_get_attachments(&$body)
2491 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2493 $URLSearchString = "^\[\]";
2494 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2502 foreach ($images[1] as $image) {
2503 $imagedata = Image::getInfoFromURL($image);
2506 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2510 if (strstr(defaults($_SERVER, 'HTTP_USER_AGENT', ''), "AndStatus")) {
2511 foreach ($images[0] as $orig) {
2512 $body = str_replace($orig, "", $body);
2516 return $attachments;
2521 * @param string $text
2522 * @param string $bbcode
2525 * @todo Links at the first character of the post
2527 function api_get_entitities(&$text, $bbcode)
2529 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
2531 if ($include_entities != "true") {
2532 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2534 foreach ($images[1] as $image) {
2535 $replace = ProxyUtils::proxifyUrl($image);
2536 $text = str_replace($image, $replace, $text);
2541 $bbcode = BBCode::cleanPictureLinks($bbcode);
2543 // Change pure links in text to bbcode uris
2544 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2547 $entities["hashtags"] = [];
2548 $entities["symbols"] = [];
2549 $entities["urls"] = [];
2550 $entities["user_mentions"] = [];
2552 $URLSearchString = "^\[\]";
2554 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2556 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2557 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2558 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2560 $bbcode = preg_replace(
2561 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2562 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2565 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2567 $bbcode = preg_replace(
2568 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2569 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2572 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2574 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2576 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2577 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2580 foreach ($urls[1] as $id => $url) {
2581 //$start = strpos($text, $url, $offset);
2582 $start = iconv_strpos($text, $url, 0, "UTF-8");
2583 if (!($start === false)) {
2584 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2588 ksort($ordered_urls);
2591 //foreach ($urls[1] AS $id=>$url) {
2592 foreach ($ordered_urls as $url) {
2593 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2594 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2596 $display_url = $url["title"];
2598 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2599 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2601 if (strlen($display_url) > 26) {
2602 $display_url = substr($display_url, 0, 25)."…";
2606 //$start = strpos($text, $url, $offset);
2607 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2608 if (!($start === false)) {
2609 $entities["urls"][] = ["url" => $url["url"],
2610 "expanded_url" => $url["url"],
2611 "display_url" => $display_url,
2612 "indices" => [$start, $start+strlen($url["url"])]];
2613 $offset = $start + 1;
2617 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2618 $ordered_images = [];
2619 foreach ($images[1] as $image) {
2620 //$start = strpos($text, $url, $offset);
2621 $start = iconv_strpos($text, $image, 0, "UTF-8");
2622 if (!($start === false)) {
2623 $ordered_images[$start] = $image;
2626 //$entities["media"] = array();
2629 foreach ($ordered_images as $url) {
2630 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2631 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2633 if (strlen($display_url) > 26) {
2634 $display_url = substr($display_url, 0, 25)."…";
2637 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2638 if (!($start === false)) {
2639 $image = Image::getInfoFromURL($url);
2641 // If image cache is activated, then use the following sizes:
2642 // thumb (150), small (340), medium (600) and large (1024)
2643 if (!Config::get("system", "proxy_disabled")) {
2644 $media_url = ProxyUtils::proxifyUrl($url);
2647 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2648 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2650 if (($image[0] > 150) || ($image[1] > 150)) {
2651 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2652 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2655 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2656 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2658 if (($image[0] > 600) || ($image[1] > 600)) {
2659 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2660 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2664 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2667 $entities["media"][] = [
2669 "id_str" => (string)$start+1,
2670 "indices" => [$start, $start+strlen($url)],
2671 "media_url" => Strings::normaliseLink($media_url),
2672 "media_url_https" => $media_url,
2674 "display_url" => $display_url,
2675 "expanded_url" => $url,
2679 $offset = $start + 1;
2688 * @param array $item
2689 * @param string $text
2693 function api_format_items_embeded_images($item, $text)
2695 $text = preg_replace_callback(
2696 '|data:image/([^;]+)[^=]+=*|m',
2697 function () use ($item) {
2698 return System::baseUrl() . '/display/' . $item['guid'];
2706 * @brief return <a href='url'>name</a> as array
2708 * @param string $txt text
2713 function api_contactlink_to_array($txt)
2716 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2717 if ($r && count($match)==3) {
2719 'name' => $match[2],
2733 * @brief return likes, dislikes and attend status for item
2735 * @param array $item array
2736 * @param string $type Return type (atom, rss, xml, json)
2739 * likes => int count,
2740 * dislikes => int count
2742 function api_format_items_activities($item, $type = "json")
2751 'attendmaybe' => [],
2754 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2755 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2757 while ($parent_item = Item::fetch($ret)) {
2758 // not used as result should be structured like other user data
2759 //builtin_activity_puller($i, $activities);
2761 // get user data and add it to the array of the activity
2762 $user = api_get_user($a, $parent_item['author-id']);
2763 switch ($parent_item['verb']) {
2765 $activities['like'][] = $user;
2767 case ACTIVITY_DISLIKE:
2768 $activities['dislike'][] = $user;
2770 case ACTIVITY_ATTEND:
2771 $activities['attendyes'][] = $user;
2773 case ACTIVITY_ATTENDNO:
2774 $activities['attendno'][] = $user;
2776 case ACTIVITY_ATTENDMAYBE:
2777 $activities['attendmaybe'][] = $user;
2786 if ($type == "xml") {
2787 $xml_activities = [];
2788 foreach ($activities as $k => $v) {
2789 // change xml element from "like" to "friendica:like"
2790 $xml_activities["friendica:".$k] = $v;
2791 // add user data into xml output
2793 foreach ($v as $user) {
2794 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2797 $activities = $xml_activities;
2805 * @brief return data from profiles
2807 * @param array $profile_row array containing data from db table 'profile'
2810 function api_format_items_profiles($profile_row)
2813 'profile_id' => $profile_row['id'],
2814 'profile_name' => $profile_row['profile-name'],
2815 'is_default' => $profile_row['is-default'] ? true : false,
2816 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2817 'profile_photo' => $profile_row['photo'],
2818 'profile_thumb' => $profile_row['thumb'],
2819 'publish' => $profile_row['publish'] ? true : false,
2820 'net_publish' => $profile_row['net-publish'] ? true : false,
2821 'description' => $profile_row['pdesc'],
2822 'date_of_birth' => $profile_row['dob'],
2823 'address' => $profile_row['address'],
2824 'city' => $profile_row['locality'],
2825 'region' => $profile_row['region'],
2826 'postal_code' => $profile_row['postal-code'],
2827 'country' => $profile_row['country-name'],
2828 'hometown' => $profile_row['hometown'],
2829 'gender' => $profile_row['gender'],
2830 'marital' => $profile_row['marital'],
2831 'marital_with' => $profile_row['with'],
2832 'marital_since' => $profile_row['howlong'],
2833 'sexual' => $profile_row['sexual'],
2834 'politic' => $profile_row['politic'],
2835 'religion' => $profile_row['religion'],
2836 'public_keywords' => $profile_row['pub_keywords'],
2837 'private_keywords' => $profile_row['prv_keywords'],
2838 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2839 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2840 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2841 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2842 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2843 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2844 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2845 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2846 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2847 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2848 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2849 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2850 'homepage' => $profile_row['homepage'],
2857 * @brief format items to be returned by api
2859 * @param array $r array of items
2860 * @param array $user_info
2861 * @param bool $filter_user filter items by $user_info
2862 * @param string $type Return type (atom, rss, xml, json)
2864 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2870 foreach ($r as $item) {
2871 localize_item($item);
2872 list($status_user, $owner_user) = api_item_get_user($a, $item);
2874 // Look if the posts are matching if they should be filtered by user id
2875 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2879 $in_reply_to = api_in_reply_to($item);
2881 $converted = api_convert_item($item);
2883 if ($type == "xml") {
2884 $geo = "georss:point";
2890 'text' => $converted["text"],
2891 'truncated' => false,
2892 'created_at'=> api_date($item['created']),
2893 'in_reply_to_status_id' => $in_reply_to['status_id'],
2894 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2895 'source' => (($item['app']) ? $item['app'] : 'web'),
2896 'id' => intval($item['id']),
2897 'id_str' => (string) intval($item['id']),
2898 'in_reply_to_user_id' => $in_reply_to['user_id'],
2899 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2900 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2902 'favorited' => $item['starred'] ? true : false,
2903 'user' => $status_user,
2904 'friendica_owner' => $owner_user,
2905 'friendica_private' => $item['private'] == 1,
2906 //'entities' => NULL,
2907 'statusnet_html' => $converted["html"],
2908 'statusnet_conversation_id' => $item['parent'],
2909 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2910 'friendica_activities' => api_format_items_activities($item, $type),
2913 if (count($converted["attachments"]) > 0) {
2914 $status["attachments"] = $converted["attachments"];
2917 if (count($converted["entities"]) > 0) {
2918 $status["entities"] = $converted["entities"];
2921 if ($status["source"] == 'web') {
2922 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
2923 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
2924 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
2927 if ($item["id"] == $item["parent"]) {
2928 $retweeted_item = api_share_as_retweet($item);
2929 if ($retweeted_item !== false) {
2930 $retweeted_status = $status;
2931 $status['user'] = $status['friendica_owner'];
2933 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
2934 } catch (BadRequestException $e) {
2935 // user not found. should be found?
2936 /// @todo check if the user should be always found
2937 $retweeted_status["user"] = [];
2940 $rt_converted = api_convert_item($retweeted_item);
2942 $retweeted_status['text'] = $rt_converted["text"];
2943 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2944 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2945 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2946 $status['retweeted_status'] = $retweeted_status;
2950 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2951 unset($status["user"]["uid"]);
2952 unset($status["user"]["self"]);
2954 if ($item["coord"] != "") {
2955 $coords = explode(' ', $item["coord"]);
2956 if (count($coords) == 2) {
2957 if ($type == "json") {
2958 $status["geo"] = ['type' => 'Point',
2959 'coordinates' => [(float) $coords[0],
2960 (float) $coords[1]]];
2961 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2962 $status["georss:point"] = $item["coord"];
2972 * Returns the remaining number of API requests available to the user before the API limit is reached.
2974 * @param string $type Return type (atom, rss, xml, json)
2976 * @return array|string
2978 function api_account_rate_limit_status($type)
2980 if ($type == "xml") {
2982 'remaining-hits' => '150',
2983 '@attributes' => ["type" => "integer"],
2984 'hourly-limit' => '150',
2985 '@attributes2' => ["type" => "integer"],
2986 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
2987 '@attributes3' => ["type" => "datetime"],
2988 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2989 '@attributes4' => ["type" => "integer"],
2993 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2994 'remaining_hits' => '150',
2995 'hourly_limit' => '150',
2996 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3000 return api_format_data('hash', $type, ['hash' => $hash]);
3003 /// @TODO move to top of file or somewhere better
3004 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3007 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3009 * @param string $type Return type (atom, rss, xml, json)
3011 * @return array|string
3013 function api_help_test($type)
3015 if ($type == 'xml') {
3021 return api_format_data('ok', $type, ["ok" => $ok]);
3024 /// @TODO move to top of file or somewhere better
3025 api_register_func('api/help/test', 'api_help_test', false);
3028 * Returns all lists the user subscribes to.
3030 * @param string $type Return type (atom, rss, xml, json)
3032 * @return array|string
3033 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3035 function api_lists_list($type)
3038 /// @TODO $ret is not filled here?
3039 return api_format_data('lists', $type, ["lists_list" => $ret]);
3042 /// @TODO move to top of file or somewhere better
3043 api_register_func('api/lists/list', 'api_lists_list', true);
3044 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3047 * Returns all groups the user owns.
3049 * @param string $type Return type (atom, rss, xml, json)
3051 * @return array|string
3052 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3054 function api_lists_ownerships($type)
3058 if (api_user() === false) {
3059 throw new ForbiddenException();
3063 $user_info = api_get_user($a);
3064 $uid = $user_info['uid'];
3066 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3068 // loop through all groups
3070 foreach ($groups as $group) {
3071 if ($group['visible']) {
3077 'name' => $group['name'],
3078 'id' => intval($group['id']),
3079 'id_str' => (string) $group['id'],
3080 'user' => $user_info,
3084 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3087 /// @TODO move to top of file or somewhere better
3088 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3091 * Returns recent statuses from users in the specified group.
3093 * @param string $type Return type (atom, rss, xml, json)
3095 * @return array|string
3096 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3098 function api_lists_statuses($type)
3102 $user_info = api_get_user($a);
3103 if (api_user() === false || $user_info === false) {
3104 throw new ForbiddenException();
3107 unset($_REQUEST["user_id"]);
3108 unset($_GET["user_id"]);
3110 unset($_REQUEST["screen_name"]);
3111 unset($_GET["screen_name"]);
3113 if (empty($_REQUEST['list_id'])) {
3114 throw new BadRequestException('list_id not specified');
3118 $count = defaults($_REQUEST, 'count', 20);
3119 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
3123 $since_id = defaults($_REQUEST, 'since_id', 0);
3124 $max_id = defaults($_REQUEST, 'max_id', 0);
3125 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3126 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
3128 $start = $page * $count;
3130 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3131 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3134 $condition[0] .= " AND `item`.`id` <= ?";
3135 $condition[] = $max_id;
3137 if ($exclude_replies > 0) {
3138 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3140 if ($conversation_id > 0) {
3141 $condition[0] .= " AND `item`.`parent` = ?";
3142 $condition[] = $conversation_id;
3145 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3146 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3148 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3150 $data = ['status' => $items];
3155 $data = api_rss_extra($a, $data, $user_info);
3159 return api_format_data("statuses", $type, $data);
3162 /// @TODO move to top of file or somewhere better
3163 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3166 * Considers friends and followers lists to be private and won't return
3167 * anything if any user_id parameter is passed.
3169 * @brief Returns either the friends of the follower list
3171 * @param string $qtype Either "friends" or "followers"
3172 * @return boolean|array
3173 * @throws ForbiddenException
3175 function api_statuses_f($qtype)
3179 if (api_user() === false) {
3180 throw new ForbiddenException();
3184 $count = defaults($_GET, 'count', 20);
3185 $page = defaults($_GET, 'page', 1);
3189 $start = ($page - 1) * $count;
3191 $user_info = api_get_user($a);
3193 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3194 /* this is to stop Hotot to load friends multiple times
3195 * I'm not sure if I'm missing return something or
3196 * is a bug in hotot. Workaround, meantime
3200 return array('$users' => $ret);*/
3205 if ($qtype == 'friends') {
3206 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3207 } elseif ($qtype == 'followers') {
3208 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3211 // friends and followers only for self
3212 if ($user_info['self'] == 0) {
3213 $sql_extra = " AND false ";
3216 if ($qtype == 'blocks') {
3217 $sql_filter = 'AND `blocked` AND NOT `pending`';
3218 } elseif ($qtype == 'incoming') {
3219 $sql_filter = 'AND `pending`';
3221 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3239 foreach ($r as $cid) {
3240 $user = api_get_user($a, $cid['nurl']);
3241 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3242 unset($user["uid"]);
3243 unset($user["self"]);
3250 return ['user' => $ret];
3255 * Returns the user's friends.
3257 * @brief Returns the list of friends of the provided user
3259 * @deprecated By Twitter API in favor of friends/list
3261 * @param string $type Either "json" or "xml"
3262 * @return boolean|string|array
3264 function api_statuses_friends($type)
3266 $data = api_statuses_f("friends");
3267 if ($data === false) {
3270 return api_format_data("users", $type, $data);
3274 * Returns the user's followers.
3276 * @brief Returns the list of followers of the provided user
3278 * @deprecated By Twitter API in favor of friends/list
3280 * @param string $type Either "json" or "xml"
3281 * @return boolean|string|array
3283 function api_statuses_followers($type)
3285 $data = api_statuses_f("followers");
3286 if ($data === false) {
3289 return api_format_data("users", $type, $data);
3292 /// @TODO move to top of file or somewhere better
3293 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3294 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3297 * Returns the list of blocked users
3299 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3301 * @param string $type Either "json" or "xml"
3303 * @return boolean|string|array
3305 function api_blocks_list($type)
3307 $data = api_statuses_f('blocks');
3308 if ($data === false) {
3311 return api_format_data("users", $type, $data);
3314 /// @TODO move to top of file or somewhere better
3315 api_register_func('api/blocks/list', 'api_blocks_list', true);
3318 * Returns the list of pending users IDs
3320 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3322 * @param string $type Either "json" or "xml"
3324 * @return boolean|string|array
3326 function api_friendships_incoming($type)
3328 $data = api_statuses_f('incoming');
3329 if ($data === false) {
3334 foreach ($data['user'] as $user) {
3335 $ids[] = $user['id'];
3338 return api_format_data("ids", $type, ['id' => $ids]);
3341 /// @TODO move to top of file or somewhere better
3342 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3345 * Returns the instance's configuration information.
3347 * @param string $type Return type (atom, rss, xml, json)
3349 * @return array|string
3351 function api_statusnet_config($type)
3355 $name = Config::get('config', 'sitename');
3356 $server = $a->getHostName();
3357 $logo = System::baseUrl() . '/images/friendica-64.png';
3358 $email = Config::get('config', 'admin_email');
3359 $closed = intval(Config::get('config', 'register_policy')) === REGISTER_CLOSED ? 'true' : 'false';
3360 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3361 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3362 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3363 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3366 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3367 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3368 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3369 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3370 'shorturllength' => '30',
3372 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3373 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3374 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3375 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3380 return api_format_data('config', $type, ['config' => $config]);
3383 /// @TODO move to top of file or somewhere better
3384 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3385 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3389 * @param string $type Return type (atom, rss, xml, json)
3391 * @return array|string
3393 function api_statusnet_version($type)
3396 $fake_statusnet_version = "0.9.7";
3398 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3401 /// @TODO move to top of file or somewhere better
3402 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3403 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3407 * @param string $type Return type (atom, rss, xml, json)
3409 * @todo use api_format_data() to return data
3411 function api_ff_ids($type)
3414 throw new ForbiddenException();
3421 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3424 "SELECT `pcontact`.`id` FROM `contact`
3425 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3426 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3429 if (!DBA::isResult($r)) {
3434 foreach ($r as $rr) {
3435 if ($stringify_ids) {
3438 $ids[] = intval($rr['id']);
3442 return api_format_data("ids", $type, ['id' => $ids]);
3446 * Returns the ID of every user the user is following.
3448 * @param string $type Return type (atom, rss, xml, json)
3450 * @return array|string
3451 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3453 function api_friends_ids($type)
3455 return api_ff_ids($type);
3459 * Returns the ID of every user following the user.
3461 * @param string $type Return type (atom, rss, xml, json)
3463 * @return array|string
3464 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3466 function api_followers_ids($type)
3468 return api_ff_ids($type);
3471 /// @TODO move to top of file or somewhere better
3472 api_register_func('api/friends/ids', 'api_friends_ids', true);
3473 api_register_func('api/followers/ids', 'api_followers_ids', true);
3476 * Sends a new direct message.
3478 * @param string $type Return type (atom, rss, xml, json)
3480 * @return array|string
3481 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3483 function api_direct_messages_new($type)
3487 if (api_user() === false) {
3488 throw new ForbiddenException();
3491 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3495 $sender = api_get_user($a);
3498 if (!empty($_POST['screen_name'])) {
3500 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3502 DBA::escape($_POST['screen_name'])
3505 if (DBA::isResult($r)) {
3506 // Selecting the id by priority, friendica first
3507 api_best_nickname($r);
3509 $recipient = api_get_user($a, $r[0]['nurl']);
3512 $recipient = api_get_user($a, $_POST['user_id']);
3515 if (empty($recipient)) {
3516 throw new NotFoundException('Recipient not found');
3521 if (!empty($_REQUEST['replyto'])) {
3523 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3525 intval($_REQUEST['replyto'])
3527 $replyto = $r[0]['parent-uri'];
3528 $sub = $r[0]['title'];
3530 if (!empty($_REQUEST['title'])) {
3531 $sub = $_REQUEST['title'];
3533 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3537 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3540 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3541 $ret = api_format_messages($r[0], $recipient, $sender);
3543 $ret = ["error"=>$id];
3546 $data = ['direct_message'=>$ret];
3552 $data = api_rss_extra($a, $data, $sender);
3556 return api_format_data("direct-messages", $type, $data);
3559 /// @TODO move to top of file or somewhere better
3560 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3563 * Destroys a direct message.
3565 * @brief delete a direct_message from mail table through api
3567 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3568 * @return string|array
3569 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3571 function api_direct_messages_destroy($type)
3575 if (api_user() === false) {
3576 throw new ForbiddenException();
3580 $user_info = api_get_user($a);
3582 $id = defaults($_REQUEST, 'id', 0);
3584 $parenturi = defaults($_REQUEST, 'friendica_parenturi', "");
3585 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3586 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3588 $uid = $user_info['uid'];
3589 // error if no id or parenturi specified (for clients posting parent-uri as well)
3590 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3591 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3592 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3595 // BadRequestException if no id specified (for clients using Twitter API)
3597 throw new BadRequestException('Message id not specified');
3600 // add parent-uri to sql command if specified by calling app
3601 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3603 // get data of the specified message id
3605 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3610 // error message if specified id is not in database
3611 if (!DBA::isResult($r)) {
3612 if ($verbose == "true") {
3613 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3614 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3616 /// @todo BadRequestException ok for Twitter API clients?
3617 throw new BadRequestException('message id not in database');
3622 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3627 if ($verbose == "true") {
3630 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3631 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3633 $answer = ['result' => 'error', 'message' => 'unknown error'];
3634 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3637 /// @todo return JSON data like Twitter API not yet implemented
3640 /// @TODO move to top of file or somewhere better
3641 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3646 * @brief unfollow contact
3648 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3649 * @return string|array
3650 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3652 function api_friendships_destroy($type)
3656 if ($uid === false) {
3657 throw new ForbiddenException();
3660 $contact_id = defaults($_REQUEST, 'user_id');
3662 if (empty($contact_id)) {
3663 Logger::log("No user_id specified", Logger::DEBUG);
3664 throw new BadRequestException("no user_id specified");
3667 // Get Contact by given id
3668 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3670 if(!DBA::isResult($contact)) {
3671 Logger::log("No contact found for ID" . $contact_id, Logger::DEBUG);
3672 throw new NotFoundException("no contact found to given ID");
3675 $url = $contact["url"];
3677 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3678 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3679 Strings::normaliseLink($url), $url];
3680 $contact = DBA::selectFirst('contact', [], $condition);
3682 if (!DBA::isResult($contact)) {
3683 Logger::log("Not following Contact", Logger::DEBUG);
3684 throw new NotFoundException("Not following Contact");
3687 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3688 Logger::log("Not supported", Logger::DEBUG);
3689 throw new ExpectationFailedException("Not supported");
3692 $dissolve = ($contact['rel'] == Contact::SHARING);
3694 $owner = User::getOwnerDataById($uid);
3696 Contact::terminateFriendship($owner, $contact, $dissolve);
3699 Logger::log("No owner found", Logger::DEBUG);
3700 throw new NotFoundException("Error Processing Request");
3703 // Sharing-only contacts get deleted as there no relationship any more
3705 Contact::remove($contact['id']);
3707 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3710 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3711 unset($contact["uid"]);
3712 unset($contact["self"]);
3714 // Set screen_name since Twidere requests it
3715 $contact["screen_name"] = $contact["nick"];
3717 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3719 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3723 * @param string $type Return type (atom, rss, xml, json)
3724 * @param string $box
3725 * @param string $verbose
3727 * @return array|string
3729 function api_direct_messages_box($type, $box, $verbose)
3732 if (api_user() === false) {
3733 throw new ForbiddenException();
3736 $count = defaults($_GET, 'count', 20);
3737 $page = defaults($_REQUEST, 'page', 1) - 1;
3742 $since_id = defaults($_REQUEST, 'since_id', 0);
3743 $max_id = defaults($_REQUEST, 'max_id', 0);
3745 $user_id = defaults($_REQUEST, 'user_id', '');
3746 $screen_name = defaults($_REQUEST, 'screen_name', '');
3749 unset($_REQUEST["user_id"]);
3750 unset($_GET["user_id"]);
3752 unset($_REQUEST["screen_name"]);
3753 unset($_GET["screen_name"]);
3755 $user_info = api_get_user($a);
3756 if ($user_info === false) {
3757 throw new ForbiddenException();
3759 $profile_url = $user_info["url"];
3762 $start = $page * $count;
3767 if ($box=="sentbox") {
3768 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3769 } elseif ($box == "conversation") {
3770 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape(defaults($_GET, 'uri', '')) . "'";
3771 } elseif ($box == "all") {
3772 $sql_extra = "true";
3773 } elseif ($box == "inbox") {
3774 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3778 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3781 if ($user_id != "") {
3782 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3783 } elseif ($screen_name !="") {
3784 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3788 "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",
3794 if ($verbose == "true" && !DBA::isResult($r)) {
3795 $answer = ['result' => 'error', 'message' => 'no mails available'];
3796 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3800 foreach ($r as $item) {
3801 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3802 $recipient = $user_info;
3803 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3804 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3805 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3806 $sender = $user_info;
3809 if (isset($recipient) && isset($sender)) {
3810 $ret[] = api_format_messages($item, $recipient, $sender);
3815 $data = ['direct_message' => $ret];
3820 $data = api_rss_extra($a, $data, $user_info);
3824 return api_format_data("direct-messages", $type, $data);
3828 * Returns the most recent direct messages sent by the user.
3830 * @param string $type Return type (atom, rss, xml, json)
3832 * @return array|string
3833 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3835 function api_direct_messages_sentbox($type)
3837 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3838 return api_direct_messages_box($type, "sentbox", $verbose);
3842 * Returns the most recent direct messages sent to the user.
3844 * @param string $type Return type (atom, rss, xml, json)
3846 * @return array|string
3847 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3849 function api_direct_messages_inbox($type)
3851 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3852 return api_direct_messages_box($type, "inbox", $verbose);
3857 * @param string $type Return type (atom, rss, xml, json)
3859 * @return array|string
3861 function api_direct_messages_all($type)
3863 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3864 return api_direct_messages_box($type, "all", $verbose);
3869 * @param string $type Return type (atom, rss, xml, json)
3871 * @return array|string
3873 function api_direct_messages_conversation($type)
3875 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3876 return api_direct_messages_box($type, "conversation", $verbose);
3879 /// @TODO move to top of file or somewhere better
3880 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3881 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3882 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3883 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3886 * Returns an OAuth Request Token.
3888 * @see https://oauth.net/core/1.0/#auth_step1
3890 function api_oauth_request_token()
3892 $oauth1 = new FKOAuth1();
3894 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3895 } catch (Exception $e) {
3896 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3904 * Returns an OAuth Access Token.
3906 * @return array|string
3907 * @see https://oauth.net/core/1.0/#auth_step3
3909 function api_oauth_access_token()
3911 $oauth1 = new FKOAuth1();
3913 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3914 } catch (Exception $e) {
3915 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3922 /// @TODO move to top of file or somewhere better
3923 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3924 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3928 * @brief delete a complete photoalbum with all containing photos from database through api
3930 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3931 * @return string|array
3933 function api_fr_photoalbum_delete($type)
3935 if (api_user() === false) {
3936 throw new ForbiddenException();
3939 $album = defaults($_REQUEST, 'album', "");
3941 // we do not allow calls without album string
3943 throw new BadRequestException("no albumname specified");
3945 // check if album is existing
3947 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3951 if (!DBA::isResult($r)) {
3952 throw new BadRequestException("album not available");
3955 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3956 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3957 foreach ($r as $rr) {
3958 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
3959 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
3961 if (!DBA::isResult($photo_item)) {
3962 throw new InternalServerErrorException("problem with deleting items occured");
3964 Item::deleteForUser(['id' => $photo_item['id']], api_user());
3967 // now let's delete all photos from the album
3968 $result = DBA::delete('photo', ['uid' => api_user(), 'album' => $album]);
3970 // return success of deletion or error message
3972 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
3973 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
3975 throw new InternalServerErrorException("unknown error - deleting from database failed");
3980 * @brief update the name of the album for all photos of an album
3982 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3983 * @return string|array
3985 function api_fr_photoalbum_update($type)
3987 if (api_user() === false) {
3988 throw new ForbiddenException();
3991 $album = defaults($_REQUEST, 'album', "");
3992 $album_new = defaults($_REQUEST, 'album_new', "");
3994 // we do not allow calls without album string
3996 throw new BadRequestException("no albumname specified");
3998 if ($album_new == "") {
3999 throw new BadRequestException("no new albumname specified");
4001 // check if album is existing
4002 if (!DBA::exists('photo', ['uid' => api_user(), 'album' => $album])) {
4003 throw new BadRequestException("album not available");
4005 // now let's update all photos to the albumname
4006 $result = DBA::update('photo', ['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4008 // return success of updating or error message
4010 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4011 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4013 throw new InternalServerErrorException("unknown error - updating in database failed");
4019 * @brief list all photos of the authenticated user
4021 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4022 * @return string|array
4024 function api_fr_photos_list($type)
4026 if (api_user() === false) {
4027 throw new ForbiddenException();
4030 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4031 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4032 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4033 intval(local_user())
4036 'image/jpeg' => 'jpg',
4037 'image/png' => 'png',
4038 'image/gif' => 'gif'
4040 $data = ['photo'=>[]];
4041 if (DBA::isResult($r)) {
4042 foreach ($r as $rr) {
4044 $photo['id'] = $rr['resource-id'];
4045 $photo['album'] = $rr['album'];
4046 $photo['filename'] = $rr['filename'];
4047 $photo['type'] = $rr['type'];
4048 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4049 $photo['created'] = $rr['created'];
4050 $photo['edited'] = $rr['edited'];
4051 $photo['desc'] = $rr['desc'];
4053 if ($type == "xml") {
4054 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4056 $photo['thumb'] = $thumb;
4057 $data['photo'][] = $photo;
4061 return api_format_data("photos", $type, $data);
4065 * @brief upload a new photo or change an existing photo
4067 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4068 * @return string|array
4070 function api_fr_photo_create_update($type)
4072 if (api_user() === false) {
4073 throw new ForbiddenException();
4076 $photo_id = defaults($_REQUEST, 'photo_id', null);
4077 $desc = defaults($_REQUEST, 'desc', (array_key_exists('desc', $_REQUEST) ? "" : null)) ; // extra check necessary to distinguish between 'not provided' and 'empty string'
4078 $album = defaults($_REQUEST, 'album', null);
4079 $album_new = defaults($_REQUEST, 'album_new', null);
4080 $allow_cid = defaults($_REQUEST, 'allow_cid', (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4081 $deny_cid = defaults($_REQUEST, 'deny_cid' , (array_key_exists('deny_cid' , $_REQUEST) ? " " : null));
4082 $allow_gid = defaults($_REQUEST, 'allow_gid', (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4083 $deny_gid = defaults($_REQUEST, 'deny_gid' , (array_key_exists('deny_gid' , $_REQUEST) ? " " : null));
4084 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4086 // do several checks on input parameters
4087 // we do not allow calls without album string
4088 if ($album == null) {
4089 throw new BadRequestException("no albumname specified");
4091 // if photo_id == null --> we are uploading a new photo
4092 if ($photo_id == null) {
4095 // error if no media posted in create-mode
4096 if (empty($_FILES['media'])) {
4098 throw new BadRequestException("no media data submitted");
4101 // album_new will be ignored in create-mode
4106 // check if photo is existing in database
4108 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4110 DBA::escape($photo_id),
4113 if (!DBA::isResult($r)) {
4114 throw new BadRequestException("photo not available");
4118 // checks on acl strings provided by clients
4119 $acl_input_error = false;
4120 $acl_input_error |= check_acl_input($allow_cid);
4121 $acl_input_error |= check_acl_input($deny_cid);
4122 $acl_input_error |= check_acl_input($allow_gid);
4123 $acl_input_error |= check_acl_input($deny_gid);
4124 if ($acl_input_error) {
4125 throw new BadRequestException("acl data invalid");
4127 // now let's upload the new media in create-mode
4128 if ($mode == "create") {
4129 $media = $_FILES['media'];
4130 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4132 // return success of updating or error message
4133 if (!is_null($data)) {
4134 return api_format_data("photo_create", $type, $data);
4136 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4140 // now let's do the changes in update-mode
4141 if ($mode == "update") {
4144 if (!is_null($desc)) {
4145 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4148 if (!is_null($album_new)) {
4149 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4152 if (!is_null($allow_cid)) {
4153 $allow_cid = trim($allow_cid);
4154 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4157 if (!is_null($deny_cid)) {
4158 $deny_cid = trim($deny_cid);
4159 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4162 if (!is_null($allow_gid)) {
4163 $allow_gid = trim($allow_gid);
4164 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4167 if (!is_null($deny_gid)) {
4168 $deny_gid = trim($deny_gid);
4169 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4173 if ($sql_extra != "") {
4174 $nothingtodo = false;
4176 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4178 DateTimeFormat::utcNow(), // update edited timestamp
4180 DBA::escape($photo_id),
4184 $nothingtodo = true;
4187 if (!empty($_FILES['media'])) {
4188 $nothingtodo = false;
4189 $media = $_FILES['media'];
4190 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4191 if (!is_null($data)) {
4192 return api_format_data("photo_update", $type, $data);
4196 // return success of updating or error message
4198 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4199 return api_format_data("photo_update", $type, ['$result' => $answer]);
4202 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4203 return api_format_data("photo_update", $type, ['$result' => $answer]);
4205 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4208 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4212 * @brief delete a single photo from the database through api
4214 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4215 * @return string|array
4217 function api_fr_photo_delete($type)
4219 if (api_user() === false) {
4220 throw new ForbiddenException();
4223 $photo_id = defaults($_REQUEST, 'photo_id', null);
4225 // do several checks on input parameters
4226 // we do not allow calls without photo id
4227 if ($photo_id == null) {
4228 throw new BadRequestException("no photo_id specified");
4230 // check if photo is existing in database
4232 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4234 DBA::escape($photo_id)
4236 if (!DBA::isResult($r)) {
4237 throw new BadRequestException("photo not available");
4239 // now we can perform on the deletion of the photo
4240 $result = DBA::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4242 // return success of deletion or error message
4244 // retrieve the id of the parent element (the photo element)
4245 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4246 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4248 if (!DBA::isResult($photo_item)) {
4249 throw new InternalServerErrorException("problem with deleting items occured");
4251 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4252 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4253 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4255 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4256 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4258 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4264 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4266 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4267 * @return string|array
4269 function api_fr_photo_detail($type)
4271 if (api_user() === false) {
4272 throw new ForbiddenException();
4274 if (empty($_REQUEST['photo_id'])) {
4275 throw new BadRequestException("No photo id.");
4278 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4279 $photo_id = $_REQUEST['photo_id'];
4281 // prepare json/xml output with data from database for the requested photo
4282 $data = prepare_photo_data($type, $scale, $photo_id);
4284 return api_format_data("photo_detail", $type, $data);
4289 * Updates the user’s profile image.
4291 * @brief updates the profile image for the user (either a specified profile or the default profile)
4293 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4295 * @return string|array
4296 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4298 function api_account_update_profile_image($type)
4300 if (api_user() === false) {
4301 throw new ForbiddenException();
4304 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4306 // error if image data is missing
4307 if (empty($_FILES['image'])) {
4308 throw new BadRequestException("no media data submitted");
4311 // check if specified profile id is valid
4312 if ($profile_id != 0) {
4313 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4314 // error message if specified profile id is not in database
4315 if (!DBA::isResult($profile)) {
4316 throw new BadRequestException("profile_id not available");
4318 $is_default_profile = $profile['is-default'];
4320 $is_default_profile = 1;
4323 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4325 if (!empty($_FILES['image'])) {
4326 $media = $_FILES['image'];
4327 } elseif (!empty($_FILES['media'])) {
4328 $media = $_FILES['media'];
4330 // save new profile image
4331 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4334 if (is_array($media['type'])) {
4335 $filetype = $media['type'][0];
4337 $filetype = $media['type'];
4339 if ($filetype == "image/jpeg") {
4341 } elseif ($filetype == "image/png") {
4344 throw new InternalServerErrorException('Unsupported filetype');
4347 // change specified profile or all profiles to the new resource-id
4348 if ($is_default_profile) {
4349 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4350 DBA::update('photo', ['profile' => false], $condition);
4352 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype,
4353 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype];
4354 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4357 Contact::updateSelfFromUserID(api_user(), true);
4359 // Update global directory in background
4360 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4361 if ($url && strlen(Config::get('system', 'directory'))) {
4362 Worker::add(PRIORITY_LOW, "Directory", $url);
4365 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4367 // output for client
4369 return api_account_verify_credentials($type);
4371 // SaveMediaToDatabase failed for some reason
4372 throw new InternalServerErrorException("image upload failed");
4376 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4377 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4378 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4379 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4380 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4381 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4382 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4383 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4384 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4387 * Update user profile
4389 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4391 * @return array|string
4393 function api_account_update_profile($type)
4395 $local_user = api_user();
4396 $api_user = api_get_user(get_app());
4398 if (!empty($_POST['name'])) {
4399 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4400 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4401 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4402 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4405 if (isset($_POST['description'])) {
4406 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4407 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4408 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4411 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4412 // Update global directory in background
4413 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4414 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4417 return api_account_verify_credentials($type);
4420 /// @TODO move to top of file or somewhere better
4421 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4425 * @param string $acl_string
4427 function check_acl_input($acl_string)
4429 if ($acl_string == null || $acl_string == " ") {
4432 $contact_not_found = false;
4434 // split <x><y><z> into array of cid's
4435 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4437 // check for each cid if it is available on server
4438 $cid_array = $array[0];
4439 foreach ($cid_array as $cid) {
4440 $cid = str_replace("<", "", $cid);
4441 $cid = str_replace(">", "", $cid);
4442 $condition = ['id' => $cid, 'uid' => api_user()];
4443 $contact_not_found |= !DBA::exists('contact', $condition);
4445 return $contact_not_found;
4450 * @param string $mediatype
4451 * @param array $media
4452 * @param string $type
4453 * @param string $album
4454 * @param string $allow_cid
4455 * @param string $deny_cid
4456 * @param string $allow_gid
4457 * @param string $deny_gid
4458 * @param string $desc
4459 * @param integer $profile
4460 * @param boolean $visibility
4461 * @param string $photo_id
4463 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)
4471 if (is_array($media)) {
4472 if (is_array($media['tmp_name'])) {
4473 $src = $media['tmp_name'][0];
4475 $src = $media['tmp_name'];
4477 if (is_array($media['name'])) {
4478 $filename = basename($media['name'][0]);
4480 $filename = basename($media['name']);
4482 if (is_array($media['size'])) {
4483 $filesize = intval($media['size'][0]);
4485 $filesize = intval($media['size']);
4487 if (is_array($media['type'])) {
4488 $filetype = $media['type'][0];
4490 $filetype = $media['type'];
4494 if ($filetype == "") {
4495 $filetype=Image::guessType($filename);
4497 $imagedata = @getimagesize($src);
4499 $filetype = $imagedata['mime'];
4502 "File upload src: " . $src . " - filename: " . $filename .
4503 " - size: " . $filesize . " - type: " . $filetype,
4507 // check if there was a php upload error
4508 if ($filesize == 0 && $media['error'] == 1) {
4509 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4511 // check against max upload size within Friendica instance
4512 $maximagesize = Config::get('system', 'maximagesize');
4513 if ($maximagesize && ($filesize > $maximagesize)) {
4514 $formattedBytes = Strings::formatBytes($maximagesize);
4515 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4518 // create Photo instance with the data of the image
4519 $imagedata = @file_get_contents($src);
4520 $Image = new Image($imagedata, $filetype);
4521 if (!$Image->isValid()) {
4522 throw new InternalServerErrorException("unable to process image data");
4525 // check orientation of image
4526 $Image->orient($src);
4529 // check max length of images on server
4530 $max_length = Config::get('system', 'max_image_length');
4532 $max_length = MAX_IMAGE_LENGTH;
4534 if ($max_length > 0) {
4535 $Image->scaleDown($max_length);
4536 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4538 $width = $Image->getWidth();
4539 $height = $Image->getHeight();
4541 // create a new resource-id if not already provided
4542 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4544 if ($mediatype == "photo") {
4545 // upload normal image (scales 0, 1, 2)
4546 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4548 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4550 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4552 if ($width > 640 || $height > 640) {
4553 $Image->scaleDown(640);
4554 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4556 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4560 if ($width > 320 || $height > 320) {
4561 $Image->scaleDown(320);
4562 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4564 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4567 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4568 } elseif ($mediatype == "profileimage") {
4569 // upload profile image (scales 4, 5, 6)
4570 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4572 if ($width > 300 || $height > 300) {
4573 $Image->scaleDown(300);
4574 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4576 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4580 if ($width > 80 || $height > 80) {
4581 $Image->scaleDown(80);
4582 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4584 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4588 if ($width > 48 || $height > 48) {
4589 $Image->scaleDown(48);
4590 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4592 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4595 $Image->__destruct();
4596 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4599 if (isset($r) && $r) {
4600 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4601 if ($photo_id == null && $mediatype == "photo") {
4602 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4604 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4605 return prepare_photo_data($type, false, $hash);
4607 throw new InternalServerErrorException("image upload failed");
4613 * @param string $hash
4614 * @param string $allow_cid
4615 * @param string $deny_cid
4616 * @param string $allow_gid
4617 * @param string $deny_gid
4618 * @param string $filetype
4619 * @param boolean $visibility
4621 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4623 // get data about the api authenticated user
4624 $uri = Item::newURI(intval(api_user()));
4625 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4628 $arr['guid'] = System::createUUID();
4629 $arr['uid'] = intval(api_user());
4631 $arr['parent-uri'] = $uri;
4632 $arr['type'] = 'photo';
4634 $arr['resource-id'] = $hash;
4635 $arr['contact-id'] = $owner_record['id'];
4636 $arr['owner-name'] = $owner_record['name'];
4637 $arr['owner-link'] = $owner_record['url'];
4638 $arr['owner-avatar'] = $owner_record['thumb'];
4639 $arr['author-name'] = $owner_record['name'];
4640 $arr['author-link'] = $owner_record['url'];
4641 $arr['author-avatar'] = $owner_record['thumb'];
4643 $arr['allow_cid'] = $allow_cid;
4644 $arr['allow_gid'] = $allow_gid;
4645 $arr['deny_cid'] = $deny_cid;
4646 $arr['deny_gid'] = $deny_gid;
4647 $arr['visible'] = $visibility;
4651 'image/jpeg' => 'jpg',
4652 'image/png' => 'png',
4653 'image/gif' => 'gif'
4656 // adds link to the thumbnail scale photo
4657 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4658 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4661 // do the magic for storing the item in the database and trigger the federation to other contacts
4667 * @param string $type
4669 * @param string $photo_id
4673 function prepare_photo_data($type, $scale, $photo_id)
4676 $user_info = api_get_user($a);
4678 if ($user_info === false) {
4679 throw new ForbiddenException();
4682 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4683 $data_sql = ($scale === false ? "" : "data, ");
4685 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4686 // clients needs to convert this in their way for further processing
4688 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4689 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4690 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4691 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4693 intval(local_user()),
4694 DBA::escape($photo_id),
4699 'image/jpeg' => 'jpg',
4700 'image/png' => 'png',
4701 'image/gif' => 'gif'
4704 // prepare output data for photo
4705 if (DBA::isResult($r)) {
4706 $data = ['photo' => $r[0]];
4707 $data['photo']['id'] = $data['photo']['resource-id'];
4708 if ($scale !== false) {
4709 $data['photo']['data'] = base64_encode($data['photo']['data']);
4711 unset($data['photo']['datasize']); //needed only with scale param
4713 if ($type == "xml") {
4714 $data['photo']['links'] = [];
4715 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4716 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4718 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4721 $data['photo']['link'] = [];
4722 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4724 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4725 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4729 unset($data['photo']['resource-id']);
4730 unset($data['photo']['minscale']);
4731 unset($data['photo']['maxscale']);
4733 throw new NotFoundException();
4736 // retrieve item element for getting activities (like, dislike etc.) related to photo
4737 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4738 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4740 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4742 // retrieve comments on photo
4743 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4744 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4746 $statuses = Item::selectForUser(api_user(), [], $condition);
4748 // prepare output of comments
4749 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
4751 if ($type == "xml") {
4753 foreach ($commentData as $comment) {
4754 $comments[$k++ . ":comment"] = $comment;
4757 foreach ($commentData as $comment) {
4758 $comments[] = $comment;
4761 $data['photo']['friendica_comments'] = $comments;
4763 // include info if rights on photo and rights on item are mismatching
4764 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4765 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4766 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4767 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4768 $data['photo']['rights_mismatch'] = $rights_mismatch;
4775 * Similar as /mod/redir.php
4776 * redirect to 'url' after dfrn auth
4778 * Why this when there is mod/redir.php already?
4779 * This use api_user() and api_login()
4782 * c_url: url of remote contact to auth to
4783 * url: string, url to redirect after auth
4785 function api_friendica_remoteauth()
4787 $url = defaults($_GET, 'url', '');
4788 $c_url = defaults($_GET, 'c_url', '');
4790 if ($url === '' || $c_url === '') {
4791 throw new BadRequestException("Wrong parameters.");
4794 $c_url = Strings::normaliseLink($c_url);
4798 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4800 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
4801 throw new BadRequestException("Unknown contact");
4804 $cid = $contact['id'];
4806 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4808 if ($contact['duplex'] && $contact['issued-id']) {
4809 $orig_id = $contact['issued-id'];
4810 $dfrn_id = '1:' . $orig_id;
4812 if ($contact['duplex'] && $contact['dfrn-id']) {
4813 $orig_id = $contact['dfrn-id'];
4814 $dfrn_id = '0:' . $orig_id;
4817 $sec = Strings::getRandomHex();
4819 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4820 'sec' => $sec, 'expire' => time() + 45];
4821 DBA::insert('profile_check', $fields);
4823 Logger::log($contact['name'] . ' ' . $sec, Logger::DEBUG);
4824 $dest = ($url ? '&destination_url=' . $url : '');
4826 System::externalRedirect(
4827 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4828 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4829 . '&type=profile&sec=' . $sec . $dest
4832 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4835 * @brief Return the item shared, if the item contains only the [share] tag
4837 * @param array $item Sharer item
4838 * @return array|false Shared item or false if not a reshare
4840 function api_share_as_retweet(&$item)
4842 $body = trim($item["body"]);
4844 if (Diaspora::isReshare($body, false) === false) {
4845 if ($item['author-id'] == $item['owner-id']) {
4848 // Reshares from OStatus, ActivityPub and Twitter
4849 $reshared_item = $item;
4850 $reshared_item['owner-id'] = $reshared_item['author-id'];
4851 $reshared_item['owner-link'] = $reshared_item['author-link'];
4852 $reshared_item['owner-name'] = $reshared_item['author-name'];
4853 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
4854 return $reshared_item;
4858 /// @TODO "$1" should maybe mean '$1' ?
4859 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4861 * Skip if there is no shared message in there
4862 * we already checked this in diaspora::isReshare()
4863 * but better one more than one less...
4865 if (($body == $attributes) || empty($attributes)) {
4869 // build the fake reshared item
4870 $reshared_item = $item;
4873 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4874 if (!empty($matches[1])) {
4875 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4878 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4879 if (!empty($matches[1])) {
4880 $author = $matches[1];
4884 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4885 if (!empty($matches[1])) {
4886 $profile = $matches[1];
4889 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4890 if (!empty($matches[1])) {
4891 $profile = $matches[1];
4895 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4896 if (!empty($matches[1])) {
4897 $avatar = $matches[1];
4900 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4901 if (!empty($matches[1])) {
4902 $avatar = $matches[1];
4906 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4907 if (!empty($matches[1])) {
4908 $link = $matches[1];
4911 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4912 if (!empty($matches[1])) {
4913 $link = $matches[1];
4917 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4918 if (!empty($matches[1])) {
4919 $posted = $matches[1];
4922 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4923 if (!empty($matches[1])) {
4924 $posted = $matches[1];
4927 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4929 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4933 $reshared_item["body"] = $shared_body;
4934 $reshared_item["author-id"] = Contact::getIdForURL($profile, 0, true);
4935 $reshared_item["author-name"] = $author;
4936 $reshared_item["author-link"] = $profile;
4937 $reshared_item["author-avatar"] = $avatar;
4938 $reshared_item["plink"] = $link;
4939 $reshared_item["created"] = $posted;
4940 $reshared_item["edited"] = $posted;
4942 return $reshared_item;
4947 * @param string $profile
4949 * @return string|false
4950 * @todo remove trailing junk from profile url
4951 * @todo pump.io check has to check the website
4953 function api_get_nick($profile)
4958 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4959 DBA::escape(Strings::normaliseLink($profile))
4962 if (DBA::isResult($r)) {
4963 $nick = $r[0]["nick"];
4968 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4969 DBA::escape(Strings::normaliseLink($profile))
4972 if (DBA::isResult($r)) {
4973 $nick = $r[0]["nick"];
4978 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4979 if ($friendica != $profile) {
4985 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4986 if ($diaspora != $profile) {
4992 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4993 if ($twitter != $profile) {
5000 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5001 if ($StatusnetHost != $profile) {
5002 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5003 if ($StatusnetUser != $profile) {
5004 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5005 $user = json_decode($UserData);
5007 $nick = $user->screen_name;
5013 // To-Do: look at the page if its really a pumpio site
5014 //if (!$nick == "") {
5015 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5016 // if ($pumpio != $profile)
5018 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5031 * @param array $item
5035 function api_in_reply_to($item)
5039 $in_reply_to['status_id'] = null;
5040 $in_reply_to['user_id'] = null;
5041 $in_reply_to['status_id_str'] = null;
5042 $in_reply_to['user_id_str'] = null;
5043 $in_reply_to['screen_name'] = null;
5045 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5046 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5047 if (DBA::isResult($parent)) {
5048 $in_reply_to['status_id'] = intval($parent['id']);
5050 $in_reply_to['status_id'] = intval($item['parent']);
5053 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5055 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5056 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5058 if (DBA::isResult($parent)) {
5059 if ($parent['author-nick'] == "") {
5060 $parent['author-nick'] = api_get_nick($parent['author-link']);
5063 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5064 $in_reply_to['user_id'] = intval($parent['author-id']);
5065 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5068 // There seems to be situation, where both fields are identical:
5069 // https://github.com/friendica/friendica/issues/1010
5070 // This is a bugfix for that.
5071 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5072 Logger::log('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], Logger::DEBUG);
5073 $in_reply_to['status_id'] = null;
5074 $in_reply_to['user_id'] = null;
5075 $in_reply_to['status_id_str'] = null;
5076 $in_reply_to['user_id_str'] = null;
5077 $in_reply_to['screen_name'] = null;
5081 return $in_reply_to;
5086 * @param string $text
5090 function api_clean_plain_items($text)
5092 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
5094 $text = BBCode::cleanPictureLinks($text);
5095 $URLSearchString = "^\[\]";
5097 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5099 if ($include_entities == "true") {
5100 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5103 // Simplify "attachment" element
5104 $text = api_clean_attachments($text);
5110 * @brief Removes most sharing information for API text export
5112 * @param string $body The original body
5114 * @return string Cleaned body
5116 function api_clean_attachments($body)
5118 $data = BBCode::getAttachmentData($body);
5125 if (isset($data["text"])) {
5126 $body = $data["text"];
5128 if (($body == "") && isset($data["title"])) {
5129 $body = $data["title"];
5131 if (isset($data["url"])) {
5132 $body .= "\n".$data["url"];
5134 $body .= $data["after"];
5141 * @param array $contacts
5145 function api_best_nickname(&$contacts)
5149 if (count($contacts) == 0) {
5153 foreach ($contacts as $contact) {
5154 if ($contact["network"] == "") {
5155 $contact["network"] = "dfrn";
5156 $best_contact = [$contact];
5160 if (sizeof($best_contact) == 0) {
5161 foreach ($contacts as $contact) {
5162 if ($contact["network"] == "dfrn") {
5163 $best_contact = [$contact];
5168 if (sizeof($best_contact) == 0) {
5169 foreach ($contacts as $contact) {
5170 if ($contact["network"] == "dspr") {
5171 $best_contact = [$contact];
5176 if (sizeof($best_contact) == 0) {
5177 foreach ($contacts as $contact) {
5178 if ($contact["network"] == "stat") {
5179 $best_contact = [$contact];
5184 if (sizeof($best_contact) == 0) {
5185 foreach ($contacts as $contact) {
5186 if ($contact["network"] == "pump") {
5187 $best_contact = [$contact];
5192 if (sizeof($best_contact) == 0) {
5193 foreach ($contacts as $contact) {
5194 if ($contact["network"] == "twit") {
5195 $best_contact = [$contact];
5200 if (sizeof($best_contact) == 1) {
5201 $contacts = $best_contact;
5203 $contacts = [$contacts[0]];
5208 * Return all or a specified group of the user with the containing contacts.
5210 * @param string $type Return type (atom, rss, xml, json)
5212 * @return array|string
5214 function api_friendica_group_show($type)
5218 if (api_user() === false) {
5219 throw new ForbiddenException();
5223 $user_info = api_get_user($a);
5224 $gid = defaults($_REQUEST, 'gid', 0);
5225 $uid = $user_info['uid'];
5227 // get data of the specified group id or all groups if not specified
5230 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5234 // error message if specified gid is not in database
5235 if (!DBA::isResult($r)) {
5236 throw new BadRequestException("gid not available");
5240 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5245 // loop through all groups and retrieve all members for adding data in the user array
5247 foreach ($r as $rr) {
5248 $members = Contact::getByGroupId($rr['id']);
5251 if ($type == "xml") {
5252 $user_element = "users";
5254 foreach ($members as $member) {
5255 $user = api_get_user($a, $member['nurl']);
5256 $users[$k++.":user"] = $user;
5259 $user_element = "user";
5260 foreach ($members as $member) {
5261 $user = api_get_user($a, $member['nurl']);
5265 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5267 return api_format_data("groups", $type, ['group' => $grps]);
5269 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5273 * Delete the specified group of the user.
5275 * @param string $type Return type (atom, rss, xml, json)
5277 * @return array|string
5279 function api_friendica_group_delete($type)
5283 if (api_user() === false) {
5284 throw new ForbiddenException();
5288 $user_info = api_get_user($a);
5289 $gid = defaults($_REQUEST, 'gid', 0);
5290 $name = defaults($_REQUEST, 'name', "");
5291 $uid = $user_info['uid'];
5293 // error if no gid specified
5294 if ($gid == 0 || $name == "") {
5295 throw new BadRequestException('gid or name not specified');
5298 // get data of the specified group id
5300 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5304 // error message if specified gid is not in database
5305 if (!DBA::isResult($r)) {
5306 throw new BadRequestException('gid not available');
5309 // get data of the specified group id and group name
5311 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5316 // error message if specified gid is not in database
5317 if (!DBA::isResult($rname)) {
5318 throw new BadRequestException('wrong group name');
5322 $ret = Group::removeByName($uid, $name);
5325 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5326 return api_format_data("group_delete", $type, ['result' => $success]);
5328 throw new BadRequestException('other API error');
5331 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5336 * @param string $type Return type (atom, rss, xml, json)
5338 * @return array|string
5339 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5341 function api_lists_destroy($type)
5345 if (api_user() === false) {
5346 throw new ForbiddenException();
5350 $user_info = api_get_user($a);
5351 $gid = defaults($_REQUEST, 'list_id', 0);
5352 $uid = $user_info['uid'];
5354 // error if no gid specified
5356 throw new BadRequestException('gid not specified');
5359 // get data of the specified group id
5360 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5361 // error message if specified gid is not in database
5363 throw new BadRequestException('gid not available');
5366 if (Group::remove($gid)) {
5368 'name' => $group['name'],
5369 'id' => intval($gid),
5370 'id_str' => (string) $gid,
5371 'user' => $user_info
5374 return api_format_data("lists", $type, ['lists' => $list]);
5377 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5380 * Add a new group to the database.
5382 * @param string $name Group name
5383 * @param int $uid User ID
5384 * @param array $users List of users to add to the group
5388 function group_create($name, $uid, $users = [])
5390 // error if no name specified
5392 throw new BadRequestException('group name not specified');
5395 // get data of the specified group name
5397 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5401 // error message if specified group name already exists
5402 if (DBA::isResult($rname)) {
5403 throw new BadRequestException('group name already exists');
5406 // check if specified group name is a deleted group
5408 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5412 // error message if specified group name already exists
5413 if (DBA::isResult($rname)) {
5414 $reactivate_group = true;
5418 $ret = Group::create($uid, $name);
5420 $gid = Group::getIdByName($uid, $name);
5422 throw new BadRequestException('other API error');
5426 $erroraddinguser = false;
5428 foreach ($users as $user) {
5429 $cid = $user['cid'];
5430 // check if user really exists as contact
5432 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5436 if (count($contact)) {
5437 Group::addMember($gid, $cid);
5439 $erroraddinguser = true;
5440 $errorusers[] = $cid;
5444 // return success message incl. missing users in array
5445 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5447 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5451 * Create the specified group with the posted array of contacts.
5453 * @param string $type Return type (atom, rss, xml, json)
5455 * @return array|string
5457 function api_friendica_group_create($type)
5461 if (api_user() === false) {
5462 throw new ForbiddenException();
5466 $user_info = api_get_user($a);
5467 $name = defaults($_REQUEST, 'name', "");
5468 $uid = $user_info['uid'];
5469 $json = json_decode($_POST['json'], true);
5470 $users = $json['user'];
5472 $success = group_create($name, $uid, $users);
5474 return api_format_data("group_create", $type, ['result' => $success]);
5476 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5479 * Create a new group.
5481 * @param string $type Return type (atom, rss, xml, json)
5483 * @return array|string
5484 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5486 function api_lists_create($type)
5490 if (api_user() === false) {
5491 throw new ForbiddenException();
5495 $user_info = api_get_user($a);
5496 $name = defaults($_REQUEST, 'name', "");
5497 $uid = $user_info['uid'];
5499 $success = group_create($name, $uid);
5500 if ($success['success']) {
5502 'name' => $success['name'],
5503 'id' => intval($success['gid']),
5504 'id_str' => (string) $success['gid'],
5505 'user' => $user_info
5508 return api_format_data("lists", $type, ['lists'=>$grp]);
5511 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5514 * Update the specified group with the posted array of contacts.
5516 * @param string $type Return type (atom, rss, xml, json)
5518 * @return array|string
5520 function api_friendica_group_update($type)
5524 if (api_user() === false) {
5525 throw new ForbiddenException();
5529 $user_info = api_get_user($a);
5530 $uid = $user_info['uid'];
5531 $gid = defaults($_REQUEST, 'gid', 0);
5532 $name = defaults($_REQUEST, 'name', "");
5533 $json = json_decode($_POST['json'], true);
5534 $users = $json['user'];
5536 // error if no name specified
5538 throw new BadRequestException('group name not specified');
5541 // error if no gid specified
5543 throw new BadRequestException('gid not specified');
5547 $members = Contact::getByGroupId($gid);
5548 foreach ($members as $member) {
5549 $cid = $member['id'];
5550 foreach ($users as $user) {
5551 $found = ($user['cid'] == $cid ? true : false);
5553 if (!isset($found) || !$found) {
5554 Group::removeMemberByName($uid, $name, $cid);
5559 $erroraddinguser = false;
5561 foreach ($users as $user) {
5562 $cid = $user['cid'];
5563 // check if user really exists as contact
5565 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5570 if (count($contact)) {
5571 Group::addMember($gid, $cid);
5573 $erroraddinguser = true;
5574 $errorusers[] = $cid;
5578 // return success message incl. missing users in array
5579 $status = ($erroraddinguser ? "missing user" : "ok");
5580 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5581 return api_format_data("group_update", $type, ['result' => $success]);
5584 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5587 * Update information about a group.
5589 * @param string $type Return type (atom, rss, xml, json)
5591 * @return array|string
5592 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5594 function api_lists_update($type)
5598 if (api_user() === false) {
5599 throw new ForbiddenException();
5603 $user_info = api_get_user($a);
5604 $gid = defaults($_REQUEST, 'list_id', 0);
5605 $name = defaults($_REQUEST, 'name', "");
5606 $uid = $user_info['uid'];
5608 // error if no gid specified
5610 throw new BadRequestException('gid not specified');
5613 // get data of the specified group id
5614 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5615 // error message if specified gid is not in database
5617 throw new BadRequestException('gid not available');
5620 if (Group::update($gid, $name)) {
5623 'id' => intval($gid),
5624 'id_str' => (string) $gid,
5625 'user' => $user_info
5628 return api_format_data("lists", $type, ['lists' => $list]);
5632 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5636 * @param string $type Return type (atom, rss, xml, json)
5638 * @return array|string
5640 function api_friendica_activity($type)
5644 if (api_user() === false) {
5645 throw new ForbiddenException();
5647 $verb = strtolower($a->argv[3]);
5648 $verb = preg_replace("|\..*$|", "", $verb);
5650 $id = defaults($_REQUEST, 'id', 0);
5652 $res = Item::performLike($id, $verb);
5655 if ($type == "xml") {
5660 return api_format_data('ok', $type, ['ok' => $ok]);
5662 throw new BadRequestException('Error adding activity');
5666 /// @TODO move to top of file or somewhere better
5667 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5668 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5669 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5670 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5671 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5672 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5673 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5674 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5675 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5676 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5679 * @brief Returns notifications
5681 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5682 * @return string|array
5684 function api_friendica_notification($type)
5688 if (api_user() === false) {
5689 throw new ForbiddenException();
5692 throw new BadRequestException("Invalid argument count");
5694 $nm = new NotificationsManager();
5696 $notes = $nm->getAll([], "+seen -date", 50);
5698 if ($type == "xml") {
5700 if (!empty($notes)) {
5701 foreach ($notes as $note) {
5702 $xmlnotes[] = ["@attributes" => $note];
5709 return api_format_data("notes", $type, ['note' => $notes]);
5713 * POST request with 'id' param as notification id
5715 * @brief Set notification as seen and returns associated item (if possible)
5717 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5718 * @return string|array
5720 function api_friendica_notification_seen($type)
5723 $user_info = api_get_user($a);
5725 if (api_user() === false || $user_info === false) {
5726 throw new ForbiddenException();
5729 throw new BadRequestException("Invalid argument count");
5732 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5734 $nm = new NotificationsManager();
5735 $note = $nm->getByID($id);
5736 if (is_null($note)) {
5737 throw new BadRequestException("Invalid argument");
5740 $nm->setSeen($note);
5741 if ($note['otype']=='item') {
5742 // would be really better with an ItemsManager and $im->getByID() :-P
5743 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5744 if (DBA::isResult($item)) {
5745 // we found the item, return it to the user
5746 $ret = api_format_items([$item], $user_info, false, $type);
5747 $data = ['status' => $ret];
5748 return api_format_data("status", $type, $data);
5750 // the item can't be found, but we set the note as seen, so we count this as a success
5752 return api_format_data('result', $type, ['result' => "success"]);
5755 /// @TODO move to top of file or somewhere better
5756 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5757 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5760 * @brief update a direct_message to seen state
5762 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5763 * @return string|array (success result=ok, error result=error with error message)
5765 function api_friendica_direct_messages_setseen($type)
5768 if (api_user() === false) {
5769 throw new ForbiddenException();
5773 $user_info = api_get_user($a);
5774 $uid = $user_info['uid'];
5775 $id = defaults($_REQUEST, 'id', 0);
5777 // return error if id is zero
5779 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5780 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5783 // error message if specified id is not in database
5784 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5785 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5786 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5789 // update seen indicator
5790 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5794 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5795 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5797 $answer = ['result' => 'error', 'message' => 'unknown error'];
5798 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5802 /// @TODO move to top of file or somewhere better
5803 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5806 * @brief search for direct_messages containing a searchstring through api
5808 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5809 * @param string $box
5810 * @return string|array (success: success=true if found and search_result contains found messages,
5811 * success=false if nothing was found, search_result='nothing found',
5812 * error: result=error with error message)
5814 function api_friendica_direct_messages_search($type, $box = "")
5818 if (api_user() === false) {
5819 throw new ForbiddenException();
5823 $user_info = api_get_user($a);
5824 $searchstring = defaults($_REQUEST, 'searchstring', "");
5825 $uid = $user_info['uid'];
5827 // error if no searchstring specified
5828 if ($searchstring == "") {
5829 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5830 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5833 // get data for the specified searchstring
5835 "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",
5837 DBA::escape('%'.$searchstring.'%')
5840 $profile_url = $user_info["url"];
5842 // message if nothing was found
5843 if (!DBA::isResult($r)) {
5844 $success = ['success' => false, 'search_results' => 'problem with query'];
5845 } elseif (count($r) == 0) {
5846 $success = ['success' => false, 'search_results' => 'nothing found'];
5849 foreach ($r as $item) {
5850 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5851 $recipient = $user_info;
5852 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5853 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5854 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5855 $sender = $user_info;
5858 if (isset($recipient) && isset($sender)) {
5859 $ret[] = api_format_messages($item, $recipient, $sender);
5862 $success = ['success' => true, 'search_results' => $ret];
5865 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5868 /// @TODO move to top of file or somewhere better
5869 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5872 * @brief return data of all the profiles a user has to the client
5874 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5875 * @return string|array
5877 function api_friendica_profile_show($type)
5881 if (api_user() === false) {
5882 throw new ForbiddenException();
5886 $profile_id = defaults($_REQUEST, 'profile_id', 0);
5888 // retrieve general information about profiles for user
5889 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5890 $directory = Config::get('system', 'directory');
5892 // get data of the specified profile id or all profiles of the user if not specified
5893 if ($profile_id != 0) {
5895 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5900 // error message if specified gid is not in database
5901 if (!DBA::isResult($r)) {
5902 throw new BadRequestException("profile_id not available");
5906 "SELECT * FROM `profile` WHERE `uid` = %d",
5910 // loop through all returned profiles and retrieve data and users
5913 foreach ($r as $rr) {
5914 $profile = api_format_items_profiles($rr);
5916 // select all users from contact table, loop and prepare standard return for user data
5919 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5924 foreach ($nurls as $nurl) {
5925 $user = api_get_user($a, $nurl['nurl']);
5926 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5928 $profile['users'] = $users;
5930 // add prepared profile data to array for final return
5931 if ($type == "xml") {
5932 $profiles[$k++ . ":profile"] = $profile;
5934 $profiles[] = $profile;
5938 // return settings, authenticated user and profiles data
5939 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
5941 $result = ['multi_profiles' => $multi_profiles ? true : false,
5942 'global_dir' => $directory,
5943 'friendica_owner' => api_get_user($a, $self['nurl']),
5944 'profiles' => $profiles];
5945 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5947 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5950 * Returns a list of saved searches.
5952 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5954 * @param string $type Return format: json or xml
5956 * @return string|array
5958 function api_saved_searches_list($type)
5960 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
5963 while ($term = $terms->fetch()) {
5965 'created_at' => api_date(time()),
5966 'id' => intval($term['id']),
5967 'id_str' => $term['id'],
5968 'name' => $term['term'],
5970 'query' => $term['term']
5976 return api_format_data("terms", $type, ['terms' => $result]);
5979 /// @TODO move to top of file or somewhere better
5980 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5983 @TODO Maybe open to implement?
5985 [pagename] => api/1.1/statuses/lookup.json
5986 [id] => 605138389168451584
5987 [include_cards] => true
5988 [cards_platform] => Android-12
5989 [include_entities] => true
5990 [include_my_retweet] => 1
5992 [include_reply_count] => true
5993 [include_descendent_reply_count] => true
5997 Not implemented by now:
5998 statuses/retweets_of_me
6003 account/update_location
6004 account/update_profile_background_image
6007 friendica/profile/update
6008 friendica/profile/create
6009 friendica/profile/delete
6011 Not implemented in status.net:
6012 statuses/retweeted_to_me
6013 statuses/retweeted_by_me
6014 direct_messages/destroy
6016 account/update_delivery_device
6017 notifications/follow