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\Config;
15 use Friendica\Core\Hook;
16 use Friendica\Core\L10n;
17 use Friendica\Core\Logger;
18 use Friendica\Core\NotificationsManager;
19 use Friendica\Core\PConfig;
20 use Friendica\Core\Protocol;
21 use Friendica\Core\Session;
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\Profile;
31 use Friendica\Model\User;
32 use Friendica\Network\FKOAuth1;
33 use Friendica\Network\HTTPException;
34 use Friendica\Network\HTTPException\BadRequestException;
35 use Friendica\Network\HTTPException\ExpectationFailedException;
36 use Friendica\Network\HTTPException\ForbiddenException;
37 use Friendica\Network\HTTPException\InternalServerErrorException;
38 use Friendica\Network\HTTPException\MethodNotAllowedException;
39 use Friendica\Network\HTTPException\NotFoundException;
40 use Friendica\Network\HTTPException\NotImplementedException;
41 use Friendica\Network\HTTPException\TooManyRequestsException;
42 use Friendica\Network\HTTPException\UnauthorizedException;
43 use Friendica\Object\Image;
44 use Friendica\Protocol\Diaspora;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Network;
47 use Friendica\Util\Proxy as ProxyUtils;
48 use Friendica\Util\Strings;
49 use Friendica\Util\XML;
51 require_once 'mod/share.php';
52 require_once 'mod/item.php';
53 require_once 'mod/wall_upload.php';
55 define('API_METHOD_ANY', '*');
56 define('API_METHOD_GET', 'GET');
57 define('API_METHOD_POST', 'POST,PUT');
58 define('API_METHOD_DELETE', 'POST,DELETE');
60 define('API_LOG_PREFIX', 'API {action} - ');
66 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
67 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
68 * into a page, and visitors will post something without noticing it).
70 * @brief Auth API user
74 if (!empty($_SESSION['allow_api'])) {
82 * Clients can send 'source' parameter to be show in post metadata
83 * as "sent via <source>".
84 * Some clients doesn't send a source param, we support ones we know
87 * @brief Get source name from API client
90 * Client source name, default to "api" if unset/unknown
95 if (requestdata('source')) {
96 return requestdata('source');
99 // Support for known clients that doesn't send a source name
100 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
101 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
105 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
107 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
114 * @brief Format date for API
116 * @param string $str Source date, as UTC
117 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
120 function api_date($str)
122 // Wed May 23 06:01:13 +0000 2007
123 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
127 * Register a function to be the endpoint for defined API path.
129 * @brief Register API endpoint
131 * @param string $path API URL path, relative to System::baseUrl()
132 * @param string $func Function name to call on path request
133 * @param bool $auth API need logged user
134 * @param string $method HTTP method reqiured to call this endpoint.
135 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
136 * Default to API_METHOD_ANY
138 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
148 // Workaround for hotot
149 $path = str_replace("api/", "api/1.1/", $path);
159 * Log in user via OAuth1 or Simple HTTP Auth.
160 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
162 * @brief Login API user
165 * @throws InternalServerErrorException
166 * @throws UnauthorizedException
167 * @hook 'authenticate'
169 * 'username' => username from login form
170 * 'password' => password from login form
171 * 'authenticated' => return status,
172 * 'user_record' => return authenticated user record
174 * array $user logged user record
176 function api_login(App $a)
178 $oauth1 = new FKOAuth1();
181 $request = OAuthRequest::from_request();
182 list($consumer, $token) = $oauth1->verify_request($request);
183 if (!is_null($token)) {
184 $oauth1->loginUser($token->uid);
185 Hook::callAll('logged_in', $a->user);
188 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
189 var_dump($consumer, $token);
191 } catch (Exception $e) {
192 Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
195 // workaround for HTTP-auth in CGI mode
196 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
197 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
198 if (strlen($userpass)) {
199 list($name, $password) = explode(':', $userpass);
200 $_SERVER['PHP_AUTH_USER'] = $name;
201 $_SERVER['PHP_AUTH_PW'] = $password;
205 if (empty($_SERVER['PHP_AUTH_USER'])) {
206 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
207 header('WWW-Authenticate: Basic realm="Friendica"');
208 throw new UnauthorizedException("This API requires login");
211 $user = defaults($_SERVER, 'PHP_AUTH_USER', '');
212 $password = defaults($_SERVER, 'PHP_AUTH_PW', '');
214 // allow "user@server" login (but ignore 'server' part)
215 $at = strstr($user, "@", true);
220 // next code from mod/auth.php. needs better solution
224 'username' => trim($user),
225 'password' => trim($password),
226 'authenticated' => 0,
227 'user_record' => null,
231 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
232 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
233 * and later addons should not interfere with an earlier one that succeeded.
235 Hook::callAll('authenticate', $addon_auth);
237 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
238 $record = $addon_auth['user_record'];
240 $user_id = User::authenticate(trim($user), trim($password), true);
241 if ($user_id !== false) {
242 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
246 if (!DBA::isResult($record)) {
247 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
248 header('WWW-Authenticate: Basic realm="Friendica"');
249 //header('HTTP/1.0 401 Unauthorized');
250 //die('This api requires login');
251 throw new UnauthorizedException("This API requires login");
254 Session::setAuthenticatedForUser($a, $record);
256 $_SESSION["allow_api"] = true;
258 Hook::callAll('logged_in', $a->user);
262 * API endpoints can define which HTTP method to accept when called.
263 * This function check the current HTTP method agains endpoint
266 * @brief Check HTTP method of called API
268 * @param string $method Required methods, uppercase, separated by comma
271 function api_check_method($method)
273 if ($method == "*") {
276 return (stripos($method, defaults($_SERVER, 'REQUEST_METHOD', 'GET')) !== false);
280 * Authenticate user, call registered API function, set HTTP headers
282 * @brief Main API entry point
285 * @return string|array API call result
288 function api_call(App $a)
290 global $API, $called_api;
293 if (strpos($a->query_string, ".xml") > 0) {
296 if (strpos($a->query_string, ".json") > 0) {
299 if (strpos($a->query_string, ".rss") > 0) {
302 if (strpos($a->query_string, ".atom") > 0) {
307 foreach ($API as $p => $info) {
308 if (strpos($a->query_string, $p) === 0) {
309 if (!api_check_method($info['method'])) {
310 throw new MethodNotAllowedException();
313 $called_api = explode("/", $p);
314 //unset($_SERVER['PHP_AUTH_USER']);
316 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
317 if (!empty($info['auth']) && api_user() === false) {
321 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
322 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
324 $stamp = microtime(true);
325 $return = call_user_func($info['func'], $type);
326 $duration = (float) (microtime(true) - $stamp);
328 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
330 $a->getProfiler()->saveLog($a->getLogger(), API_LOG_PREFIX . 'performance');
332 if (false === $return) {
334 * api function returned false withour throw an
335 * exception. This should not happend, throw a 500
337 throw new InternalServerErrorException();
342 header("Content-Type: text/xml");
345 header("Content-Type: application/json");
346 $json = json_encode(end($return));
347 if (!empty($_GET['callback'])) {
348 $json = $_GET['callback'] . "(" . $json . ")";
353 header("Content-Type: application/rss+xml");
354 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
357 header("Content-Type: application/atom+xml");
358 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
365 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => $a->query_string]);
366 throw new NotImplementedException();
367 } catch (HTTPException $e) {
368 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
369 return api_error($type, $e);
374 * @brief Format API error string
376 * @param string $type Return type (xml, json, rss, as)
377 * @param object $e HTTPException Error object
378 * @return string|array error message formatted as $type
380 function api_error($type, $e)
384 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
385 /// @TODO: https://dev.twitter.com/overview/api/response-codes
387 $error = ["error" => $error,
388 "code" => $e->getCode() . " " . $e->httpdesc,
389 "request" => $a->query_string];
391 $return = api_format_data('status', $type, ['status' => $error]);
395 header("Content-Type: text/xml");
398 header("Content-Type: application/json");
399 $return = json_encode($return);
402 header("Content-Type: application/rss+xml");
405 header("Content-Type: application/atom+xml");
413 * @brief Set values for RSS template
416 * @param array $arr Array to be passed to template
417 * @param array $user_info User info
419 * @throws BadRequestException
420 * @throws ImagickException
421 * @throws InternalServerErrorException
422 * @throws UnauthorizedException
423 * @todo find proper type-hints
425 function api_rss_extra(App $a, $arr, $user_info)
427 if (is_null($user_info)) {
428 $user_info = api_get_user($a);
431 $arr['$user'] = $user_info;
433 'alternate' => $user_info['url'],
434 'self' => System::baseUrl() . "/" . $a->query_string,
435 'base' => System::baseUrl(),
436 'updated' => api_date(null),
437 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
438 'language' => $user_info['lang'],
439 'logo' => System::baseUrl() . "/images/friendica-32.png",
447 * @brief Unique contact to contact url.
449 * @param int $id Contact id
450 * @return bool|string
451 * Contact url or False if contact id is unknown
454 function api_unique_id_to_nurl($id)
456 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
458 if (DBA::isResult($r)) {
466 * @brief Get user info array.
469 * @param int|string $contact_id Contact ID or URL
471 * @throws BadRequestException
472 * @throws ImagickException
473 * @throws InternalServerErrorException
474 * @throws UnauthorizedException
476 function api_get_user(App $a, $contact_id = null)
484 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
486 // Searching for contact URL
487 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
488 $user = DBA::escape(Strings::normaliseLink($contact_id));
490 $extra_query = "AND `contact`.`nurl` = '%s' ";
491 if (api_user() !== false) {
492 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
496 // Searching for contact id with uid = 0
497 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
498 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
501 throw new BadRequestException("User ID ".$contact_id." not found.");
505 $extra_query = "AND `contact`.`nurl` = '%s' ";
506 if (api_user() !== false) {
507 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
511 if (is_null($user) && !empty($_GET['user_id'])) {
512 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
515 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
519 $extra_query = "AND `contact`.`nurl` = '%s' ";
520 if (api_user() !== false) {
521 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
524 if (is_null($user) && !empty($_GET['screen_name'])) {
525 $user = DBA::escape($_GET['screen_name']);
526 $extra_query = "AND `contact`.`nick` = '%s' ";
527 if (api_user() !== false) {
528 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
532 if (is_null($user) && !empty($_GET['profileurl'])) {
533 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
534 $extra_query = "AND `contact`.`nurl` = '%s' ";
535 if (api_user() !== false) {
536 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
540 // $called_api is the API path exploded on / and is expected to have at least 2 elements
541 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
542 $argid = count($called_api);
543 if (!empty($a->argv[$argid])) {
544 $data = explode(".", $a->argv[$argid]);
545 if (count($data) > 1) {
546 list($user, $null) = $data;
549 if (is_numeric($user)) {
550 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
554 $extra_query = "AND `contact`.`nurl` = '%s' ";
555 if (api_user() !== false) {
556 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
560 $user = DBA::escape($user);
561 $extra_query = "AND `contact`.`nick` = '%s' ";
562 if (api_user() !== false) {
563 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
568 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
571 if (api_user() === false) {
575 $user = $_SESSION['uid'];
576 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
580 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
584 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
590 // Selecting the id by priority, friendica first
591 if (is_array($uinfo)) {
592 api_best_nickname($uinfo);
595 // if the contact wasn't found, fetch it from the contacts with uid = 0
596 if (!DBA::isResult($uinfo)) {
598 throw new BadRequestException("User not found.");
601 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
603 if (DBA::isResult($contact)) {
604 // If no nick where given, extract it from the address
605 if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
606 $contact['nick'] = api_get_nick($contact["url"]);
610 'id' => $contact["id"],
611 'id_str' => (string) $contact["id"],
612 'name' => $contact["name"],
613 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
614 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url']),
615 'description' => HTML::toPlaintext(BBCode::toPlaintext($contact["about"])),
616 'profile_image_url' => $contact["micro"],
617 'profile_image_url_https' => $contact["micro"],
618 'profile_image_url_profile_size' => $contact["thumb"],
619 'profile_image_url_large' => $contact["photo"],
620 'url' => $contact["url"],
621 'protected' => false,
622 'followers_count' => 0,
623 'friends_count' => 0,
625 'created_at' => api_date($contact["created"]),
626 'favourites_count' => 0,
628 'time_zone' => 'UTC',
629 'geo_enabled' => false,
631 'statuses_count' => 0,
633 'contributors_enabled' => false,
634 'is_translator' => false,
635 'is_translation_enabled' => false,
636 'following' => false,
637 'follow_request_sent' => false,
638 'statusnet_blocking' => false,
639 'notifications' => false,
640 'statusnet_profile_url' => $contact["url"],
642 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
643 'pid' => Contact::getIdForURL($contact["url"], 0, true),
645 'network' => $contact["network"],
650 throw new BadRequestException("User ".$url." not found.");
654 if ($uinfo[0]['self']) {
655 if ($uinfo[0]['network'] == "") {
656 $uinfo[0]['network'] = Protocol::DFRN;
659 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
660 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
667 // Add a nick if it isn't present there
668 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
669 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
672 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
674 if (!empty($profile['about'])) {
675 $description = $profile['about'];
677 $description = $uinfo[0]["about"];
680 if (!empty($usr['default-location'])) {
681 $location = $usr['default-location'];
682 } elseif (!empty($uinfo[0]["location"])) {
683 $location = $uinfo[0]["location"];
685 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
689 'id' => intval($pcontact_id),
690 'id_str' => (string) intval($pcontact_id),
691 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
692 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
693 'location' => $location,
694 'description' => HTML::toPlaintext(BBCode::toPlaintext($description)),
695 'profile_image_url' => $uinfo[0]['micro'],
696 'profile_image_url_https' => $uinfo[0]['micro'],
697 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
698 'profile_image_url_large' => $uinfo[0]["photo"],
699 'url' => $uinfo[0]['url'],
700 'protected' => false,
701 'followers_count' => intval($countfollowers),
702 'friends_count' => intval($countfriends),
704 'created_at' => api_date($uinfo[0]['created']),
705 'favourites_count' => intval($starred),
707 'time_zone' => 'UTC',
708 'geo_enabled' => false,
710 'statuses_count' => intval($countitems),
712 'contributors_enabled' => false,
713 'is_translator' => false,
714 'is_translation_enabled' => false,
715 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
716 'follow_request_sent' => false,
717 'statusnet_blocking' => false,
718 'notifications' => false,
720 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
721 'statusnet_profile_url' => $uinfo[0]['url'],
722 'uid' => intval($uinfo[0]['uid']),
723 'cid' => intval($uinfo[0]['cid']),
724 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
725 'self' => $uinfo[0]['self'],
726 'network' => $uinfo[0]['network'],
729 // If this is a local user and it uses Frio, we can get its color preferences.
731 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
732 if ($theme_info['theme'] === 'frio') {
733 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
735 if ($schema && ($schema != '---')) {
736 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
737 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
738 require_once $schemefile;
741 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
742 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
743 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
745 if (empty($nav_bg)) {
748 if (empty($link_color)) {
749 $link_color = "#6fdbe8";
751 if (empty($bgcolor)) {
752 $bgcolor = "#ededed";
755 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
756 $ret['profile_link_color'] = str_replace('#', '', $link_color);
757 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
765 * @brief return api-formatted array for item's author and owner
768 * @param array $item item from db
769 * @return array(array:author, array:owner)
770 * @throws BadRequestException
771 * @throws ImagickException
772 * @throws InternalServerErrorException
773 * @throws UnauthorizedException
775 function api_item_get_user(App $a, $item)
777 $status_user = api_get_user($a, defaults($item, 'author-id', null));
779 $author_user = $status_user;
781 $status_user["protected"] = defaults($item, 'private', 0);
783 if (defaults($item, 'thr-parent', '') == defaults($item, 'uri', '')) {
784 $owner_user = api_get_user($a, defaults($item, 'owner-id', null));
786 $owner_user = $author_user;
789 return ([$status_user, $author_user, $owner_user]);
793 * @brief walks recursively through an array with the possibility to change value and key
795 * @param array $array The array to walk through
796 * @param callable $callback The callback function
798 * @return array the transformed array
800 function api_walk_recursive(array &$array, callable $callback)
804 foreach ($array as $k => $v) {
806 if ($callback($v, $k)) {
807 $new_array[$k] = api_walk_recursive($v, $callback);
810 if ($callback($v, $k)) {
821 * @brief Callback function to transform the array in an array that can be transformed in a XML file
823 * @param mixed $item Array item value
824 * @param string $key Array key
826 * @return boolean Should the array item be deleted?
828 function api_reformat_xml(&$item, &$key)
830 if (is_bool($item)) {
831 $item = ($item ? "true" : "false");
834 if (substr($key, 0, 10) == "statusnet_") {
835 $key = "statusnet:".substr($key, 10);
836 } elseif (substr($key, 0, 10) == "friendica_") {
837 $key = "friendica:".substr($key, 10);
839 /// @TODO old-lost code?
841 // $key = "default:".$key;
847 * @brief Creates the XML from a JSON style array
849 * @param array $data JSON style array
850 * @param string $root_element Name of the root element
852 * @return string The XML data
854 function api_create_xml(array $data, $root_element)
856 $childname = key($data);
857 $data2 = array_pop($data);
859 $namespaces = ["" => "http://api.twitter.com",
860 "statusnet" => "http://status.net/schema/api/1/",
861 "friendica" => "http://friendi.ca/schema/api/1/",
862 "georss" => "http://www.georss.org/georss"];
864 /// @todo Auto detection of needed namespaces
865 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
869 if (is_array($data2)) {
871 api_walk_recursive($data2, "api_reformat_xml");
877 foreach ($data2 as $item) {
878 $data4[$i++ . ":" . $childname] = $item;
885 $data3 = [$root_element => $data2];
887 $ret = XML::fromArray($data3, $xml, false, $namespaces);
892 * @brief Formats the data according to the data type
894 * @param string $root_element Name of the root element
895 * @param string $type Return type (atom, rss, xml, json)
896 * @param array $data JSON style array
898 * @return array|string (string|array) XML data or JSON data
900 function api_format_data($root_element, $type, $data)
906 $ret = api_create_xml($data, $root_element);
921 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
922 * returns a 401 status code and an error message if not.
924 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
926 * @param string $type Return type (atom, rss, xml, json)
927 * @return array|string
928 * @throws BadRequestException
929 * @throws ForbiddenException
930 * @throws ImagickException
931 * @throws InternalServerErrorException
932 * @throws UnauthorizedException
934 function api_account_verify_credentials($type)
938 if (api_user() === false) {
939 throw new ForbiddenException();
942 unset($_REQUEST["user_id"]);
943 unset($_GET["user_id"]);
945 unset($_REQUEST["screen_name"]);
946 unset($_GET["screen_name"]);
948 $skip_status = defaults($_REQUEST, 'skip_status', false);
950 $user_info = api_get_user($a);
952 // "verified" isn't used here in the standard
953 unset($user_info["verified"]);
955 // - Adding last status
957 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
959 $user_info['status'] = api_format_item($item, $type);
963 // "uid" and "self" are only needed for some internal stuff, so remove it from here
964 unset($user_info["uid"]);
965 unset($user_info["self"]);
967 return api_format_data("user", $type, ['user' => $user_info]);
970 /// @TODO move to top of file or somewhere better
971 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
974 * Get data from $_POST or $_GET
979 function requestdata($k)
981 if (!empty($_POST[$k])) {
984 if (!empty($_GET[$k])) {
991 * Deprecated function to upload media.
993 * @param string $type Return type (atom, rss, xml, json)
995 * @return array|string
996 * @throws BadRequestException
997 * @throws ForbiddenException
998 * @throws ImagickException
999 * @throws InternalServerErrorException
1000 * @throws UnauthorizedException
1002 function api_statuses_mediap($type)
1006 if (api_user() === false) {
1007 Logger::log('api_statuses_update: no user');
1008 throw new ForbiddenException();
1010 $user_info = api_get_user($a);
1012 $_REQUEST['profile_uid'] = api_user();
1013 $_REQUEST['api_source'] = true;
1014 $txt = requestdata('status');
1015 /// @TODO old-lost code?
1016 //$txt = urldecode(requestdata('status'));
1018 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1019 $txt = HTML::toBBCodeVideo($txt);
1020 $config = HTMLPurifier_Config::createDefault();
1021 $config->set('Cache.DefinitionImpl', null);
1022 $purifier = new HTMLPurifier($config);
1023 $txt = $purifier->purify($txt);
1025 $txt = HTML::toBBCode($txt);
1027 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1029 $picture = wall_upload_post($a, false);
1031 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1032 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1033 $item_id = item_post($a);
1035 // output the post that we just posted.
1036 return api_status_show($type, $item_id);
1039 /// @TODO move this to top of file or somewhere better!
1040 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1043 * Updates the user’s current status.
1045 * @param string $type Return type (atom, rss, xml, json)
1047 * @return array|string
1048 * @throws BadRequestException
1049 * @throws ForbiddenException
1050 * @throws ImagickException
1051 * @throws InternalServerErrorException
1052 * @throws TooManyRequestsException
1053 * @throws UnauthorizedException
1054 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1056 function api_statuses_update($type)
1060 if (api_user() === false) {
1061 Logger::log('api_statuses_update: no user');
1062 throw new ForbiddenException();
1067 // convert $_POST array items to the form we use for web posts.
1068 if (requestdata('htmlstatus')) {
1069 $txt = requestdata('htmlstatus');
1070 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1071 $txt = HTML::toBBCodeVideo($txt);
1073 $config = HTMLPurifier_Config::createDefault();
1074 $config->set('Cache.DefinitionImpl', null);
1076 $purifier = new HTMLPurifier($config);
1077 $txt = $purifier->purify($txt);
1079 $_REQUEST['body'] = HTML::toBBCode($txt);
1082 $_REQUEST['body'] = requestdata('status');
1085 $_REQUEST['title'] = requestdata('title');
1087 $parent = requestdata('in_reply_to_status_id');
1089 // Twidere sends "-1" if it is no reply ...
1090 if ($parent == -1) {
1094 if (ctype_digit($parent)) {
1095 $_REQUEST['parent'] = $parent;
1097 $_REQUEST['parent_uri'] = $parent;
1100 if (requestdata('lat') && requestdata('long')) {
1101 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1103 $_REQUEST['profile_uid'] = api_user();
1106 // Check for throttling (maximum posts per day, week and month)
1107 $throttle_day = Config::get('system', 'throttle_limit_day');
1108 if ($throttle_day > 0) {
1109 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1111 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1112 $posts_day = DBA::count('thread', $condition);
1114 if ($posts_day > $throttle_day) {
1115 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1116 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1117 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));
1121 $throttle_week = Config::get('system', 'throttle_limit_week');
1122 if ($throttle_week > 0) {
1123 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1125 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1126 $posts_week = DBA::count('thread', $condition);
1128 if ($posts_week > $throttle_week) {
1129 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1130 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1131 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));
1135 $throttle_month = Config::get('system', 'throttle_limit_month');
1136 if ($throttle_month > 0) {
1137 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1139 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1140 $posts_month = DBA::count('thread', $condition);
1142 if ($posts_month > $throttle_month) {
1143 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1144 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1145 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));
1150 if (!empty($_FILES['media'])) {
1151 // upload the image if we have one
1152 $picture = wall_upload_post($a, false);
1153 if (is_array($picture)) {
1154 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1158 // To-Do: Multiple IDs
1159 if (requestdata('media_ids')) {
1161 "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",
1162 intval(requestdata('media_ids')),
1165 if (DBA::isResult($r)) {
1166 $phototypes = Image::supportedTypes();
1167 $ext = $phototypes[$r[0]['type']];
1168 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1169 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1173 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1175 $_REQUEST['api_source'] = true;
1177 if (empty($_REQUEST['source'])) {
1178 $_REQUEST["source"] = api_source();
1181 // call out normal post function
1182 $item_id = item_post($a);
1184 // output the post that we just posted.
1185 return api_status_show($type, $item_id);
1188 /// @TODO move to top of file or somewhere better
1189 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1190 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1193 * Uploads an image to Friendica.
1196 * @throws BadRequestException
1197 * @throws ForbiddenException
1198 * @throws ImagickException
1199 * @throws InternalServerErrorException
1200 * @throws UnauthorizedException
1201 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1203 function api_media_upload()
1207 if (api_user() === false) {
1208 Logger::log('no user');
1209 throw new ForbiddenException();
1214 if (empty($_FILES['media'])) {
1216 throw new BadRequestException("No media.");
1219 $media = wall_upload_post($a, false);
1222 throw new InternalServerErrorException();
1226 $returndata["media_id"] = $media["id"];
1227 $returndata["media_id_string"] = (string)$media["id"];
1228 $returndata["size"] = $media["size"];
1229 $returndata["image"] = ["w" => $media["width"],
1230 "h" => $media["height"],
1231 "image_type" => $media["type"],
1232 "friendica_preview_url" => $media["preview"]];
1234 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1236 return ["media" => $returndata];
1239 /// @TODO move to top of file or somewhere better
1240 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1243 * @param string $type Return format (atom, rss, xml, json)
1244 * @param int $item_id
1248 function api_status_show($type, $item_id)
1250 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1254 $item = api_get_item(['id' => $item_id]);
1256 $status_info = api_format_item($item, $type);
1259 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1261 return api_format_data('statuses', $type, ['status' => $status_info]);
1265 * Retrieves the last public status of the provided user info
1267 * @param int $ownerId Public contact Id
1268 * @param int $uid User Id
1272 function api_get_last_status($ownerId, $uid)
1275 'author-id'=> $ownerId,
1277 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1281 $item = api_get_item($condition);
1287 * Retrieves a single item record based on the provided condition and converts it for API use.
1289 * @param array $condition Item table condition array
1293 function api_get_item(array $condition)
1295 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1301 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1302 * The author's most recent status will be returned inline.
1304 * @param string $type Return type (atom, rss, xml, json)
1305 * @return array|string
1306 * @throws BadRequestException
1307 * @throws ImagickException
1308 * @throws InternalServerErrorException
1309 * @throws UnauthorizedException
1310 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1312 function api_users_show($type)
1314 $a = \Friendica\BaseObject::getApp();
1316 $user_info = api_get_user($a);
1318 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1320 $user_info['status'] = api_format_item($item, $type);
1323 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1324 unset($user_info['uid']);
1325 unset($user_info['self']);
1327 return api_format_data('user', $type, ['user' => $user_info]);
1330 /// @TODO move to top of file or somewhere better
1331 api_register_func('api/users/show', 'api_users_show');
1332 api_register_func('api/externalprofile/show', 'api_users_show');
1335 * Search a public user account.
1337 * @param string $type Return type (atom, rss, xml, json)
1339 * @return array|string
1340 * @throws BadRequestException
1341 * @throws ImagickException
1342 * @throws InternalServerErrorException
1343 * @throws UnauthorizedException
1344 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1346 function api_users_search($type)
1352 if (!empty($_GET['q'])) {
1353 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1355 if (!DBA::isResult($r)) {
1356 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1359 if (DBA::isResult($r)) {
1361 foreach ($r as $user) {
1362 $user_info = api_get_user($a, $user["id"]);
1364 if ($type == "xml") {
1365 $userlist[$k++.":user"] = $user_info;
1367 $userlist[] = $user_info;
1370 $userlist = ["users" => $userlist];
1372 throw new BadRequestException("User ".$_GET["q"]." not found.");
1375 throw new BadRequestException("No user specified.");
1378 return api_format_data("users", $type, $userlist);
1381 /// @TODO move to top of file or somewhere better
1382 api_register_func('api/users/search', 'api_users_search');
1385 * Return user objects
1387 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1389 * @param string $type Return format: json or xml
1391 * @return array|string
1392 * @throws BadRequestException
1393 * @throws ImagickException
1394 * @throws InternalServerErrorException
1395 * @throws NotFoundException if the results are empty.
1396 * @throws UnauthorizedException
1398 function api_users_lookup($type)
1402 if (!empty($_REQUEST['user_id'])) {
1403 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1405 $users[] = api_get_user(get_app(), $id);
1410 if (empty($users)) {
1411 throw new NotFoundException;
1414 return api_format_data("users", $type, ['users' => $users]);
1417 /// @TODO move to top of file or somewhere better
1418 api_register_func('api/users/lookup', 'api_users_lookup', true);
1421 * Returns statuses that match a specified query.
1423 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1425 * @param string $type Return format: json, xml, atom, rss
1427 * @return array|string
1428 * @throws BadRequestException if the "q" parameter is missing.
1429 * @throws ForbiddenException
1430 * @throws ImagickException
1431 * @throws InternalServerErrorException
1432 * @throws UnauthorizedException
1434 function api_search($type)
1437 $user_info = api_get_user($a);
1439 if (api_user() === false || $user_info === false) { throw new ForbiddenException(); }
1441 if (empty($_REQUEST['q'])) {
1442 throw new BadRequestException('q parameter is required.');
1445 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1448 $data['status'] = [];
1450 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1451 if (!empty($_REQUEST['rpp'])) {
1452 $count = $_REQUEST['rpp'];
1453 } elseif (!empty($_REQUEST['count'])) {
1454 $count = $_REQUEST['count'];
1457 $since_id = defaults($_REQUEST, 'since_id', 0);
1458 $max_id = defaults($_REQUEST, 'max_id', 0);
1459 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1460 $start = $page * $count;
1461 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1462 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1463 $searchTerm = $matches[1];
1464 $condition = ["`oid` > ?
1465 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1466 AND `otype` = ? AND `type` = ? AND `term` = ?",
1467 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1469 $condition[0] .= ' AND `oid` <= ?';
1470 $condition[] = $max_id;
1472 $terms = DBA::select('term', ['oid'], $condition, []);
1474 while ($term = DBA::fetch($terms)) {
1475 $itemIds[] = $term['oid'];
1479 if (empty($itemIds)) {
1480 return api_format_data('statuses', $type, $data);
1483 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1484 if ($exclude_replies) {
1485 $preCondition[] = '`id` = `parent`';
1488 $condition = [implode(' AND ', $preCondition)];
1490 $condition = ["`id` > ?
1491 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1492 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1493 AND `body` LIKE CONCAT('%',?,'%')",
1494 $since_id, api_user(), $_REQUEST['q']];
1496 $condition[0] .= ' AND `id` <= ?';
1497 $condition[] = $max_id;
1501 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1503 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1505 bindComments($data['status']);
1507 return api_format_data('statuses', $type, $data);
1510 /// @TODO move to top of file or somewhere better
1511 api_register_func('api/search/tweets', 'api_search', true);
1512 api_register_func('api/search', 'api_search', true);
1515 * Returns the most recent statuses posted by the user and the users they follow.
1517 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1519 * @param string $type Return type (atom, rss, xml, json)
1521 * @return array|string
1522 * @throws BadRequestException
1523 * @throws ForbiddenException
1524 * @throws ImagickException
1525 * @throws InternalServerErrorException
1526 * @throws UnauthorizedException
1527 * @todo Optional parameters
1528 * @todo Add reply info
1530 function api_statuses_home_timeline($type)
1533 $user_info = api_get_user($a);
1535 if (api_user() === false || $user_info === false) {
1536 throw new ForbiddenException();
1539 unset($_REQUEST["user_id"]);
1540 unset($_GET["user_id"]);
1542 unset($_REQUEST["screen_name"]);
1543 unset($_GET["screen_name"]);
1545 // get last network messages
1548 $count = defaults($_REQUEST, 'count', 20);
1549 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1553 $since_id = defaults($_REQUEST, 'since_id', 0);
1554 $max_id = defaults($_REQUEST, 'max_id', 0);
1555 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1556 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1558 $start = $page * $count;
1560 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1561 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1564 $condition[0] .= " AND `item`.`id` <= ?";
1565 $condition[] = $max_id;
1567 if ($exclude_replies) {
1568 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1570 if ($conversation_id > 0) {
1571 $condition[0] .= " AND `item`.`parent` = ?";
1572 $condition[] = $conversation_id;
1575 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1576 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1578 $items = Item::inArray($statuses);
1580 $ret = api_format_items($items, $user_info, false, $type);
1582 // Set all posts from the query above to seen
1584 foreach ($items as $item) {
1585 $idarray[] = intval($item["id"]);
1588 if (!empty($idarray)) {
1589 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1591 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1597 $data = ['status' => $ret];
1602 $data = api_rss_extra($a, $data, $user_info);
1606 return api_format_data("statuses", $type, $data);
1610 /// @TODO move to top of file or somewhere better
1611 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1612 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1615 * Returns the most recent statuses from public users.
1617 * @param string $type Return type (atom, rss, xml, json)
1619 * @return array|string
1620 * @throws BadRequestException
1621 * @throws ForbiddenException
1622 * @throws ImagickException
1623 * @throws InternalServerErrorException
1624 * @throws UnauthorizedException
1626 function api_statuses_public_timeline($type)
1629 $user_info = api_get_user($a);
1631 if (api_user() === false || $user_info === false) {
1632 throw new ForbiddenException();
1635 // get last network messages
1638 $count = defaults($_REQUEST, 'count', 20);
1639 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
1643 $since_id = defaults($_REQUEST, 'since_id', 0);
1644 $max_id = defaults($_REQUEST, 'max_id', 0);
1645 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1646 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1648 $start = $page * $count;
1650 if ($exclude_replies && !$conversation_id) {
1651 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1652 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1655 $condition[0] .= " AND `thread`.`iid` <= ?";
1656 $condition[] = $max_id;
1659 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1660 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1662 $r = Item::inArray($statuses);
1664 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1665 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1668 $condition[0] .= " AND `item`.`id` <= ?";
1669 $condition[] = $max_id;
1671 if ($conversation_id > 0) {
1672 $condition[0] .= " AND `item`.`parent` = ?";
1673 $condition[] = $conversation_id;
1676 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1677 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1679 $r = Item::inArray($statuses);
1682 $ret = api_format_items($r, $user_info, false, $type);
1686 $data = ['status' => $ret];
1691 $data = api_rss_extra($a, $data, $user_info);
1695 return api_format_data("statuses", $type, $data);
1698 /// @TODO move to top of file or somewhere better
1699 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1702 * Returns the most recent statuses posted by users this node knows about.
1704 * @brief Returns the list of public federated posts this node knows about
1706 * @param string $type Return format: json, xml, atom, rss
1707 * @return array|string
1708 * @throws BadRequestException
1709 * @throws ForbiddenException
1710 * @throws ImagickException
1711 * @throws InternalServerErrorException
1712 * @throws UnauthorizedException
1714 function api_statuses_networkpublic_timeline($type)
1717 $user_info = api_get_user($a);
1719 if (api_user() === false || $user_info === false) {
1720 throw new ForbiddenException();
1723 $since_id = defaults($_REQUEST, 'since_id', 0);
1724 $max_id = defaults($_REQUEST, 'max_id', 0);
1727 $count = defaults($_REQUEST, 'count', 20);
1728 $page = defaults($_REQUEST, 'page', 1);
1732 $start = ($page - 1) * $count;
1734 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1735 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1738 $condition[0] .= " AND `thread`.`iid` <= ?";
1739 $condition[] = $max_id;
1742 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1743 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1745 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1749 $data = ['status' => $ret];
1754 $data = api_rss_extra($a, $data, $user_info);
1758 return api_format_data("statuses", $type, $data);
1761 /// @TODO move to top of file or somewhere better
1762 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1765 * Returns a single status.
1767 * @param string $type Return type (atom, rss, xml, json)
1769 * @return array|string
1770 * @throws BadRequestException
1771 * @throws ForbiddenException
1772 * @throws ImagickException
1773 * @throws InternalServerErrorException
1774 * @throws UnauthorizedException
1775 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1777 function api_statuses_show($type)
1780 $user_info = api_get_user($a);
1782 if (api_user() === false || $user_info === false) {
1783 throw new ForbiddenException();
1787 $id = intval(defaults($a->argv, 3, 0));
1790 $id = intval(defaults($_REQUEST, 'id', 0));
1795 $id = intval(defaults($a->argv, 4, 0));
1798 Logger::log('API: api_statuses_show: ' . $id);
1800 $conversation = !empty($_REQUEST['conversation']);
1802 // try to fetch the item for the local user - or the public item, if there is no local one
1803 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1804 if (!DBA::isResult($uri_item)) {
1805 throw new BadRequestException("There is no status with this id.");
1808 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1809 if (!DBA::isResult($item)) {
1810 throw new BadRequestException("There is no status with this id.");
1815 if ($conversation) {
1816 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1817 $params = ['order' => ['id' => true]];
1819 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1823 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1825 /// @TODO How about copying this to above methods which don't check $r ?
1826 if (!DBA::isResult($statuses)) {
1827 throw new BadRequestException("There is no status with this id.");
1830 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1832 if ($conversation) {
1833 $data = ['status' => $ret];
1834 return api_format_data("statuses", $type, $data);
1836 $data = ['status' => $ret[0]];
1837 return api_format_data("status", $type, $data);
1841 /// @TODO move to top of file or somewhere better
1842 api_register_func('api/statuses/show', 'api_statuses_show', true);
1846 * @param string $type Return type (atom, rss, xml, json)
1848 * @return array|string
1849 * @throws BadRequestException
1850 * @throws ForbiddenException
1851 * @throws ImagickException
1852 * @throws InternalServerErrorException
1853 * @throws UnauthorizedException
1854 * @todo nothing to say?
1856 function api_conversation_show($type)
1859 $user_info = api_get_user($a);
1861 if (api_user() === false || $user_info === false) {
1862 throw new ForbiddenException();
1866 $id = intval(defaults($a->argv , 3 , 0));
1867 $since_id = intval(defaults($_REQUEST, 'since_id', 0));
1868 $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
1869 $count = intval(defaults($_REQUEST, 'count' , 20));
1870 $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
1875 $start = $page * $count;
1878 $id = intval(defaults($_REQUEST, 'id', 0));
1883 $id = intval(defaults($a->argv, 4, 0));
1886 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1888 // try to fetch the item for the local user - or the public item, if there is no local one
1889 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1890 if (!DBA::isResult($item)) {
1891 throw new BadRequestException("There is no status with this id.");
1894 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1895 if (!DBA::isResult($parent)) {
1896 throw new BadRequestException("There is no status with this id.");
1899 $id = $parent['id'];
1901 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1902 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1905 $condition[0] .= " AND `item`.`id` <= ?";
1906 $condition[] = $max_id;
1909 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1910 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1912 if (!DBA::isResult($statuses)) {
1913 throw new BadRequestException("There is no status with id $id.");
1916 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1918 $data = ['status' => $ret];
1919 return api_format_data("statuses", $type, $data);
1922 /// @TODO move to top of file or somewhere better
1923 api_register_func('api/conversation/show', 'api_conversation_show', true);
1924 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1929 * @param string $type Return type (atom, rss, xml, json)
1931 * @return array|string
1932 * @throws BadRequestException
1933 * @throws ForbiddenException
1934 * @throws ImagickException
1935 * @throws InternalServerErrorException
1936 * @throws UnauthorizedException
1937 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1939 function api_statuses_repeat($type)
1945 if (api_user() === false) {
1946 throw new ForbiddenException();
1952 $id = intval(defaults($a->argv, 3, 0));
1955 $id = intval(defaults($_REQUEST, 'id', 0));
1960 $id = intval(defaults($a->argv, 4, 0));
1963 Logger::log('API: api_statuses_repeat: '.$id);
1965 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1966 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
1968 if (DBA::isResult($item) && $item['body'] != "") {
1969 if (strpos($item['body'], "[/share]") !== false) {
1970 $pos = strpos($item['body'], "[share");
1971 $post = substr($item['body'], $pos);
1973 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
1975 $post .= $item['body'];
1976 $post .= "[/share]";
1978 $_REQUEST['body'] = $post;
1979 $_REQUEST['profile_uid'] = api_user();
1980 $_REQUEST['api_source'] = true;
1982 if (empty($_REQUEST['source'])) {
1983 $_REQUEST["source"] = api_source();
1986 $item_id = item_post($a);
1988 throw new ForbiddenException();
1991 // output the post that we just posted.
1993 return api_status_show($type, $item_id);
1996 /// @TODO move to top of file or somewhere better
1997 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2000 * Destroys a specific status.
2002 * @param string $type Return type (atom, rss, xml, json)
2004 * @return array|string
2005 * @throws BadRequestException
2006 * @throws ForbiddenException
2007 * @throws ImagickException
2008 * @throws InternalServerErrorException
2009 * @throws UnauthorizedException
2010 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2012 function api_statuses_destroy($type)
2016 if (api_user() === false) {
2017 throw new ForbiddenException();
2023 $id = intval(defaults($a->argv, 3, 0));
2026 $id = intval(defaults($_REQUEST, 'id', 0));
2031 $id = intval(defaults($a->argv, 4, 0));
2034 Logger::log('API: api_statuses_destroy: '.$id);
2036 $ret = api_statuses_show($type);
2038 Item::deleteForUser(['id' => $id], api_user());
2043 /// @TODO move to top of file or somewhere better
2044 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2047 * Returns the most recent mentions.
2049 * @param string $type Return type (atom, rss, xml, json)
2051 * @return array|string
2052 * @throws BadRequestException
2053 * @throws ForbiddenException
2054 * @throws ImagickException
2055 * @throws InternalServerErrorException
2056 * @throws UnauthorizedException
2057 * @see http://developer.twitter.com/doc/get/statuses/mentions
2059 function api_statuses_mentions($type)
2062 $user_info = api_get_user($a);
2064 if (api_user() === false || $user_info === false) {
2065 throw new ForbiddenException();
2068 unset($_REQUEST["user_id"]);
2069 unset($_GET["user_id"]);
2071 unset($_REQUEST["screen_name"]);
2072 unset($_GET["screen_name"]);
2074 // get last network messages
2077 $since_id = defaults($_REQUEST, 'since_id', 0);
2078 $max_id = defaults($_REQUEST, 'max_id' , 0);
2079 $count = defaults($_REQUEST, 'count' , 20);
2080 $page = defaults($_REQUEST, 'page' , 1);
2085 $start = ($page - 1) * $count;
2087 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2088 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2089 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2092 $condition[0] .= " AND `item`.`id` <= ?";
2093 $condition[] = $max_id;
2096 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2097 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2099 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2101 $data = ['status' => $ret];
2106 $data = api_rss_extra($a, $data, $user_info);
2110 return api_format_data("statuses", $type, $data);
2113 /// @TODO move to top of file or somewhere better
2114 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2115 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2118 * Returns the most recent statuses posted by the user.
2120 * @brief Returns a user's public timeline
2122 * @param string $type Either "json" or "xml"
2123 * @return string|array
2124 * @throws BadRequestException
2125 * @throws ForbiddenException
2126 * @throws ImagickException
2127 * @throws InternalServerErrorException
2128 * @throws UnauthorizedException
2129 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2131 function api_statuses_user_timeline($type)
2134 $user_info = api_get_user($a);
2136 if (api_user() === false || $user_info === false) {
2137 throw new ForbiddenException();
2141 "api_statuses_user_timeline: api_user: ". api_user() .
2142 "\nuser_info: ".print_r($user_info, true) .
2143 "\n_REQUEST: ".print_r($_REQUEST, true),
2147 $since_id = defaults($_REQUEST, 'since_id', 0);
2148 $max_id = defaults($_REQUEST, 'max_id', 0);
2149 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2150 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
2153 $count = defaults($_REQUEST, 'count', 20);
2154 $page = defaults($_REQUEST, 'page', 1);
2158 $start = ($page - 1) * $count;
2160 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2161 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2163 if ($user_info['self'] == 1) {
2164 $condition[0] .= ' AND `item`.`wall` ';
2167 if ($exclude_replies) {
2168 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2171 if ($conversation_id > 0) {
2172 $condition[0] .= " AND `item`.`parent` = ?";
2173 $condition[] = $conversation_id;
2177 $condition[0] .= " AND `item`.`id` <= ?";
2178 $condition[] = $max_id;
2181 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2182 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2184 $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 * @return array|string
2210 * @throws BadRequestException
2211 * @throws ForbiddenException
2212 * @throws ImagickException
2213 * @throws InternalServerErrorException
2214 * @throws UnauthorizedException
2215 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2217 function api_favorites_create_destroy($type)
2221 if (api_user() === false) {
2222 throw new ForbiddenException();
2225 // for versioned api.
2226 /// @TODO We need a better global soluton
2227 $action_argv_id = 2;
2228 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2229 $action_argv_id = 3;
2232 if ($a->argc <= $action_argv_id) {
2233 throw new BadRequestException("Invalid request.");
2235 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2236 if ($a->argc == $action_argv_id + 2) {
2237 $itemid = intval(defaults($a->argv, $action_argv_id + 1, 0));
2239 $itemid = intval(defaults($_REQUEST, 'id', 0));
2242 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2244 if (!DBA::isResult($item)) {
2245 throw new BadRequestException("Invalid item.");
2250 $item['starred'] = 1;
2253 $item['starred'] = 0;
2256 throw new BadRequestException("Invalid action ".$action);
2259 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2262 throw new InternalServerErrorException("DB error");
2266 $user_info = api_get_user($a);
2267 $rets = api_format_items([$item], $user_info, false, $type);
2270 $data = ['status' => $ret];
2275 $data = api_rss_extra($a, $data, $user_info);
2279 return api_format_data("status", $type, $data);
2282 /// @TODO move to top of file or somewhere better
2283 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2284 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2287 * Returns the most recent favorite statuses.
2289 * @param string $type Return type (atom, rss, xml, json)
2291 * @return string|array
2292 * @throws BadRequestException
2293 * @throws ForbiddenException
2294 * @throws ImagickException
2295 * @throws InternalServerErrorException
2296 * @throws UnauthorizedException
2298 function api_favorites($type)
2303 $user_info = api_get_user($a);
2305 if (api_user() === false || $user_info === false) {
2306 throw new ForbiddenException();
2311 // in friendica starred item are private
2312 // return favorites only for self
2313 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2315 if ($user_info['self'] == 0) {
2319 $since_id = defaults($_REQUEST, 'since_id', 0);
2320 $max_id = defaults($_REQUEST, 'max_id', 0);
2321 $count = defaults($_GET, 'count', 20);
2322 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
2327 $start = $page*$count;
2329 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2330 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2332 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2335 $condition[0] .= " AND `item`.`id` <= ?";
2336 $condition[] = $max_id;
2339 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2341 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2346 $data = ['status' => $ret];
2351 $data = api_rss_extra($a, $data, $user_info);
2355 return api_format_data("statuses", $type, $data);
2358 /// @TODO move to top of file or somewhere better
2359 api_register_func('api/favorites', 'api_favorites', true);
2363 * @param array $item
2364 * @param array $recipient
2365 * @param array $sender
2368 * @throws InternalServerErrorException
2370 function api_format_messages($item, $recipient, $sender)
2372 // standard meta information
2374 'id' => $item['id'],
2375 'sender_id' => $sender['id'],
2377 'recipient_id' => $recipient['id'],
2378 'created_at' => api_date(defaults($item, 'created', DateTimeFormat::utcNow())),
2379 'sender_screen_name' => $sender['screen_name'],
2380 'recipient_screen_name' => $recipient['screen_name'],
2381 'sender' => $sender,
2382 'recipient' => $recipient,
2384 'friendica_seen' => defaults($item, 'seen', 0),
2385 'friendica_parent_uri' => defaults($item, 'parent-uri', ''),
2388 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2389 if (isset($ret['sender']['uid'])) {
2390 unset($ret['sender']['uid']);
2392 if (isset($ret['sender']['self'])) {
2393 unset($ret['sender']['self']);
2395 if (isset($ret['recipient']['uid'])) {
2396 unset($ret['recipient']['uid']);
2398 if (isset($ret['recipient']['self'])) {
2399 unset($ret['recipient']['self']);
2402 //don't send title to regular StatusNET requests to avoid confusing these apps
2403 if (!empty($_GET['getText'])) {
2404 $ret['title'] = $item['title'];
2405 if ($_GET['getText'] == 'html') {
2406 $ret['text'] = BBCode::convert($item['body'], false);
2407 } elseif ($_GET['getText'] == 'plain') {
2408 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2411 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2413 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2414 unset($ret['sender']);
2415 unset($ret['recipient']);
2423 * @param array $item
2426 * @throws InternalServerErrorException
2428 function api_convert_item($item)
2430 $body = $item['body'];
2431 $attachments = api_get_attachments($body);
2433 // Workaround for ostatus messages where the title is identically to the body
2434 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2435 $statusbody = trim(HTML::toPlaintext($html, 0));
2437 // handle data: images
2438 $statusbody = api_format_items_embeded_images($item, $statusbody);
2440 $statustitle = trim($item['title']);
2442 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2443 $statustext = trim($statusbody);
2445 $statustext = trim($statustitle."\n\n".$statusbody);
2448 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2449 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . defaults($item, 'plink', '');
2452 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2454 // Workaround for clients with limited HTML parser functionality
2455 $search = ["<br>", "<blockquote>", "</blockquote>",
2456 "<h1>", "</h1>", "<h2>", "</h2>",
2457 "<h3>", "</h3>", "<h4>", "</h4>",
2458 "<h5>", "</h5>", "<h6>", "</h6>"];
2459 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2460 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2461 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2462 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2463 $statushtml = str_replace($search, $replace, $statushtml);
2465 if ($item['title'] != "") {
2466 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2470 $oldtext = $statushtml;
2471 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2472 } while ($oldtext != $statushtml);
2474 if (substr($statushtml, 0, 4) == '<br>') {
2475 $statushtml = substr($statushtml, 4);
2478 if (substr($statushtml, 0, -4) == '<br>') {
2479 $statushtml = substr($statushtml, -4);
2482 // feeds without body should contain the link
2483 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2484 $statushtml .= BBCode::convert($item['plink']);
2487 $entities = api_get_entitities($statustext, $body);
2490 "text" => $statustext,
2491 "html" => $statushtml,
2492 "attachments" => $attachments,
2493 "entities" => $entities
2499 * @param string $body
2502 * @throws InternalServerErrorException
2504 function api_get_attachments(&$body)
2507 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2509 $URLSearchString = "^\[\]";
2510 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2518 foreach ($images[1] as $image) {
2519 $imagedata = Image::getInfoFromURL($image);
2522 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2526 if (strstr(defaults($_SERVER, 'HTTP_USER_AGENT', ''), "AndStatus")) {
2527 foreach ($images[0] as $orig) {
2528 $body = str_replace($orig, "", $body);
2532 return $attachments;
2537 * @param string $text
2538 * @param string $bbcode
2541 * @throws InternalServerErrorException
2542 * @todo Links at the first character of the post
2544 function api_get_entitities(&$text, $bbcode)
2546 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
2548 if ($include_entities != "true") {
2549 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2551 foreach ($images[1] as $image) {
2552 $replace = ProxyUtils::proxifyUrl($image);
2553 $text = str_replace($image, $replace, $text);
2558 $bbcode = BBCode::cleanPictureLinks($bbcode);
2560 // Change pure links in text to bbcode uris
2561 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2564 $entities["hashtags"] = [];
2565 $entities["symbols"] = [];
2566 $entities["urls"] = [];
2567 $entities["user_mentions"] = [];
2569 $URLSearchString = "^\[\]";
2571 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2573 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2574 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2575 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2577 $bbcode = preg_replace(
2578 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2579 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2582 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2584 $bbcode = preg_replace(
2585 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2586 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2589 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2591 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2593 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2594 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2597 foreach ($urls[1] as $id => $url) {
2598 //$start = strpos($text, $url, $offset);
2599 $start = iconv_strpos($text, $url, 0, "UTF-8");
2600 if (!($start === false)) {
2601 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2605 ksort($ordered_urls);
2608 //foreach ($urls[1] AS $id=>$url) {
2609 foreach ($ordered_urls as $url) {
2610 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2611 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2613 $display_url = $url["title"];
2615 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2616 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2618 if (strlen($display_url) > 26) {
2619 $display_url = substr($display_url, 0, 25)."…";
2623 //$start = strpos($text, $url, $offset);
2624 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2625 if (!($start === false)) {
2626 $entities["urls"][] = ["url" => $url["url"],
2627 "expanded_url" => $url["url"],
2628 "display_url" => $display_url,
2629 "indices" => [$start, $start+strlen($url["url"])]];
2630 $offset = $start + 1;
2634 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2635 $ordered_images = [];
2636 foreach ($images[1] as $image) {
2637 //$start = strpos($text, $url, $offset);
2638 $start = iconv_strpos($text, $image, 0, "UTF-8");
2639 if (!($start === false)) {
2640 $ordered_images[$start] = $image;
2643 //$entities["media"] = array();
2646 foreach ($ordered_images as $url) {
2647 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2648 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2650 if (strlen($display_url) > 26) {
2651 $display_url = substr($display_url, 0, 25)."…";
2654 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2655 if (!($start === false)) {
2656 $image = Image::getInfoFromURL($url);
2658 // If image cache is activated, then use the following sizes:
2659 // thumb (150), small (340), medium (600) and large (1024)
2660 if (!Config::get("system", "proxy_disabled")) {
2661 $media_url = ProxyUtils::proxifyUrl($url);
2664 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2665 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2667 if (($image[0] > 150) || ($image[1] > 150)) {
2668 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2669 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2672 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2673 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2675 if (($image[0] > 600) || ($image[1] > 600)) {
2676 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2677 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2681 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2684 $entities["media"][] = [
2686 "id_str" => (string) ($start + 1),
2687 "indices" => [$start, $start+strlen($url)],
2688 "media_url" => Strings::normaliseLink($media_url),
2689 "media_url_https" => $media_url,
2691 "display_url" => $display_url,
2692 "expanded_url" => $url,
2696 $offset = $start + 1;
2705 * @param array $item
2706 * @param string $text
2710 function api_format_items_embeded_images($item, $text)
2712 $text = preg_replace_callback(
2713 '|data:image/([^;]+)[^=]+=*|m',
2714 function () use ($item) {
2715 return System::baseUrl() . '/display/' . $item['guid'];
2723 * @brief return <a href='url'>name</a> as array
2725 * @param string $txt text
2730 function api_contactlink_to_array($txt)
2733 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2734 if ($r && count($match)==3) {
2736 'name' => $match[2],
2750 * @brief return likes, dislikes and attend status for item
2752 * @param array $item array
2753 * @param string $type Return type (atom, rss, xml, json)
2756 * likes => int count,
2757 * dislikes => int count
2758 * @throws BadRequestException
2759 * @throws ImagickException
2760 * @throws InternalServerErrorException
2761 * @throws UnauthorizedException
2763 function api_format_items_activities($item, $type = "json")
2772 'attendmaybe' => [],
2775 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2776 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2778 while ($parent_item = Item::fetch($ret)) {
2779 // not used as result should be structured like other user data
2780 //builtin_activity_puller($i, $activities);
2782 // get user data and add it to the array of the activity
2783 $user = api_get_user($a, $parent_item['author-id']);
2784 switch ($parent_item['verb']) {
2786 $activities['like'][] = $user;
2788 case ACTIVITY_DISLIKE:
2789 $activities['dislike'][] = $user;
2791 case ACTIVITY_ATTEND:
2792 $activities['attendyes'][] = $user;
2794 case ACTIVITY_ATTENDNO:
2795 $activities['attendno'][] = $user;
2797 case ACTIVITY_ATTENDMAYBE:
2798 $activities['attendmaybe'][] = $user;
2807 if ($type == "xml") {
2808 $xml_activities = [];
2809 foreach ($activities as $k => $v) {
2810 // change xml element from "like" to "friendica:like"
2811 $xml_activities["friendica:".$k] = $v;
2812 // add user data into xml output
2814 foreach ($v as $user) {
2815 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2818 $activities = $xml_activities;
2826 * @brief return data from profiles
2828 * @param array $profile_row array containing data from db table 'profile'
2830 * @throws InternalServerErrorException
2832 function api_format_items_profiles($profile_row)
2835 'profile_id' => $profile_row['id'],
2836 'profile_name' => $profile_row['profile-name'],
2837 'is_default' => $profile_row['is-default'] ? true : false,
2838 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2839 'profile_photo' => $profile_row['photo'],
2840 'profile_thumb' => $profile_row['thumb'],
2841 'publish' => $profile_row['publish'] ? true : false,
2842 'net_publish' => $profile_row['net-publish'] ? true : false,
2843 'description' => $profile_row['pdesc'],
2844 'date_of_birth' => $profile_row['dob'],
2845 'address' => $profile_row['address'],
2846 'city' => $profile_row['locality'],
2847 'region' => $profile_row['region'],
2848 'postal_code' => $profile_row['postal-code'],
2849 'country' => $profile_row['country-name'],
2850 'hometown' => $profile_row['hometown'],
2851 'gender' => $profile_row['gender'],
2852 'marital' => $profile_row['marital'],
2853 'marital_with' => $profile_row['with'],
2854 'marital_since' => $profile_row['howlong'],
2855 'sexual' => $profile_row['sexual'],
2856 'politic' => $profile_row['politic'],
2857 'religion' => $profile_row['religion'],
2858 'public_keywords' => $profile_row['pub_keywords'],
2859 'private_keywords' => $profile_row['prv_keywords'],
2860 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2861 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2862 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2863 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2864 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2865 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2866 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2867 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2868 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2869 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2870 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2871 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2872 'homepage' => $profile_row['homepage'],
2879 * @brief format items to be returned by api
2881 * @param array $items array of items
2882 * @param array $user_info
2883 * @param bool $filter_user filter items by $user_info
2884 * @param string $type Return type (atom, rss, xml, json)
2886 * @throws BadRequestException
2887 * @throws ImagickException
2888 * @throws InternalServerErrorException
2889 * @throws UnauthorizedException
2891 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2893 $a = \Friendica\BaseObject::getApp();
2897 foreach ((array)$items as $item) {
2898 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2900 // Look if the posts are matching if they should be filtered by user id
2901 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2905 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2914 * @param array $item Item record
2915 * @param string $type Return format (atom, rss, xml, json)
2916 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2917 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2918 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2919 * @return array API-formatted status
2920 * @throws BadRequestException
2921 * @throws ImagickException
2922 * @throws InternalServerErrorException
2923 * @throws UnauthorizedException
2925 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2927 $a = \Friendica\BaseObject::getApp();
2929 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2930 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2933 localize_item($item);
2935 $in_reply_to = api_in_reply_to($item);
2937 $converted = api_convert_item($item);
2939 if ($type == "xml") {
2940 $geo = "georss:point";
2946 'text' => $converted["text"],
2947 'truncated' => false,
2948 'created_at'=> api_date($item['created']),
2949 'in_reply_to_status_id' => $in_reply_to['status_id'],
2950 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2951 'source' => (($item['app']) ? $item['app'] : 'web'),
2952 'id' => intval($item['id']),
2953 'id_str' => (string) intval($item['id']),
2954 'in_reply_to_user_id' => $in_reply_to['user_id'],
2955 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2956 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2958 'favorited' => $item['starred'] ? true : false,
2959 'user' => $status_user,
2960 'friendica_author' => $author_user,
2961 'friendica_owner' => $owner_user,
2962 'friendica_private' => $item['private'] == 1,
2963 //'entities' => NULL,
2964 'statusnet_html' => $converted["html"],
2965 'statusnet_conversation_id' => $item['parent'],
2966 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2967 'friendica_activities' => api_format_items_activities($item, $type),
2970 if (count($converted["attachments"]) > 0) {
2971 $status["attachments"] = $converted["attachments"];
2974 if (count($converted["entities"]) > 0) {
2975 $status["entities"] = $converted["entities"];
2978 if ($status["source"] == 'web') {
2979 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
2980 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
2981 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
2984 $retweeted_item = [];
2987 if ($item["id"] == $item["parent"]) {
2988 $body = $item['body'];
2989 $retweeted_item = api_share_as_retweet($item);
2990 if ($body != $item['body']) {
2991 $quoted_item = $retweeted_item;
2992 $retweeted_item = [];
2996 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
2997 $announce = api_get_announce($item);
2998 if (!empty($announce)) {
2999 $retweeted_item = $item;
3001 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3005 if (!empty($quoted_item)) {
3006 $conv_quoted = api_convert_item($quoted_item);
3007 $quoted_status = $status;
3008 unset($quoted_status['friendica_author']);
3009 unset($quoted_status['friendica_owner']);
3010 unset($quoted_status['friendica_activities']);
3011 unset($quoted_status['friendica_private']);
3012 unset($quoted_status['statusnet_conversation_id']);
3013 $quoted_status['text'] = $conv_quoted['text'];
3014 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3016 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3017 } catch (BadRequestException $e) {
3018 // user not found. should be found?
3019 /// @todo check if the user should be always found
3020 $quoted_status["user"] = [];
3024 if (!empty($retweeted_item)) {
3025 $retweeted_status = $status;
3026 unset($retweeted_status['friendica_author']);
3027 unset($retweeted_status['friendica_owner']);
3028 unset($retweeted_status['friendica_activities']);
3029 unset($retweeted_status['friendica_private']);
3030 unset($retweeted_status['statusnet_conversation_id']);
3031 $status['user'] = $status['friendica_owner'];
3033 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3034 } catch (BadRequestException $e) {
3035 // user not found. should be found?
3036 /// @todo check if the user should be always found
3037 $retweeted_status["user"] = [];
3040 $rt_converted = api_convert_item($retweeted_item);
3042 $retweeted_status['text'] = $rt_converted["text"];
3043 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3044 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3046 if (!empty($quoted_status)) {
3047 $retweeted_status['quoted_status'] = $quoted_status;
3050 $status['friendica_author'] = $retweeted_status['user'];
3051 $status['retweeted_status'] = $retweeted_status;
3052 } elseif (!empty($quoted_status)) {
3053 $root_status = api_convert_item($item);
3055 $status['text'] = $root_status["text"];
3056 $status['statusnet_html'] = $root_status["html"];
3057 $status['quoted_status'] = $quoted_status;
3060 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3061 unset($status["user"]["uid"]);
3062 unset($status["user"]["self"]);
3064 if ($item["coord"] != "") {
3065 $coords = explode(' ', $item["coord"]);
3066 if (count($coords) == 2) {
3067 if ($type == "json") {
3068 $status["geo"] = ['type' => 'Point',
3069 'coordinates' => [(float) $coords[0],
3070 (float) $coords[1]]];
3071 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3072 $status["georss:point"] = $item["coord"];
3081 * Returns the remaining number of API requests available to the user before the API limit is reached.
3083 * @param string $type Return type (atom, rss, xml, json)
3085 * @return array|string
3088 function api_account_rate_limit_status($type)
3090 if ($type == "xml") {
3092 'remaining-hits' => '150',
3093 '@attributes' => ["type" => "integer"],
3094 'hourly-limit' => '150',
3095 '@attributes2' => ["type" => "integer"],
3096 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3097 '@attributes3' => ["type" => "datetime"],
3098 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3099 '@attributes4' => ["type" => "integer"],
3103 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3104 'remaining_hits' => '150',
3105 'hourly_limit' => '150',
3106 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3110 return api_format_data('hash', $type, ['hash' => $hash]);
3113 /// @TODO move to top of file or somewhere better
3114 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3117 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3119 * @param string $type Return type (atom, rss, xml, json)
3121 * @return array|string
3123 function api_help_test($type)
3125 if ($type == 'xml') {
3131 return api_format_data('ok', $type, ["ok" => $ok]);
3134 /// @TODO move to top of file or somewhere better
3135 api_register_func('api/help/test', 'api_help_test', false);
3138 * Returns all lists the user subscribes to.
3140 * @param string $type Return type (atom, rss, xml, json)
3142 * @return array|string
3143 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3145 function api_lists_list($type)
3148 /// @TODO $ret is not filled here?
3149 return api_format_data('lists', $type, ["lists_list" => $ret]);
3152 /// @TODO move to top of file or somewhere better
3153 api_register_func('api/lists/list', 'api_lists_list', true);
3154 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3157 * Returns all groups the user owns.
3159 * @param string $type Return type (atom, rss, xml, json)
3161 * @return array|string
3162 * @throws BadRequestException
3163 * @throws ForbiddenException
3164 * @throws ImagickException
3165 * @throws InternalServerErrorException
3166 * @throws UnauthorizedException
3167 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3169 function api_lists_ownerships($type)
3173 if (api_user() === false) {
3174 throw new ForbiddenException();
3178 $user_info = api_get_user($a);
3179 $uid = $user_info['uid'];
3181 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3183 // loop through all groups
3185 foreach ($groups as $group) {
3186 if ($group['visible']) {
3192 'name' => $group['name'],
3193 'id' => intval($group['id']),
3194 'id_str' => (string) $group['id'],
3195 'user' => $user_info,
3199 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3202 /// @TODO move to top of file or somewhere better
3203 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3206 * Returns recent statuses from users in the specified group.
3208 * @param string $type Return type (atom, rss, xml, json)
3210 * @return array|string
3211 * @throws BadRequestException
3212 * @throws ForbiddenException
3213 * @throws ImagickException
3214 * @throws InternalServerErrorException
3215 * @throws UnauthorizedException
3216 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3218 function api_lists_statuses($type)
3222 $user_info = api_get_user($a);
3223 if (api_user() === false || $user_info === false) {
3224 throw new ForbiddenException();
3227 unset($_REQUEST["user_id"]);
3228 unset($_GET["user_id"]);
3230 unset($_REQUEST["screen_name"]);
3231 unset($_GET["screen_name"]);
3233 if (empty($_REQUEST['list_id'])) {
3234 throw new BadRequestException('list_id not specified');
3238 $count = defaults($_REQUEST, 'count', 20);
3239 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
3243 $since_id = defaults($_REQUEST, 'since_id', 0);
3244 $max_id = defaults($_REQUEST, 'max_id', 0);
3245 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3246 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
3248 $start = $page * $count;
3250 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3251 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3254 $condition[0] .= " AND `item`.`id` <= ?";
3255 $condition[] = $max_id;
3257 if ($exclude_replies > 0) {
3258 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3260 if ($conversation_id > 0) {
3261 $condition[0] .= " AND `item`.`parent` = ?";
3262 $condition[] = $conversation_id;
3265 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3266 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3268 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3270 $data = ['status' => $items];
3275 $data = api_rss_extra($a, $data, $user_info);
3279 return api_format_data("statuses", $type, $data);
3282 /// @TODO move to top of file or somewhere better
3283 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3286 * Considers friends and followers lists to be private and won't return
3287 * anything if any user_id parameter is passed.
3289 * @brief Returns either the friends of the follower list
3291 * @param string $qtype Either "friends" or "followers"
3292 * @return boolean|array
3293 * @throws BadRequestException
3294 * @throws ForbiddenException
3295 * @throws ImagickException
3296 * @throws InternalServerErrorException
3297 * @throws UnauthorizedException
3299 function api_statuses_f($qtype)
3303 if (api_user() === false) {
3304 throw new ForbiddenException();
3308 $count = defaults($_GET, 'count', 20);
3309 $page = defaults($_GET, 'page', 1);
3313 $start = ($page - 1) * $count;
3315 $user_info = api_get_user($a);
3317 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3318 /* this is to stop Hotot to load friends multiple times
3319 * I'm not sure if I'm missing return something or
3320 * is a bug in hotot. Workaround, meantime
3324 return array('$users' => $ret);*/
3329 if ($qtype == 'friends') {
3330 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3331 } elseif ($qtype == 'followers') {
3332 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3335 // friends and followers only for self
3336 if ($user_info['self'] == 0) {
3337 $sql_extra = " AND false ";
3340 if ($qtype == 'blocks') {
3341 $sql_filter = 'AND `blocked` AND NOT `pending`';
3342 } elseif ($qtype == 'incoming') {
3343 $sql_filter = 'AND `pending`';
3345 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3363 foreach ($r as $cid) {
3364 $user = api_get_user($a, $cid['nurl']);
3365 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3366 unset($user["uid"]);
3367 unset($user["self"]);
3374 return ['user' => $ret];
3379 * Returns the user's friends.
3381 * @brief Returns the list of friends of the provided user
3383 * @deprecated By Twitter API in favor of friends/list
3385 * @param string $type Either "json" or "xml"
3386 * @return boolean|string|array
3387 * @throws BadRequestException
3388 * @throws ForbiddenException
3390 function api_statuses_friends($type)
3392 $data = api_statuses_f("friends");
3393 if ($data === false) {
3396 return api_format_data("users", $type, $data);
3400 * Returns the user's followers.
3402 * @brief Returns the list of followers of the provided user
3404 * @deprecated By Twitter API in favor of friends/list
3406 * @param string $type Either "json" or "xml"
3407 * @return boolean|string|array
3408 * @throws BadRequestException
3409 * @throws ForbiddenException
3411 function api_statuses_followers($type)
3413 $data = api_statuses_f("followers");
3414 if ($data === false) {
3417 return api_format_data("users", $type, $data);
3420 /// @TODO move to top of file or somewhere better
3421 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3422 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3425 * Returns the list of blocked users
3427 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3429 * @param string $type Either "json" or "xml"
3431 * @return boolean|string|array
3432 * @throws BadRequestException
3433 * @throws ForbiddenException
3435 function api_blocks_list($type)
3437 $data = api_statuses_f('blocks');
3438 if ($data === false) {
3441 return api_format_data("users", $type, $data);
3444 /// @TODO move to top of file or somewhere better
3445 api_register_func('api/blocks/list', 'api_blocks_list', true);
3448 * Returns the list of pending users IDs
3450 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3452 * @param string $type Either "json" or "xml"
3454 * @return boolean|string|array
3455 * @throws BadRequestException
3456 * @throws ForbiddenException
3458 function api_friendships_incoming($type)
3460 $data = api_statuses_f('incoming');
3461 if ($data === false) {
3466 foreach ($data['user'] as $user) {
3467 $ids[] = $user['id'];
3470 return api_format_data("ids", $type, ['id' => $ids]);
3473 /// @TODO move to top of file or somewhere better
3474 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3477 * Returns the instance's configuration information.
3479 * @param string $type Return type (atom, rss, xml, json)
3481 * @return array|string
3482 * @throws InternalServerErrorException
3484 function api_statusnet_config($type)
3488 $name = Config::get('config', 'sitename');
3489 $server = $a->getHostName();
3490 $logo = System::baseUrl() . '/images/friendica-64.png';
3491 $email = Config::get('config', 'admin_email');
3492 $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3493 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3494 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3495 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3496 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3499 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3500 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3501 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3502 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3503 'shorturllength' => '30',
3505 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3506 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3507 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3508 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3513 return api_format_data('config', $type, ['config' => $config]);
3516 /// @TODO move to top of file or somewhere better
3517 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3518 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3522 * @param string $type Return type (atom, rss, xml, json)
3524 * @return array|string
3526 function api_statusnet_version($type)
3529 $fake_statusnet_version = "0.9.7";
3531 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3534 /// @TODO move to top of file or somewhere better
3535 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3536 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3540 * @param string $type Return type (atom, rss, xml, json)
3542 * @return array|string|void
3543 * @throws BadRequestException
3544 * @throws ForbiddenException
3545 * @throws ImagickException
3546 * @throws InternalServerErrorException
3547 * @throws UnauthorizedException
3548 * @todo use api_format_data() to return data
3550 function api_ff_ids($type)
3553 throw new ForbiddenException();
3560 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3563 "SELECT `pcontact`.`id` FROM `contact`
3564 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3565 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3568 if (!DBA::isResult($r)) {
3573 foreach ($r as $rr) {
3574 if ($stringify_ids) {
3577 $ids[] = intval($rr['id']);
3581 return api_format_data("ids", $type, ['id' => $ids]);
3585 * Returns the ID of every user the user is following.
3587 * @param string $type Return type (atom, rss, xml, json)
3589 * @return array|string
3590 * @throws BadRequestException
3591 * @throws ForbiddenException
3592 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3594 function api_friends_ids($type)
3596 return api_ff_ids($type);
3600 * Returns the ID of every user following the user.
3602 * @param string $type Return type (atom, rss, xml, json)
3604 * @return array|string
3605 * @throws BadRequestException
3606 * @throws ForbiddenException
3607 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3609 function api_followers_ids($type)
3611 return api_ff_ids($type);
3614 /// @TODO move to top of file or somewhere better
3615 api_register_func('api/friends/ids', 'api_friends_ids', true);
3616 api_register_func('api/followers/ids', 'api_followers_ids', true);
3619 * Sends a new direct message.
3621 * @param string $type Return type (atom, rss, xml, json)
3623 * @return array|string
3624 * @throws BadRequestException
3625 * @throws ForbiddenException
3626 * @throws ImagickException
3627 * @throws InternalServerErrorException
3628 * @throws NotFoundException
3629 * @throws UnauthorizedException
3630 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3632 function api_direct_messages_new($type)
3636 if (api_user() === false) {
3637 throw new ForbiddenException();
3640 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3644 $sender = api_get_user($a);
3647 if (!empty($_POST['screen_name'])) {
3649 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3651 DBA::escape($_POST['screen_name'])
3654 if (DBA::isResult($r)) {
3655 // Selecting the id by priority, friendica first
3656 api_best_nickname($r);
3658 $recipient = api_get_user($a, $r[0]['nurl']);
3661 $recipient = api_get_user($a, $_POST['user_id']);
3664 if (empty($recipient)) {
3665 throw new NotFoundException('Recipient not found');
3669 if (!empty($_REQUEST['replyto'])) {
3671 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3673 intval($_REQUEST['replyto'])
3675 $replyto = $r[0]['parent-uri'];
3676 $sub = $r[0]['title'];
3678 if (!empty($_REQUEST['title'])) {
3679 $sub = $_REQUEST['title'];
3681 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3685 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3688 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3689 $ret = api_format_messages($r[0], $recipient, $sender);
3691 $ret = ["error"=>$id];
3694 $data = ['direct_message'=>$ret];
3700 $data = api_rss_extra($a, $data, $sender);
3704 return api_format_data("direct-messages", $type, $data);
3707 /// @TODO move to top of file or somewhere better
3708 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3711 * Destroys a direct message.
3713 * @brief delete a direct_message from mail table through api
3715 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3716 * @return string|array
3717 * @throws BadRequestException
3718 * @throws ForbiddenException
3719 * @throws ImagickException
3720 * @throws InternalServerErrorException
3721 * @throws UnauthorizedException
3722 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3724 function api_direct_messages_destroy($type)
3728 if (api_user() === false) {
3729 throw new ForbiddenException();
3733 $user_info = api_get_user($a);
3735 $id = defaults($_REQUEST, 'id', 0);
3737 $parenturi = defaults($_REQUEST, 'friendica_parenturi', "");
3738 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3739 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3741 $uid = $user_info['uid'];
3742 // error if no id or parenturi specified (for clients posting parent-uri as well)
3743 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3744 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3745 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3748 // BadRequestException if no id specified (for clients using Twitter API)
3750 throw new BadRequestException('Message id not specified');
3753 // add parent-uri to sql command if specified by calling app
3754 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3756 // get data of the specified message id
3758 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3763 // error message if specified id is not in database
3764 if (!DBA::isResult($r)) {
3765 if ($verbose == "true") {
3766 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3767 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3769 /// @todo BadRequestException ok for Twitter API clients?
3770 throw new BadRequestException('message id not in database');
3775 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3780 if ($verbose == "true") {
3783 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3784 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3786 $answer = ['result' => 'error', 'message' => 'unknown error'];
3787 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3790 /// @todo return JSON data like Twitter API not yet implemented
3793 /// @TODO move to top of file or somewhere better
3794 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3799 * @brief unfollow contact
3801 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3802 * @return string|array
3803 * @throws BadRequestException
3804 * @throws ForbiddenException
3805 * @throws ImagickException
3806 * @throws InternalServerErrorException
3807 * @throws NotFoundException
3808 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3810 function api_friendships_destroy($type)
3814 if ($uid === false) {
3815 throw new ForbiddenException();
3818 $contact_id = defaults($_REQUEST, 'user_id');
3820 if (empty($contact_id)) {
3821 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3822 throw new BadRequestException("no user_id specified");
3825 // Get Contact by given id
3826 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3828 if(!DBA::isResult($contact)) {
3829 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3830 throw new NotFoundException("no contact found to given ID");
3833 $url = $contact["url"];
3835 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3836 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3837 Strings::normaliseLink($url), $url];
3838 $contact = DBA::selectFirst('contact', [], $condition);
3840 if (!DBA::isResult($contact)) {
3841 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3842 throw new NotFoundException("Not following Contact");
3845 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3846 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3847 throw new ExpectationFailedException("Not supported");
3850 $dissolve = ($contact['rel'] == Contact::SHARING);
3852 $owner = User::getOwnerDataById($uid);
3854 Contact::terminateFriendship($owner, $contact, $dissolve);
3857 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3858 throw new NotFoundException("Error Processing Request");
3861 // Sharing-only contacts get deleted as there no relationship any more
3863 Contact::remove($contact['id']);
3865 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3868 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3869 unset($contact["uid"]);
3870 unset($contact["self"]);
3872 // Set screen_name since Twidere requests it
3873 $contact["screen_name"] = $contact["nick"];
3875 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3877 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3881 * @param string $type Return type (atom, rss, xml, json)
3882 * @param string $box
3883 * @param string $verbose
3885 * @return array|string
3886 * @throws BadRequestException
3887 * @throws ForbiddenException
3888 * @throws ImagickException
3889 * @throws InternalServerErrorException
3890 * @throws UnauthorizedException
3892 function api_direct_messages_box($type, $box, $verbose)
3895 if (api_user() === false) {
3896 throw new ForbiddenException();
3899 $count = defaults($_GET, 'count', 20);
3900 $page = defaults($_REQUEST, 'page', 1) - 1;
3905 $since_id = defaults($_REQUEST, 'since_id', 0);
3906 $max_id = defaults($_REQUEST, 'max_id', 0);
3908 $user_id = defaults($_REQUEST, 'user_id', '');
3909 $screen_name = defaults($_REQUEST, 'screen_name', '');
3912 unset($_REQUEST["user_id"]);
3913 unset($_GET["user_id"]);
3915 unset($_REQUEST["screen_name"]);
3916 unset($_GET["screen_name"]);
3918 $user_info = api_get_user($a);
3919 if ($user_info === false) {
3920 throw new ForbiddenException();
3922 $profile_url = $user_info["url"];
3925 $start = $page * $count;
3930 if ($box=="sentbox") {
3931 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3932 } elseif ($box == "conversation") {
3933 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape(defaults($_GET, 'uri', '')) . "'";
3934 } elseif ($box == "all") {
3935 $sql_extra = "true";
3936 } elseif ($box == "inbox") {
3937 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3941 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3944 if ($user_id != "") {
3945 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3946 } elseif ($screen_name !="") {
3947 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3951 "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",
3957 if ($verbose == "true" && !DBA::isResult($r)) {
3958 $answer = ['result' => 'error', 'message' => 'no mails available'];
3959 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3963 foreach ($r as $item) {
3964 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3965 $recipient = $user_info;
3966 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3967 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3968 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3969 $sender = $user_info;
3972 if (isset($recipient) && isset($sender)) {
3973 $ret[] = api_format_messages($item, $recipient, $sender);
3978 $data = ['direct_message' => $ret];
3983 $data = api_rss_extra($a, $data, $user_info);
3987 return api_format_data("direct-messages", $type, $data);
3991 * Returns the most recent direct messages sent by the user.
3993 * @param string $type Return type (atom, rss, xml, json)
3995 * @return array|string
3996 * @throws BadRequestException
3997 * @throws ForbiddenException
3998 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4000 function api_direct_messages_sentbox($type)
4002 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4003 return api_direct_messages_box($type, "sentbox", $verbose);
4007 * Returns the most recent direct messages sent to the user.
4009 * @param string $type Return type (atom, rss, xml, json)
4011 * @return array|string
4012 * @throws BadRequestException
4013 * @throws ForbiddenException
4014 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4016 function api_direct_messages_inbox($type)
4018 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4019 return api_direct_messages_box($type, "inbox", $verbose);
4024 * @param string $type Return type (atom, rss, xml, json)
4026 * @return array|string
4027 * @throws BadRequestException
4028 * @throws ForbiddenException
4030 function api_direct_messages_all($type)
4032 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4033 return api_direct_messages_box($type, "all", $verbose);
4038 * @param string $type Return type (atom, rss, xml, json)
4040 * @return array|string
4041 * @throws BadRequestException
4042 * @throws ForbiddenException
4044 function api_direct_messages_conversation($type)
4046 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4047 return api_direct_messages_box($type, "conversation", $verbose);
4050 /// @TODO move to top of file or somewhere better
4051 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4052 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4053 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4054 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4057 * Returns an OAuth Request Token.
4059 * @see https://oauth.net/core/1.0/#auth_step1
4061 function api_oauth_request_token()
4063 $oauth1 = new FKOAuth1();
4065 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4066 } catch (Exception $e) {
4067 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4075 * Returns an OAuth Access Token.
4077 * @return array|string
4078 * @see https://oauth.net/core/1.0/#auth_step3
4080 function api_oauth_access_token()
4082 $oauth1 = new FKOAuth1();
4084 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4085 } catch (Exception $e) {
4086 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4093 /// @TODO move to top of file or somewhere better
4094 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4095 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4099 * @brief delete a complete photoalbum with all containing photos from database through api
4101 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4102 * @return string|array
4103 * @throws BadRequestException
4104 * @throws ForbiddenException
4105 * @throws InternalServerErrorException
4107 function api_fr_photoalbum_delete($type)
4109 if (api_user() === false) {
4110 throw new ForbiddenException();
4113 $album = defaults($_REQUEST, 'album', "");
4115 // we do not allow calls without album string
4117 throw new BadRequestException("no albumname specified");
4119 // check if album is existing
4121 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4125 if (!DBA::isResult($r)) {
4126 throw new BadRequestException("album not available");
4129 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4130 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4131 foreach ($r as $rr) {
4132 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4133 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4135 if (!DBA::isResult($photo_item)) {
4136 throw new InternalServerErrorException("problem with deleting items occured");
4138 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4141 // now let's delete all photos from the album
4142 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4144 // return success of deletion or error message
4146 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4147 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4149 throw new InternalServerErrorException("unknown error - deleting from database failed");
4154 * @brief update the name of the album for all photos of an album
4156 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4157 * @return string|array
4158 * @throws BadRequestException
4159 * @throws ForbiddenException
4160 * @throws InternalServerErrorException
4162 function api_fr_photoalbum_update($type)
4164 if (api_user() === false) {
4165 throw new ForbiddenException();
4168 $album = defaults($_REQUEST, 'album', "");
4169 $album_new = defaults($_REQUEST, 'album_new', "");
4171 // we do not allow calls without album string
4173 throw new BadRequestException("no albumname specified");
4175 if ($album_new == "") {
4176 throw new BadRequestException("no new albumname specified");
4178 // check if album is existing
4179 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4180 throw new BadRequestException("album not available");
4182 // now let's update all photos to the albumname
4183 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4185 // return success of updating or error message
4187 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4188 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4190 throw new InternalServerErrorException("unknown error - updating in database failed");
4196 * @brief list all photos of the authenticated user
4198 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4199 * @return string|array
4200 * @throws ForbiddenException
4201 * @throws InternalServerErrorException
4203 function api_fr_photos_list($type)
4205 if (api_user() === false) {
4206 throw new ForbiddenException();
4209 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4210 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4211 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4212 intval(local_user())
4215 'image/jpeg' => 'jpg',
4216 'image/png' => 'png',
4217 'image/gif' => 'gif'
4219 $data = ['photo'=>[]];
4220 if (DBA::isResult($r)) {
4221 foreach ($r as $rr) {
4223 $photo['id'] = $rr['resource-id'];
4224 $photo['album'] = $rr['album'];
4225 $photo['filename'] = $rr['filename'];
4226 $photo['type'] = $rr['type'];
4227 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4228 $photo['created'] = $rr['created'];
4229 $photo['edited'] = $rr['edited'];
4230 $photo['desc'] = $rr['desc'];
4232 if ($type == "xml") {
4233 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4235 $photo['thumb'] = $thumb;
4236 $data['photo'][] = $photo;
4240 return api_format_data("photos", $type, $data);
4244 * @brief upload a new photo or change an existing photo
4246 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4247 * @return string|array
4248 * @throws BadRequestException
4249 * @throws ForbiddenException
4250 * @throws ImagickException
4251 * @throws InternalServerErrorException
4252 * @throws NotFoundException
4254 function api_fr_photo_create_update($type)
4256 if (api_user() === false) {
4257 throw new ForbiddenException();
4260 $photo_id = defaults($_REQUEST, 'photo_id', null);
4261 $desc = defaults($_REQUEST, 'desc', (array_key_exists('desc', $_REQUEST) ? "" : null)) ; // extra check necessary to distinguish between 'not provided' and 'empty string'
4262 $album = defaults($_REQUEST, 'album', null);
4263 $album_new = defaults($_REQUEST, 'album_new', null);
4264 $allow_cid = defaults($_REQUEST, 'allow_cid', (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4265 $deny_cid = defaults($_REQUEST, 'deny_cid' , (array_key_exists('deny_cid' , $_REQUEST) ? " " : null));
4266 $allow_gid = defaults($_REQUEST, 'allow_gid', (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4267 $deny_gid = defaults($_REQUEST, 'deny_gid' , (array_key_exists('deny_gid' , $_REQUEST) ? " " : null));
4268 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4270 // do several checks on input parameters
4271 // we do not allow calls without album string
4272 if ($album == null) {
4273 throw new BadRequestException("no albumname specified");
4275 // if photo_id == null --> we are uploading a new photo
4276 if ($photo_id == null) {
4279 // error if no media posted in create-mode
4280 if (empty($_FILES['media'])) {
4282 throw new BadRequestException("no media data submitted");
4285 // album_new will be ignored in create-mode
4290 // check if photo is existing in databasei
4291 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4292 throw new BadRequestException("photo not available");
4296 // checks on acl strings provided by clients
4297 $acl_input_error = false;
4298 $acl_input_error |= check_acl_input($allow_cid);
4299 $acl_input_error |= check_acl_input($deny_cid);
4300 $acl_input_error |= check_acl_input($allow_gid);
4301 $acl_input_error |= check_acl_input($deny_gid);
4302 if ($acl_input_error) {
4303 throw new BadRequestException("acl data invalid");
4305 // now let's upload the new media in create-mode
4306 if ($mode == "create") {
4307 $media = $_FILES['media'];
4308 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4310 // return success of updating or error message
4311 if (!is_null($data)) {
4312 return api_format_data("photo_create", $type, $data);
4314 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4318 // now let's do the changes in update-mode
4319 if ($mode == "update") {
4320 $updated_fields = [];
4322 if (!is_null($desc)) {
4323 $updated_fields['desc'] = $desc;
4326 if (!is_null($album_new)) {
4327 $updated_fields['album'] = $album_new;
4330 if (!is_null($allow_cid)) {
4331 $allow_cid = trim($allow_cid);
4332 $updated_fields['allow_cid'] = $allow_cid;
4335 if (!is_null($deny_cid)) {
4336 $deny_cid = trim($deny_cid);
4337 $updated_fields['deny_cid'] = $deny_cid;
4340 if (!is_null($allow_gid)) {
4341 $allow_gid = trim($allow_gid);
4342 $updated_fields['allow_gid'] = $allow_gid;
4345 if (!is_null($deny_gid)) {
4346 $deny_gid = trim($deny_gid);
4347 $updated_fields['deny_gid'] = $deny_gid;
4351 if (count($updated_fields) > 0) {
4352 $nothingtodo = false;
4353 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4355 $nothingtodo = true;
4358 if (!empty($_FILES['media'])) {
4359 $nothingtodo = false;
4360 $media = $_FILES['media'];
4361 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4362 if (!is_null($data)) {
4363 return api_format_data("photo_update", $type, $data);
4367 // return success of updating or error message
4369 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4370 return api_format_data("photo_update", $type, ['$result' => $answer]);
4373 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4374 return api_format_data("photo_update", $type, ['$result' => $answer]);
4376 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4379 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4383 * @brief delete a single photo from the database through api
4385 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4386 * @return string|array
4387 * @throws BadRequestException
4388 * @throws ForbiddenException
4389 * @throws InternalServerErrorException
4391 function api_fr_photo_delete($type)
4393 if (api_user() === false) {
4394 throw new ForbiddenException();
4398 $photo_id = defaults($_REQUEST, 'photo_id', null);
4400 // do several checks on input parameters
4401 // we do not allow calls without photo id
4402 if ($photo_id == null) {
4403 throw new BadRequestException("no photo_id specified");
4406 // check if photo is existing in database
4407 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4408 throw new BadRequestException("photo not available");
4411 // now we can perform on the deletion of the photo
4412 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4414 // return success of deletion or error message
4416 // retrieve the id of the parent element (the photo element)
4417 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4418 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4420 if (!DBA::isResult($photo_item)) {
4421 throw new InternalServerErrorException("problem with deleting items occured");
4423 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4424 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4425 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4427 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4428 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4430 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4436 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4438 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4439 * @return string|array
4440 * @throws BadRequestException
4441 * @throws ForbiddenException
4442 * @throws InternalServerErrorException
4443 * @throws NotFoundException
4445 function api_fr_photo_detail($type)
4447 if (api_user() === false) {
4448 throw new ForbiddenException();
4450 if (empty($_REQUEST['photo_id'])) {
4451 throw new BadRequestException("No photo id.");
4454 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4455 $photo_id = $_REQUEST['photo_id'];
4457 // prepare json/xml output with data from database for the requested photo
4458 $data = prepare_photo_data($type, $scale, $photo_id);
4460 return api_format_data("photo_detail", $type, $data);
4465 * Updates the user’s profile image.
4467 * @brief updates the profile image for the user (either a specified profile or the default profile)
4469 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4471 * @return string|array
4472 * @throws BadRequestException
4473 * @throws ForbiddenException
4474 * @throws ImagickException
4475 * @throws InternalServerErrorException
4476 * @throws NotFoundException
4477 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4479 function api_account_update_profile_image($type)
4481 if (api_user() === false) {
4482 throw new ForbiddenException();
4485 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4487 // error if image data is missing
4488 if (empty($_FILES['image'])) {
4489 throw new BadRequestException("no media data submitted");
4492 // check if specified profile id is valid
4493 if ($profile_id != 0) {
4494 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4495 // error message if specified profile id is not in database
4496 if (!DBA::isResult($profile)) {
4497 throw new BadRequestException("profile_id not available");
4499 $is_default_profile = $profile['is-default'];
4501 $is_default_profile = 1;
4504 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4506 if (!empty($_FILES['image'])) {
4507 $media = $_FILES['image'];
4508 } elseif (!empty($_FILES['media'])) {
4509 $media = $_FILES['media'];
4511 // save new profile image
4512 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4515 if (is_array($media['type'])) {
4516 $filetype = $media['type'][0];
4518 $filetype = $media['type'];
4520 if ($filetype == "image/jpeg") {
4522 } elseif ($filetype == "image/png") {
4525 throw new InternalServerErrorException('Unsupported filetype');
4528 // change specified profile or all profiles to the new resource-id
4529 if ($is_default_profile) {
4530 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4531 Photo::update(['profile' => false], $condition);
4533 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4534 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4535 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4538 Contact::updateSelfFromUserID(api_user(), true);
4540 // Update global directory in background
4541 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4542 if ($url && strlen(Config::get('system', 'directory'))) {
4543 Worker::add(PRIORITY_LOW, "Directory", $url);
4546 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4548 // output for client
4550 return api_account_verify_credentials($type);
4552 // SaveMediaToDatabase failed for some reason
4553 throw new InternalServerErrorException("image upload failed");
4557 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4558 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4559 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4560 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4561 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4562 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4563 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4564 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4565 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4568 * Update user profile
4570 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4572 * @return array|string
4573 * @throws BadRequestException
4574 * @throws ForbiddenException
4575 * @throws ImagickException
4576 * @throws InternalServerErrorException
4577 * @throws UnauthorizedException
4579 function api_account_update_profile($type)
4581 $local_user = api_user();
4582 $api_user = api_get_user(get_app());
4584 if (!empty($_POST['name'])) {
4585 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4586 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4587 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4588 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4591 if (isset($_POST['description'])) {
4592 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4593 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4594 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4597 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4598 // Update global directory in background
4599 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4600 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4603 return api_account_verify_credentials($type);
4606 /// @TODO move to top of file or somewhere better
4607 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4611 * @param string $acl_string
4615 function check_acl_input($acl_string)
4617 if ($acl_string == null || $acl_string == " ") {
4620 $contact_not_found = false;
4622 // split <x><y><z> into array of cid's
4623 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4625 // check for each cid if it is available on server
4626 $cid_array = $array[0];
4627 foreach ($cid_array as $cid) {
4628 $cid = str_replace("<", "", $cid);
4629 $cid = str_replace(">", "", $cid);
4630 $condition = ['id' => $cid, 'uid' => api_user()];
4631 $contact_not_found |= !DBA::exists('contact', $condition);
4633 return $contact_not_found;
4638 * @param string $mediatype
4639 * @param array $media
4640 * @param string $type
4641 * @param string $album
4642 * @param string $allow_cid
4643 * @param string $deny_cid
4644 * @param string $allow_gid
4645 * @param string $deny_gid
4646 * @param string $desc
4647 * @param integer $profile
4648 * @param boolean $visibility
4649 * @param string $photo_id
4651 * @throws BadRequestException
4652 * @throws ForbiddenException
4653 * @throws ImagickException
4654 * @throws InternalServerErrorException
4655 * @throws NotFoundException
4657 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)
4665 if (is_array($media)) {
4666 if (is_array($media['tmp_name'])) {
4667 $src = $media['tmp_name'][0];
4669 $src = $media['tmp_name'];
4671 if (is_array($media['name'])) {
4672 $filename = basename($media['name'][0]);
4674 $filename = basename($media['name']);
4676 if (is_array($media['size'])) {
4677 $filesize = intval($media['size'][0]);
4679 $filesize = intval($media['size']);
4681 if (is_array($media['type'])) {
4682 $filetype = $media['type'][0];
4684 $filetype = $media['type'];
4688 if ($filetype == "") {
4689 $filetype=Image::guessType($filename);
4691 $imagedata = @getimagesize($src);
4693 $filetype = $imagedata['mime'];
4696 "File upload src: " . $src . " - filename: " . $filename .
4697 " - size: " . $filesize . " - type: " . $filetype,
4701 // check if there was a php upload error
4702 if ($filesize == 0 && $media['error'] == 1) {
4703 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4705 // check against max upload size within Friendica instance
4706 $maximagesize = Config::get('system', 'maximagesize');
4707 if ($maximagesize && ($filesize > $maximagesize)) {
4708 $formattedBytes = Strings::formatBytes($maximagesize);
4709 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4712 // create Photo instance with the data of the image
4713 $imagedata = @file_get_contents($src);
4714 $Image = new Image($imagedata, $filetype);
4715 if (!$Image->isValid()) {
4716 throw new InternalServerErrorException("unable to process image data");
4719 // check orientation of image
4720 $Image->orient($src);
4723 // check max length of images on server
4724 $max_length = Config::get('system', 'max_image_length');
4726 $max_length = MAX_IMAGE_LENGTH;
4728 if ($max_length > 0) {
4729 $Image->scaleDown($max_length);
4730 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4732 $width = $Image->getWidth();
4733 $height = $Image->getHeight();
4735 // create a new resource-id if not already provided
4736 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4738 if ($mediatype == "photo") {
4739 // upload normal image (scales 0, 1, 2)
4740 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4742 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4744 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4746 if ($width > 640 || $height > 640) {
4747 $Image->scaleDown(640);
4748 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4750 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4754 if ($width > 320 || $height > 320) {
4755 $Image->scaleDown(320);
4756 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4758 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4761 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4762 } elseif ($mediatype == "profileimage") {
4763 // upload profile image (scales 4, 5, 6)
4764 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4766 if ($width > 300 || $height > 300) {
4767 $Image->scaleDown(300);
4768 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4770 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4774 if ($width > 80 || $height > 80) {
4775 $Image->scaleDown(80);
4776 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4778 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4782 if ($width > 48 || $height > 48) {
4783 $Image->scaleDown(48);
4784 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4786 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4789 $Image->__destruct();
4790 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4793 if (isset($r) && $r) {
4794 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4795 if ($photo_id == null && $mediatype == "photo") {
4796 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4798 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4799 return prepare_photo_data($type, false, $hash);
4801 throw new InternalServerErrorException("image upload failed");
4807 * @param string $hash
4808 * @param string $allow_cid
4809 * @param string $deny_cid
4810 * @param string $allow_gid
4811 * @param string $deny_gid
4812 * @param string $filetype
4813 * @param boolean $visibility
4814 * @throws InternalServerErrorException
4816 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4818 // get data about the api authenticated user
4819 $uri = Item::newURI(intval(api_user()));
4820 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4823 $arr['guid'] = System::createUUID();
4824 $arr['uid'] = intval(api_user());
4826 $arr['parent-uri'] = $uri;
4827 $arr['type'] = 'photo';
4829 $arr['resource-id'] = $hash;
4830 $arr['contact-id'] = $owner_record['id'];
4831 $arr['owner-name'] = $owner_record['name'];
4832 $arr['owner-link'] = $owner_record['url'];
4833 $arr['owner-avatar'] = $owner_record['thumb'];
4834 $arr['author-name'] = $owner_record['name'];
4835 $arr['author-link'] = $owner_record['url'];
4836 $arr['author-avatar'] = $owner_record['thumb'];
4838 $arr['allow_cid'] = $allow_cid;
4839 $arr['allow_gid'] = $allow_gid;
4840 $arr['deny_cid'] = $deny_cid;
4841 $arr['deny_gid'] = $deny_gid;
4842 $arr['visible'] = $visibility;
4846 'image/jpeg' => 'jpg',
4847 'image/png' => 'png',
4848 'image/gif' => 'gif'
4851 // adds link to the thumbnail scale photo
4852 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4853 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4856 // do the magic for storing the item in the database and trigger the federation to other contacts
4862 * @param string $type
4864 * @param string $photo_id
4867 * @throws BadRequestException
4868 * @throws ForbiddenException
4869 * @throws ImagickException
4870 * @throws InternalServerErrorException
4871 * @throws NotFoundException
4872 * @throws UnauthorizedException
4874 function prepare_photo_data($type, $scale, $photo_id)
4877 $user_info = api_get_user($a);
4879 if ($user_info === false) {
4880 throw new ForbiddenException();
4883 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4884 $data_sql = ($scale === false ? "" : "data, ");
4886 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4887 // clients needs to convert this in their way for further processing
4889 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4890 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4891 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4892 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4893 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4894 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4896 intval(local_user()),
4897 DBA::escape($photo_id),
4902 'image/jpeg' => 'jpg',
4903 'image/png' => 'png',
4904 'image/gif' => 'gif'
4907 // prepare output data for photo
4908 if (DBA::isResult($r)) {
4909 $data = ['photo' => $r[0]];
4910 $data['photo']['id'] = $data['photo']['resource-id'];
4911 if ($scale !== false) {
4912 $data['photo']['data'] = base64_encode($data['photo']['data']);
4914 unset($data['photo']['datasize']); //needed only with scale param
4916 if ($type == "xml") {
4917 $data['photo']['links'] = [];
4918 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4919 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4921 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4924 $data['photo']['link'] = [];
4925 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4927 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4928 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4932 unset($data['photo']['resource-id']);
4933 unset($data['photo']['minscale']);
4934 unset($data['photo']['maxscale']);
4936 throw new NotFoundException();
4939 // retrieve item element for getting activities (like, dislike etc.) related to photo
4940 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4941 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4943 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4945 // retrieve comments on photo
4946 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4947 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4949 $statuses = Item::selectForUser(api_user(), [], $condition);
4951 // prepare output of comments
4952 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
4954 if ($type == "xml") {
4956 foreach ($commentData as $comment) {
4957 $comments[$k++ . ":comment"] = $comment;
4960 foreach ($commentData as $comment) {
4961 $comments[] = $comment;
4964 $data['photo']['friendica_comments'] = $comments;
4966 // include info if rights on photo and rights on item are mismatching
4967 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4968 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4969 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4970 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4971 $data['photo']['rights_mismatch'] = $rights_mismatch;
4978 * Similar as /mod/redir.php
4979 * redirect to 'url' after dfrn auth
4981 * Why this when there is mod/redir.php already?
4982 * This use api_user() and api_login()
4985 * c_url: url of remote contact to auth to
4986 * url: string, url to redirect after auth
4988 function api_friendica_remoteauth()
4990 $url = defaults($_GET, 'url', '');
4991 $c_url = defaults($_GET, 'c_url', '');
4993 if ($url === '' || $c_url === '') {
4994 throw new BadRequestException("Wrong parameters.");
4997 $c_url = Strings::normaliseLink($c_url);
5001 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5003 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
5004 throw new BadRequestException("Unknown contact");
5007 $cid = $contact['id'];
5009 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
5011 if ($contact['duplex'] && $contact['issued-id']) {
5012 $orig_id = $contact['issued-id'];
5013 $dfrn_id = '1:' . $orig_id;
5015 if ($contact['duplex'] && $contact['dfrn-id']) {
5016 $orig_id = $contact['dfrn-id'];
5017 $dfrn_id = '0:' . $orig_id;
5020 $sec = Strings::getRandomHex();
5022 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5023 'sec' => $sec, 'expire' => time() + 45];
5024 DBA::insert('profile_check', $fields);
5026 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5027 $dest = ($url ? '&destination_url=' . $url : '');
5029 System::externalRedirect(
5030 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5031 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5032 . '&type=profile&sec=' . $sec . $dest
5035 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5038 * Return an item with announcer data if it had been announced
5040 * @param array $item Item array
5041 * @return array Item array with announce data
5043 function api_get_announce($item)
5045 // Quit if the item already has got a different owner and author
5046 if ($item['owner-id'] != $item['author-id']) {
5050 // Don't change original or Diaspora posts
5051 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5055 // Quit if we do now the original author and it had been a post from a native network
5056 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5060 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5061 $activity = Item::activityToIndex(ACTIVITY2_ANNOUNCE);
5062 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5063 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5064 if (!DBA::isResult($announce)) {
5068 return array_merge($item, $announce);
5072 * @brief Return the item shared, if the item contains only the [share] tag
5074 * @param array $item Sharer item
5075 * @return array|false Shared item or false if not a reshare
5076 * @throws ImagickException
5077 * @throws InternalServerErrorException
5079 function api_share_as_retweet(&$item)
5081 $body = trim($item["body"]);
5083 if (Diaspora::isReshare($body, false) === false) {
5084 if ($item['author-id'] == $item['owner-id']) {
5087 // Reshares from OStatus, ActivityPub and Twitter
5088 $reshared_item = $item;
5089 $reshared_item['owner-id'] = $reshared_item['author-id'];
5090 $reshared_item['owner-link'] = $reshared_item['author-link'];
5091 $reshared_item['owner-name'] = $reshared_item['author-name'];
5092 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5093 return $reshared_item;
5097 /// @TODO "$1" should maybe mean '$1' ?
5098 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
5100 * Skip if there is no shared message in there
5101 * we already checked this in diaspora::isReshare()
5102 * but better one more than one less...
5104 if (($body == $attributes) || empty($attributes)) {
5108 // build the fake reshared item
5109 $reshared_item = $item;
5112 preg_match("/author='(.*?)'/ism", $attributes, $matches);
5113 if (!empty($matches[1])) {
5114 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
5117 preg_match('/author="(.*?)"/ism', $attributes, $matches);
5118 if (!empty($matches[1])) {
5119 $author = $matches[1];
5123 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
5124 if (!empty($matches[1])) {
5125 $profile = $matches[1];
5128 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
5129 if (!empty($matches[1])) {
5130 $profile = $matches[1];
5134 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
5135 if (!empty($matches[1])) {
5136 $avatar = $matches[1];
5139 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
5140 if (!empty($matches[1])) {
5141 $avatar = $matches[1];
5145 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5146 if (!empty($matches[1])) {
5147 $link = $matches[1];
5150 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5151 if (!empty($matches[1])) {
5152 $link = $matches[1];
5156 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5157 if (!empty($matches[1])) {
5158 $posted = $matches[1];
5161 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5162 if (!empty($matches[1])) {
5163 $posted = $matches[1];
5166 if (!preg_match("/(.*?)\[share.*?\]\s?(.*?)\s?\[\/share\]\s?(.*?)/ism", $body, $matches)) {
5170 $pre_body = trim($matches[1]);
5171 if ($pre_body != '') {
5172 $item['body'] = $pre_body;
5175 $shared_body = trim($matches[2]);
5177 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5181 $reshared_item["share-pre-body"] = $pre_body;
5182 $reshared_item["body"] = $shared_body;
5183 $reshared_item["author-id"] = Contact::getIdForURL($profile, 0, true);
5184 $reshared_item["author-name"] = $author;
5185 $reshared_item["author-link"] = $profile;
5186 $reshared_item["author-avatar"] = $avatar;
5187 $reshared_item["plink"] = $link;
5188 $reshared_item["created"] = $posted;
5189 $reshared_item["edited"] = $posted;
5191 return $reshared_item;
5196 * @param string $profile
5198 * @return string|false
5199 * @throws InternalServerErrorException
5200 * @todo remove trailing junk from profile url
5201 * @todo pump.io check has to check the website
5203 function api_get_nick($profile)
5208 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5209 DBA::escape(Strings::normaliseLink($profile))
5212 if (DBA::isResult($r)) {
5213 $nick = $r[0]["nick"];
5218 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5219 DBA::escape(Strings::normaliseLink($profile))
5222 if (DBA::isResult($r)) {
5223 $nick = $r[0]["nick"];
5228 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5229 if ($friendica != $profile) {
5235 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5236 if ($diaspora != $profile) {
5242 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5243 if ($twitter != $profile) {
5250 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5251 if ($StatusnetHost != $profile) {
5252 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5253 if ($StatusnetUser != $profile) {
5254 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5255 $user = json_decode($UserData);
5257 $nick = $user->screen_name;
5263 // To-Do: look at the page if its really a pumpio site
5264 //if (!$nick == "") {
5265 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5266 // if ($pumpio != $profile)
5268 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5281 * @param array $item
5286 function api_in_reply_to($item)
5290 $in_reply_to['status_id'] = null;
5291 $in_reply_to['user_id'] = null;
5292 $in_reply_to['status_id_str'] = null;
5293 $in_reply_to['user_id_str'] = null;
5294 $in_reply_to['screen_name'] = null;
5296 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5297 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5298 if (DBA::isResult($parent)) {
5299 $in_reply_to['status_id'] = intval($parent['id']);
5301 $in_reply_to['status_id'] = intval($item['parent']);
5304 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5306 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5307 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5309 if (DBA::isResult($parent)) {
5310 if ($parent['author-nick'] == "") {
5311 $parent['author-nick'] = api_get_nick($parent['author-link']);
5314 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5315 $in_reply_to['user_id'] = intval($parent['author-id']);
5316 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5319 // There seems to be situation, where both fields are identical:
5320 // https://github.com/friendica/friendica/issues/1010
5321 // This is a bugfix for that.
5322 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5323 Logger::warning(API_LOG_PREFIX . 'ID {id} is similar to reply-to {reply-to}', ['module' => 'api', 'action' => 'in_reply_to', 'id' => $item['id'], 'reply-to' => $in_reply_to['status_id']]);
5324 $in_reply_to['status_id'] = null;
5325 $in_reply_to['user_id'] = null;
5326 $in_reply_to['status_id_str'] = null;
5327 $in_reply_to['user_id_str'] = null;
5328 $in_reply_to['screen_name'] = null;
5332 return $in_reply_to;
5337 * @param string $text
5340 * @throws InternalServerErrorException
5342 function api_clean_plain_items($text)
5344 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
5346 $text = BBCode::cleanPictureLinks($text);
5347 $URLSearchString = "^\[\]";
5349 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5351 if ($include_entities == "true") {
5352 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5355 // Simplify "attachment" element
5356 $text = api_clean_attachments($text);
5362 * @brief Removes most sharing information for API text export
5364 * @param string $body The original body
5366 * @return string Cleaned body
5367 * @throws InternalServerErrorException
5369 function api_clean_attachments($body)
5371 $data = BBCode::getAttachmentData($body);
5378 if (isset($data["text"])) {
5379 $body = $data["text"];
5381 if (($body == "") && isset($data["title"])) {
5382 $body = $data["title"];
5384 if (isset($data["url"])) {
5385 $body .= "\n".$data["url"];
5387 $body .= $data["after"];
5394 * @param array $contacts
5398 function api_best_nickname(&$contacts)
5402 if (count($contacts) == 0) {
5406 foreach ($contacts as $contact) {
5407 if ($contact["network"] == "") {
5408 $contact["network"] = "dfrn";
5409 $best_contact = [$contact];
5413 if (sizeof($best_contact) == 0) {
5414 foreach ($contacts as $contact) {
5415 if ($contact["network"] == "dfrn") {
5416 $best_contact = [$contact];
5421 if (sizeof($best_contact) == 0) {
5422 foreach ($contacts as $contact) {
5423 if ($contact["network"] == "dspr") {
5424 $best_contact = [$contact];
5429 if (sizeof($best_contact) == 0) {
5430 foreach ($contacts as $contact) {
5431 if ($contact["network"] == "stat") {
5432 $best_contact = [$contact];
5437 if (sizeof($best_contact) == 0) {
5438 foreach ($contacts as $contact) {
5439 if ($contact["network"] == "pump") {
5440 $best_contact = [$contact];
5445 if (sizeof($best_contact) == 0) {
5446 foreach ($contacts as $contact) {
5447 if ($contact["network"] == "twit") {
5448 $best_contact = [$contact];
5453 if (sizeof($best_contact) == 1) {
5454 $contacts = $best_contact;
5456 $contacts = [$contacts[0]];
5461 * Return all or a specified group of the user with the containing contacts.
5463 * @param string $type Return type (atom, rss, xml, json)
5465 * @return array|string
5466 * @throws BadRequestException
5467 * @throws ForbiddenException
5468 * @throws ImagickException
5469 * @throws InternalServerErrorException
5470 * @throws UnauthorizedException
5472 function api_friendica_group_show($type)
5476 if (api_user() === false) {
5477 throw new ForbiddenException();
5481 $user_info = api_get_user($a);
5482 $gid = defaults($_REQUEST, 'gid', 0);
5483 $uid = $user_info['uid'];
5485 // get data of the specified group id or all groups if not specified
5488 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5492 // error message if specified gid is not in database
5493 if (!DBA::isResult($r)) {
5494 throw new BadRequestException("gid not available");
5498 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5503 // loop through all groups and retrieve all members for adding data in the user array
5505 foreach ($r as $rr) {
5506 $members = Contact::getByGroupId($rr['id']);
5509 if ($type == "xml") {
5510 $user_element = "users";
5512 foreach ($members as $member) {
5513 $user = api_get_user($a, $member['nurl']);
5514 $users[$k++.":user"] = $user;
5517 $user_element = "user";
5518 foreach ($members as $member) {
5519 $user = api_get_user($a, $member['nurl']);
5523 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5525 return api_format_data("groups", $type, ['group' => $grps]);
5527 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5531 * Delete the specified group of the user.
5533 * @param string $type Return type (atom, rss, xml, json)
5535 * @return array|string
5536 * @throws BadRequestException
5537 * @throws ForbiddenException
5538 * @throws ImagickException
5539 * @throws InternalServerErrorException
5540 * @throws UnauthorizedException
5542 function api_friendica_group_delete($type)
5546 if (api_user() === false) {
5547 throw new ForbiddenException();
5551 $user_info = api_get_user($a);
5552 $gid = defaults($_REQUEST, 'gid', 0);
5553 $name = defaults($_REQUEST, 'name', "");
5554 $uid = $user_info['uid'];
5556 // error if no gid specified
5557 if ($gid == 0 || $name == "") {
5558 throw new BadRequestException('gid or name not specified');
5561 // get data of the specified group id
5563 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5567 // error message if specified gid is not in database
5568 if (!DBA::isResult($r)) {
5569 throw new BadRequestException('gid not available');
5572 // get data of the specified group id and group name
5574 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5579 // error message if specified gid is not in database
5580 if (!DBA::isResult($rname)) {
5581 throw new BadRequestException('wrong group name');
5585 $ret = Group::removeByName($uid, $name);
5588 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5589 return api_format_data("group_delete", $type, ['result' => $success]);
5591 throw new BadRequestException('other API error');
5594 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5599 * @param string $type Return type (atom, rss, xml, json)
5601 * @return array|string
5602 * @throws BadRequestException
5603 * @throws ForbiddenException
5604 * @throws ImagickException
5605 * @throws InternalServerErrorException
5606 * @throws UnauthorizedException
5607 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5609 function api_lists_destroy($type)
5613 if (api_user() === false) {
5614 throw new ForbiddenException();
5618 $user_info = api_get_user($a);
5619 $gid = defaults($_REQUEST, 'list_id', 0);
5620 $uid = $user_info['uid'];
5622 // error if no gid specified
5624 throw new BadRequestException('gid not specified');
5627 // get data of the specified group id
5628 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5629 // error message if specified gid is not in database
5631 throw new BadRequestException('gid not available');
5634 if (Group::remove($gid)) {
5636 'name' => $group['name'],
5637 'id' => intval($gid),
5638 'id_str' => (string) $gid,
5639 'user' => $user_info
5642 return api_format_data("lists", $type, ['lists' => $list]);
5645 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5648 * Add a new group to the database.
5650 * @param string $name Group name
5651 * @param int $uid User ID
5652 * @param array $users List of users to add to the group
5655 * @throws BadRequestException
5657 function group_create($name, $uid, $users = [])
5659 // error if no name specified
5661 throw new BadRequestException('group name not specified');
5664 // get data of the specified group name
5666 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5670 // error message if specified group name already exists
5671 if (DBA::isResult($rname)) {
5672 throw new BadRequestException('group name already exists');
5675 // check if specified group name is a deleted group
5677 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5681 // error message if specified group name already exists
5682 if (DBA::isResult($rname)) {
5683 $reactivate_group = true;
5687 $ret = Group::create($uid, $name);
5689 $gid = Group::getIdByName($uid, $name);
5691 throw new BadRequestException('other API error');
5695 $erroraddinguser = false;
5697 foreach ($users as $user) {
5698 $cid = $user['cid'];
5699 // check if user really exists as contact
5701 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5705 if (count($contact)) {
5706 Group::addMember($gid, $cid);
5708 $erroraddinguser = true;
5709 $errorusers[] = $cid;
5713 // return success message incl. missing users in array
5714 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5716 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5720 * Create the specified group with the posted array of contacts.
5722 * @param string $type Return type (atom, rss, xml, json)
5724 * @return array|string
5725 * @throws BadRequestException
5726 * @throws ForbiddenException
5727 * @throws ImagickException
5728 * @throws InternalServerErrorException
5729 * @throws UnauthorizedException
5731 function api_friendica_group_create($type)
5735 if (api_user() === false) {
5736 throw new ForbiddenException();
5740 $user_info = api_get_user($a);
5741 $name = defaults($_REQUEST, 'name', "");
5742 $uid = $user_info['uid'];
5743 $json = json_decode($_POST['json'], true);
5744 $users = $json['user'];
5746 $success = group_create($name, $uid, $users);
5748 return api_format_data("group_create", $type, ['result' => $success]);
5750 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5753 * Create a new group.
5755 * @param string $type Return type (atom, rss, xml, json)
5757 * @return array|string
5758 * @throws BadRequestException
5759 * @throws ForbiddenException
5760 * @throws ImagickException
5761 * @throws InternalServerErrorException
5762 * @throws UnauthorizedException
5763 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5765 function api_lists_create($type)
5769 if (api_user() === false) {
5770 throw new ForbiddenException();
5774 $user_info = api_get_user($a);
5775 $name = defaults($_REQUEST, 'name', "");
5776 $uid = $user_info['uid'];
5778 $success = group_create($name, $uid);
5779 if ($success['success']) {
5781 'name' => $success['name'],
5782 'id' => intval($success['gid']),
5783 'id_str' => (string) $success['gid'],
5784 'user' => $user_info
5787 return api_format_data("lists", $type, ['lists'=>$grp]);
5790 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5793 * Update the specified group with the posted array of contacts.
5795 * @param string $type Return type (atom, rss, xml, json)
5797 * @return array|string
5798 * @throws BadRequestException
5799 * @throws ForbiddenException
5800 * @throws ImagickException
5801 * @throws InternalServerErrorException
5802 * @throws UnauthorizedException
5804 function api_friendica_group_update($type)
5808 if (api_user() === false) {
5809 throw new ForbiddenException();
5813 $user_info = api_get_user($a);
5814 $uid = $user_info['uid'];
5815 $gid = defaults($_REQUEST, 'gid', 0);
5816 $name = defaults($_REQUEST, 'name', "");
5817 $json = json_decode($_POST['json'], true);
5818 $users = $json['user'];
5820 // error if no name specified
5822 throw new BadRequestException('group name not specified');
5825 // error if no gid specified
5827 throw new BadRequestException('gid not specified');
5831 $members = Contact::getByGroupId($gid);
5832 foreach ($members as $member) {
5833 $cid = $member['id'];
5834 foreach ($users as $user) {
5835 $found = ($user['cid'] == $cid ? true : false);
5837 if (!isset($found) || !$found) {
5838 Group::removeMemberByName($uid, $name, $cid);
5843 $erroraddinguser = false;
5845 foreach ($users as $user) {
5846 $cid = $user['cid'];
5847 // check if user really exists as contact
5849 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5854 if (count($contact)) {
5855 Group::addMember($gid, $cid);
5857 $erroraddinguser = true;
5858 $errorusers[] = $cid;
5862 // return success message incl. missing users in array
5863 $status = ($erroraddinguser ? "missing user" : "ok");
5864 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5865 return api_format_data("group_update", $type, ['result' => $success]);
5868 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5871 * Update information about a group.
5873 * @param string $type Return type (atom, rss, xml, json)
5875 * @return array|string
5876 * @throws BadRequestException
5877 * @throws ForbiddenException
5878 * @throws ImagickException
5879 * @throws InternalServerErrorException
5880 * @throws UnauthorizedException
5881 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5883 function api_lists_update($type)
5887 if (api_user() === false) {
5888 throw new ForbiddenException();
5892 $user_info = api_get_user($a);
5893 $gid = defaults($_REQUEST, 'list_id', 0);
5894 $name = defaults($_REQUEST, 'name', "");
5895 $uid = $user_info['uid'];
5897 // error if no gid specified
5899 throw new BadRequestException('gid not specified');
5902 // get data of the specified group id
5903 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5904 // error message if specified gid is not in database
5906 throw new BadRequestException('gid not available');
5909 if (Group::update($gid, $name)) {
5912 'id' => intval($gid),
5913 'id_str' => (string) $gid,
5914 'user' => $user_info
5917 return api_format_data("lists", $type, ['lists' => $list]);
5921 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5925 * @param string $type Return type (atom, rss, xml, json)
5927 * @return array|string
5928 * @throws BadRequestException
5929 * @throws ForbiddenException
5930 * @throws ImagickException
5931 * @throws InternalServerErrorException
5933 function api_friendica_activity($type)
5937 if (api_user() === false) {
5938 throw new ForbiddenException();
5940 $verb = strtolower($a->argv[3]);
5941 $verb = preg_replace("|\..*$|", "", $verb);
5943 $id = defaults($_REQUEST, 'id', 0);
5945 $res = Item::performLike($id, $verb);
5948 if ($type == "xml") {
5953 return api_format_data('ok', $type, ['ok' => $ok]);
5955 throw new BadRequestException('Error adding activity');
5959 /// @TODO move to top of file or somewhere better
5960 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5961 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5962 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5963 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5964 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5965 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5966 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5967 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5968 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5969 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5972 * @brief Returns notifications
5974 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5975 * @return string|array
5976 * @throws BadRequestException
5977 * @throws ForbiddenException
5978 * @throws InternalServerErrorException
5980 function api_friendica_notification($type)
5984 if (api_user() === false) {
5985 throw new ForbiddenException();
5988 throw new BadRequestException("Invalid argument count");
5990 $nm = new NotificationsManager();
5992 $notes = $nm->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
5994 if ($type == "xml") {
5996 if (!empty($notes)) {
5997 foreach ($notes as $note) {
5998 $xmlnotes[] = ["@attributes" => $note];
6004 return api_format_data("notes", $type, ['note' => $notes]);
6008 * POST request with 'id' param as notification id
6010 * @brief Set notification as seen and returns associated item (if possible)
6012 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6013 * @return string|array
6014 * @throws BadRequestException
6015 * @throws ForbiddenException
6016 * @throws ImagickException
6017 * @throws InternalServerErrorException
6018 * @throws UnauthorizedException
6020 function api_friendica_notification_seen($type)
6023 $user_info = api_get_user($a);
6025 if (api_user() === false || $user_info === false) {
6026 throw new ForbiddenException();
6029 throw new BadRequestException("Invalid argument count");
6032 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
6034 $nm = new NotificationsManager();
6035 $note = $nm->getByID($id);
6036 if (is_null($note)) {
6037 throw new BadRequestException("Invalid argument");
6040 $nm->setSeen($note);
6041 if ($note['otype']=='item') {
6042 // would be really better with an ItemsManager and $im->getByID() :-P
6043 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
6044 if (DBA::isResult($item)) {
6045 // we found the item, return it to the user
6046 $ret = api_format_items([$item], $user_info, false, $type);
6047 $data = ['status' => $ret];
6048 return api_format_data("status", $type, $data);
6050 // the item can't be found, but we set the note as seen, so we count this as a success
6052 return api_format_data('result', $type, ['result' => "success"]);
6055 /// @TODO move to top of file or somewhere better
6056 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
6057 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
6060 * @brief update a direct_message to seen state
6062 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6063 * @return string|array (success result=ok, error result=error with error message)
6064 * @throws BadRequestException
6065 * @throws ForbiddenException
6066 * @throws ImagickException
6067 * @throws InternalServerErrorException
6068 * @throws UnauthorizedException
6070 function api_friendica_direct_messages_setseen($type)
6073 if (api_user() === false) {
6074 throw new ForbiddenException();
6078 $user_info = api_get_user($a);
6079 $uid = $user_info['uid'];
6080 $id = defaults($_REQUEST, 'id', 0);
6082 // return error if id is zero
6084 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6085 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6088 // error message if specified id is not in database
6089 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6090 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6091 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6094 // update seen indicator
6095 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6099 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6100 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6102 $answer = ['result' => 'error', 'message' => 'unknown error'];
6103 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6107 /// @TODO move to top of file or somewhere better
6108 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6111 * @brief search for direct_messages containing a searchstring through api
6113 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6114 * @param string $box
6115 * @return string|array (success: success=true if found and search_result contains found messages,
6116 * success=false if nothing was found, search_result='nothing found',
6117 * error: result=error with error message)
6118 * @throws BadRequestException
6119 * @throws ForbiddenException
6120 * @throws ImagickException
6121 * @throws InternalServerErrorException
6122 * @throws UnauthorizedException
6124 function api_friendica_direct_messages_search($type, $box = "")
6128 if (api_user() === false) {
6129 throw new ForbiddenException();
6133 $user_info = api_get_user($a);
6134 $searchstring = defaults($_REQUEST, 'searchstring', "");
6135 $uid = $user_info['uid'];
6137 // error if no searchstring specified
6138 if ($searchstring == "") {
6139 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6140 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6143 // get data for the specified searchstring
6145 "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",
6147 DBA::escape('%'.$searchstring.'%')
6150 $profile_url = $user_info["url"];
6152 // message if nothing was found
6153 if (!DBA::isResult($r)) {
6154 $success = ['success' => false, 'search_results' => 'problem with query'];
6155 } elseif (count($r) == 0) {
6156 $success = ['success' => false, 'search_results' => 'nothing found'];
6159 foreach ($r as $item) {
6160 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6161 $recipient = $user_info;
6162 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6163 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6164 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6165 $sender = $user_info;
6168 if (isset($recipient) && isset($sender)) {
6169 $ret[] = api_format_messages($item, $recipient, $sender);
6172 $success = ['success' => true, 'search_results' => $ret];
6175 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6178 /// @TODO move to top of file or somewhere better
6179 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6182 * @brief return data of all the profiles a user has to the client
6184 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6185 * @return string|array
6186 * @throws BadRequestException
6187 * @throws ForbiddenException
6188 * @throws ImagickException
6189 * @throws InternalServerErrorException
6190 * @throws UnauthorizedException
6192 function api_friendica_profile_show($type)
6196 if (api_user() === false) {
6197 throw new ForbiddenException();
6201 $profile_id = defaults($_REQUEST, 'profile_id', 0);
6203 // retrieve general information about profiles for user
6204 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6205 $directory = Config::get('system', 'directory');
6207 // get data of the specified profile id or all profiles of the user if not specified
6208 if ($profile_id != 0) {
6209 $r = Profile::getById(api_user(), $profile_id);
6210 // error message if specified gid is not in database
6211 if (!DBA::isResult($r)) {
6212 throw new BadRequestException("profile_id not available");
6215 $r = Profile::getListByUser(api_user());
6217 // loop through all returned profiles and retrieve data and users
6220 if (DBA::isResult($r)) {
6221 foreach ($r as $rr) {
6222 $profile = api_format_items_profiles($rr);
6224 // select all users from contact table, loop and prepare standard return for user data
6226 $nurls = Contact::select(['id', 'nurl'], ['uid' => api_user(), 'profile-id' => $rr['id']]);
6228 if (DBA::isResult($nurls)) {
6229 foreach ($nurls as $nurl) {
6230 $user = api_get_user($a, $nurl['nurl']);
6231 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6234 $profile['users'] = $users;
6236 // add prepared profile data to array for final return
6237 if ($type == "xml") {
6238 $profiles[$k++ . ":profile"] = $profile;
6240 $profiles[] = $profile;
6245 // return settings, authenticated user and profiles data
6246 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6248 $result = ['multi_profiles' => $multi_profiles ? true : false,
6249 'global_dir' => $directory,
6250 'friendica_owner' => api_get_user($a, $self['nurl']),
6251 'profiles' => $profiles];
6252 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6254 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6257 * Returns a list of saved searches.
6259 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6261 * @param string $type Return format: json or xml
6263 * @return string|array
6266 function api_saved_searches_list($type)
6268 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6271 while ($term = DBA::fetch($terms)) {
6273 'created_at' => api_date(time()),
6274 'id' => intval($term['id']),
6275 'id_str' => $term['id'],
6276 'name' => $term['term'],
6278 'query' => $term['term']
6284 return api_format_data("terms", $type, ['terms' => $result]);
6287 /// @TODO move to top of file or somewhere better
6288 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6291 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6293 * @brief Number of comments
6295 * @param object $data [Status, Status]
6299 function bindComments(&$data)
6301 if (count($data) == 0) {
6307 foreach ($data as $item) {
6308 $ids[] = $item['id'];
6311 $idStr = DBA::escape(implode(', ', $ids));
6312 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6313 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6314 $itemsData = DBA::toArray($items);
6316 foreach ($itemsData as $item) {
6317 $comments[$item['parent']] = $item['comments'];
6320 foreach ($data as $idx => $item) {
6322 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6327 @TODO Maybe open to implement?
6329 [pagename] => api/1.1/statuses/lookup.json
6330 [id] => 605138389168451584
6331 [include_cards] => true
6332 [cards_platform] => Android-12
6333 [include_entities] => true
6334 [include_my_retweet] => 1
6336 [include_reply_count] => true
6337 [include_descendent_reply_count] => true
6341 Not implemented by now:
6342 statuses/retweets_of_me
6347 account/update_location
6348 account/update_profile_background_image
6351 friendica/profile/update
6352 friendica/profile/create
6353 friendica/profile/delete
6355 Not implemented in status.net:
6356 statuses/retweeted_to_me
6357 statuses/retweeted_by_me
6358 direct_messages/destroy
6360 account/update_delivery_device
6361 notifications/follow