3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\Content\ContactSelector;
11 use Friendica\Content\Feature;
12 use Friendica\Content\Text\BBCode;
13 use Friendica\Content\Text\HTML;
14 use Friendica\Core\Authentication;
15 use Friendica\Core\Config;
16 use Friendica\Core\Hook;
17 use Friendica\Core\L10n;
18 use Friendica\Core\Logger;
19 use Friendica\Core\NotificationsManager;
20 use Friendica\Core\PConfig;
21 use Friendica\Core\Protocol;
22 use Friendica\Core\System;
23 use Friendica\Core\Worker;
24 use Friendica\Database\DBA;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Group;
27 use Friendica\Model\Item;
28 use Friendica\Model\Mail;
29 use Friendica\Model\Photo;
30 use Friendica\Model\User;
31 use Friendica\Network\FKOAuth1;
32 use Friendica\Network\HTTPException;
33 use Friendica\Network\HTTPException\BadRequestException;
34 use Friendica\Network\HTTPException\ExpectationFailedException;
35 use Friendica\Network\HTTPException\ForbiddenException;
36 use Friendica\Network\HTTPException\InternalServerErrorException;
37 use Friendica\Network\HTTPException\MethodNotAllowedException;
38 use Friendica\Network\HTTPException\NotFoundException;
39 use Friendica\Network\HTTPException\NotImplementedException;
40 use Friendica\Network\HTTPException\TooManyRequestsException;
41 use Friendica\Network\HTTPException\UnauthorizedException;
42 use Friendica\Object\Image;
43 use Friendica\Protocol\Diaspora;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Network;
46 use Friendica\Util\Proxy as ProxyUtils;
47 use Friendica\Util\Strings;
48 use Friendica\Util\XML;
50 require_once 'mod/share.php';
51 require_once 'mod/item.php';
52 require_once 'mod/wall_upload.php';
54 define('API_METHOD_ANY', '*');
55 define('API_METHOD_GET', 'GET');
56 define('API_METHOD_POST', 'POST,PUT');
57 define('API_METHOD_DELETE', 'POST,DELETE');
59 define('API_LOG_PREFIX', 'API {action} - ');
65 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
66 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
67 * into a page, and visitors will post something without noticing it).
69 * @brief Auth API user
73 if (!empty($_SESSION['allow_api'])) {
81 * Clients can send 'source' parameter to be show in post metadata
82 * as "sent via <source>".
83 * Some clients doesn't send a source param, we support ones we know
86 * @brief Get source name from API client
89 * Client source name, default to "api" if unset/unknown
94 if (requestdata('source')) {
95 return requestdata('source');
98 // Support for known clients that doesn't send a source name
99 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
100 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
104 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
106 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
113 * @brief Format date for API
115 * @param string $str Source date, as UTC
116 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
119 function api_date($str)
121 // Wed May 23 06:01:13 +0000 2007
122 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
126 * Register a function to be the endpoint for defined API path.
128 * @brief Register API endpoint
130 * @param string $path API URL path, relative to System::baseUrl()
131 * @param string $func Function name to call on path request
132 * @param bool $auth API need logged user
133 * @param string $method HTTP method reqiured to call this endpoint.
134 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
135 * Default to API_METHOD_ANY
137 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
147 // Workaround for hotot
148 $path = str_replace("api/", "api/1.1/", $path);
158 * Log in user via OAuth1 or Simple HTTP Auth.
159 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
161 * @brief Login API user
164 * @throws InternalServerErrorException
165 * @throws UnauthorizedException
166 * @hook 'authenticate'
168 * 'username' => username from login form
169 * 'password' => password from login form
170 * 'authenticated' => return status,
171 * 'user_record' => return authenticated user record
173 * array $user logged user record
175 function api_login(App $a)
177 $oauth1 = new FKOAuth1();
180 $request = OAuthRequest::from_request();
181 list($consumer, $token) = $oauth1->verify_request($request);
182 if (!is_null($token)) {
183 $oauth1->loginUser($token->uid);
184 Hook::callAll('logged_in', $a->user);
187 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
188 var_dump($consumer, $token);
190 } catch (Exception $e) {
191 Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
194 // workaround for HTTP-auth in CGI mode
195 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
196 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
197 if (strlen($userpass)) {
198 list($name, $password) = explode(':', $userpass);
199 $_SERVER['PHP_AUTH_USER'] = $name;
200 $_SERVER['PHP_AUTH_PW'] = $password;
204 if (empty($_SERVER['PHP_AUTH_USER'])) {
205 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
206 header('WWW-Authenticate: Basic realm="Friendica"');
207 throw new UnauthorizedException("This API requires login");
210 $user = defaults($_SERVER, 'PHP_AUTH_USER', '');
211 $password = defaults($_SERVER, 'PHP_AUTH_PW', '');
213 // allow "user@server" login (but ignore 'server' part)
214 $at = strstr($user, "@", true);
219 // next code from mod/auth.php. needs better solution
223 'username' => trim($user),
224 'password' => trim($password),
225 'authenticated' => 0,
226 'user_record' => null,
230 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
231 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
232 * and later addons should not interfere with an earlier one that succeeded.
234 Hook::callAll('authenticate', $addon_auth);
236 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
237 $record = $addon_auth['user_record'];
239 $user_id = User::authenticate(trim($user), trim($password));
240 if ($user_id !== false) {
241 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
245 if (!DBA::isResult($record)) {
246 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
247 header('WWW-Authenticate: Basic realm="Friendica"');
248 //header('HTTP/1.0 401 Unauthorized');
249 //die('This api requires login');
250 throw new UnauthorizedException("This API requires login");
253 Authentication::setAuthenticatedSessionForUser($record);
255 $_SESSION["allow_api"] = true;
257 Hook::callAll('logged_in', $a->user);
261 * API endpoints can define which HTTP method to accept when called.
262 * This function check the current HTTP method agains endpoint
265 * @brief Check HTTP method of called API
267 * @param string $method Required methods, uppercase, separated by comma
270 function api_check_method($method)
272 if ($method == "*") {
275 return (stripos($method, defaults($_SERVER, 'REQUEST_METHOD', 'GET')) !== false);
279 * Authenticate user, call registered API function, set HTTP headers
281 * @brief Main API entry point
284 * @return string|array API call result
287 function api_call(App $a)
289 global $API, $called_api;
292 if (strpos($a->query_string, ".xml") > 0) {
295 if (strpos($a->query_string, ".json") > 0) {
298 if (strpos($a->query_string, ".rss") > 0) {
301 if (strpos($a->query_string, ".atom") > 0) {
306 foreach ($API as $p => $info) {
307 if (strpos($a->query_string, $p) === 0) {
308 if (!api_check_method($info['method'])) {
309 throw new MethodNotAllowedException();
312 $called_api = explode("/", $p);
313 //unset($_SERVER['PHP_AUTH_USER']);
315 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
316 if (!empty($info['auth']) && api_user() === false) {
320 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
321 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
323 $stamp = microtime(true);
324 $return = call_user_func($info['func'], $type);
325 $duration = (float) (microtime(true) - $stamp);
327 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
329 $a->getProfiler()->saveLog($a->getLogger(), API_LOG_PREFIX . 'performance');
331 if (false === $return) {
333 * api function returned false withour throw an
334 * exception. This should not happend, throw a 500
336 throw new InternalServerErrorException();
341 header("Content-Type: text/xml");
344 header("Content-Type: application/json");
345 $json = json_encode(end($return));
346 if (!empty($_GET['callback'])) {
347 $json = $_GET['callback'] . "(" . $json . ")";
352 header("Content-Type: application/rss+xml");
353 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
356 header("Content-Type: application/atom+xml");
357 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
364 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call']);
365 throw new NotImplementedException();
366 } catch (HTTPException $e) {
367 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
368 return api_error($type, $e);
373 * @brief Format API error string
375 * @param string $type Return type (xml, json, rss, as)
376 * @param object $e HTTPException Error object
377 * @return string|array error message formatted as $type
379 function api_error($type, $e)
383 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
384 /// @TODO: https://dev.twitter.com/overview/api/response-codes
386 $error = ["error" => $error,
387 "code" => $e->httpcode . " " . $e->httpdesc,
388 "request" => $a->query_string];
390 $return = api_format_data('status', $type, ['status' => $error]);
394 header("Content-Type: text/xml");
397 header("Content-Type: application/json");
398 $return = json_encode($return);
401 header("Content-Type: application/rss+xml");
404 header("Content-Type: application/atom+xml");
412 * @brief Set values for RSS template
415 * @param array $arr Array to be passed to template
416 * @param array $user_info User info
418 * @throws BadRequestException
419 * @throws ImagickException
420 * @throws InternalServerErrorException
421 * @throws UnauthorizedException
422 * @todo find proper type-hints
424 function api_rss_extra(App $a, $arr, $user_info)
426 if (is_null($user_info)) {
427 $user_info = api_get_user($a);
430 $arr['$user'] = $user_info;
432 'alternate' => $user_info['url'],
433 'self' => System::baseUrl() . "/" . $a->query_string,
434 'base' => System::baseUrl(),
435 'updated' => api_date(null),
436 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
437 'language' => $user_info['lang'],
438 'logo' => System::baseUrl() . "/images/friendica-32.png",
446 * @brief Unique contact to contact url.
448 * @param int $id Contact id
449 * @return bool|string
450 * Contact url or False if contact id is unknown
453 function api_unique_id_to_nurl($id)
455 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
457 if (DBA::isResult($r)) {
465 * @brief Get user info array.
468 * @param int|string $contact_id Contact ID or URL
470 * @throws BadRequestException
471 * @throws ImagickException
472 * @throws InternalServerErrorException
473 * @throws UnauthorizedException
475 function api_get_user(App $a, $contact_id = null)
483 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
485 // Searching for contact URL
486 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
487 $user = DBA::escape(Strings::normaliseLink($contact_id));
489 $extra_query = "AND `contact`.`nurl` = '%s' ";
490 if (api_user() !== false) {
491 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
495 // Searching for contact id with uid = 0
496 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
497 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
500 throw new BadRequestException("User ID ".$contact_id." not found.");
504 $extra_query = "AND `contact`.`nurl` = '%s' ";
505 if (api_user() !== false) {
506 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
510 if (is_null($user) && !empty($_GET['user_id'])) {
511 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
514 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
518 $extra_query = "AND `contact`.`nurl` = '%s' ";
519 if (api_user() !== false) {
520 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
523 if (is_null($user) && !empty($_GET['screen_name'])) {
524 $user = DBA::escape($_GET['screen_name']);
525 $extra_query = "AND `contact`.`nick` = '%s' ";
526 if (api_user() !== false) {
527 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
531 if (is_null($user) && !empty($_GET['profileurl'])) {
532 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
533 $extra_query = "AND `contact`.`nurl` = '%s' ";
534 if (api_user() !== false) {
535 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
539 // $called_api is the API path exploded on / and is expected to have at least 2 elements
540 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
541 $argid = count($called_api);
542 if (!empty($a->argv[$argid])) {
543 $data = explode(".", $a->argv[$argid]);
544 if (count($data) > 1) {
545 list($user, $null) = $data;
548 if (is_numeric($user)) {
549 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
553 $extra_query = "AND `contact`.`nurl` = '%s' ";
554 if (api_user() !== false) {
555 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
559 $user = DBA::escape($user);
560 $extra_query = "AND `contact`.`nick` = '%s' ";
561 if (api_user() !== false) {
562 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
567 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
570 if (api_user() === false) {
574 $user = $_SESSION['uid'];
575 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
579 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
583 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
589 // Selecting the id by priority, friendica first
590 if (is_array($uinfo)) {
591 api_best_nickname($uinfo);
594 // if the contact wasn't found, fetch it from the contacts with uid = 0
595 if (!DBA::isResult($uinfo)) {
597 throw new BadRequestException("User not found.");
600 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
602 if (DBA::isResult($contact)) {
603 // If no nick where given, extract it from the address
604 if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
605 $contact['nick'] = api_get_nick($contact["url"]);
609 'id' => $contact["id"],
610 'id_str' => (string) $contact["id"],
611 'name' => $contact["name"],
612 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
613 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url']),
614 'description' => $contact["about"],
615 'profile_image_url' => $contact["micro"],
616 'profile_image_url_https' => $contact["micro"],
617 'profile_image_url_profile_size' => $contact["thumb"],
618 'profile_image_url_large' => $contact["photo"],
619 'url' => $contact["url"],
620 'protected' => false,
621 'followers_count' => 0,
622 'friends_count' => 0,
624 'created_at' => api_date($contact["created"]),
625 'favourites_count' => 0,
627 'time_zone' => 'UTC',
628 'geo_enabled' => false,
630 'statuses_count' => 0,
632 'contributors_enabled' => false,
633 'is_translator' => false,
634 'is_translation_enabled' => false,
635 'following' => false,
636 'follow_request_sent' => false,
637 'statusnet_blocking' => false,
638 'notifications' => false,
639 'statusnet_profile_url' => $contact["url"],
641 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
642 'pid' => Contact::getIdForURL($contact["url"], 0, true),
644 'network' => $contact["network"],
649 throw new BadRequestException("User ".$url." not found.");
653 if ($uinfo[0]['self']) {
654 if ($uinfo[0]['network'] == "") {
655 $uinfo[0]['network'] = Protocol::DFRN;
658 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
659 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
666 // Add a nick if it isn't present there
667 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
668 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
671 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
673 if (!empty($profile['about'])) {
674 $description = $profile['about'];
676 $description = $uinfo[0]["about"];
679 if (!empty($usr['default-location'])) {
680 $location = $usr['default-location'];
681 } elseif (!empty($uinfo[0]["location"])) {
682 $location = $uinfo[0]["location"];
684 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
688 'id' => intval($pcontact_id),
689 'id_str' => (string) intval($pcontact_id),
690 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
691 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
692 'location' => $location,
693 'description' => $description,
694 'profile_image_url' => $uinfo[0]['micro'],
695 'profile_image_url_https' => $uinfo[0]['micro'],
696 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
697 'profile_image_url_large' => $uinfo[0]["photo"],
698 'url' => $uinfo[0]['url'],
699 'protected' => false,
700 'followers_count' => intval($countfollowers),
701 'friends_count' => intval($countfriends),
703 'created_at' => api_date($uinfo[0]['created']),
704 'favourites_count' => intval($starred),
706 'time_zone' => 'UTC',
707 'geo_enabled' => false,
709 'statuses_count' => intval($countitems),
711 'contributors_enabled' => false,
712 'is_translator' => false,
713 'is_translation_enabled' => false,
714 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
715 'follow_request_sent' => false,
716 'statusnet_blocking' => false,
717 'notifications' => false,
719 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
720 'statusnet_profile_url' => $uinfo[0]['url'],
721 'uid' => intval($uinfo[0]['uid']),
722 'cid' => intval($uinfo[0]['cid']),
723 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
724 'self' => $uinfo[0]['self'],
725 'network' => $uinfo[0]['network'],
728 // If this is a local user and it uses Frio, we can get its color preferences.
730 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
731 if ($theme_info['theme'] === 'frio') {
732 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
734 if ($schema && ($schema != '---')) {
735 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
736 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
737 require_once $schemefile;
740 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
741 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
742 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
744 if (empty($nav_bg)) {
747 if (empty($link_color)) {
748 $link_color = "#6fdbe8";
750 if (empty($bgcolor)) {
751 $bgcolor = "#ededed";
754 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
755 $ret['profile_link_color'] = str_replace('#', '', $link_color);
756 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
764 * @brief return api-formatted array for item's author and owner
767 * @param array $item item from db
768 * @return array(array:author, array:owner)
769 * @throws BadRequestException
770 * @throws ImagickException
771 * @throws InternalServerErrorException
772 * @throws UnauthorizedException
774 function api_item_get_user(App $a, $item)
776 $status_user = api_get_user($a, defaults($item, 'author-id', null));
778 $author_user = $status_user;
780 $status_user["protected"] = defaults($item, 'private', 0);
782 if (defaults($item, 'thr-parent', '') == defaults($item, 'uri', '')) {
783 $owner_user = api_get_user($a, defaults($item, 'owner-id', null));
785 $owner_user = $author_user;
788 return ([$status_user, $author_user, $owner_user]);
792 * @brief walks recursively through an array with the possibility to change value and key
794 * @param array $array The array to walk through
795 * @param callable $callback The callback function
797 * @return array the transformed array
799 function api_walk_recursive(array &$array, callable $callback)
803 foreach ($array as $k => $v) {
805 if ($callback($v, $k)) {
806 $new_array[$k] = api_walk_recursive($v, $callback);
809 if ($callback($v, $k)) {
820 * @brief Callback function to transform the array in an array that can be transformed in a XML file
822 * @param mixed $item Array item value
823 * @param string $key Array key
825 * @return boolean Should the array item be deleted?
827 function api_reformat_xml(&$item, &$key)
829 if (is_bool($item)) {
830 $item = ($item ? "true" : "false");
833 if (substr($key, 0, 10) == "statusnet_") {
834 $key = "statusnet:".substr($key, 10);
835 } elseif (substr($key, 0, 10) == "friendica_") {
836 $key = "friendica:".substr($key, 10);
838 /// @TODO old-lost code?
840 // $key = "default:".$key;
846 * @brief Creates the XML from a JSON style array
848 * @param array $data JSON style array
849 * @param string $root_element Name of the root element
851 * @return string The XML data
853 function api_create_xml(array $data, $root_element)
855 $childname = key($data);
856 $data2 = array_pop($data);
858 $namespaces = ["" => "http://api.twitter.com",
859 "statusnet" => "http://status.net/schema/api/1/",
860 "friendica" => "http://friendi.ca/schema/api/1/",
861 "georss" => "http://www.georss.org/georss"];
863 /// @todo Auto detection of needed namespaces
864 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
868 if (is_array($data2)) {
870 api_walk_recursive($data2, "api_reformat_xml");
876 foreach ($data2 as $item) {
877 $data4[$i++ . ":" . $childname] = $item;
884 $data3 = [$root_element => $data2];
886 $ret = XML::fromArray($data3, $xml, false, $namespaces);
891 * @brief Formats the data according to the data type
893 * @param string $root_element Name of the root element
894 * @param string $type Return type (atom, rss, xml, json)
895 * @param array $data JSON style array
897 * @return array|string (string|array) XML data or JSON data
899 function api_format_data($root_element, $type, $data)
905 $ret = api_create_xml($data, $root_element);
920 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
921 * returns a 401 status code and an error message if not.
923 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
925 * @param string $type Return type (atom, rss, xml, json)
926 * @return array|string
927 * @throws BadRequestException
928 * @throws ForbiddenException
929 * @throws ImagickException
930 * @throws InternalServerErrorException
931 * @throws UnauthorizedException
933 function api_account_verify_credentials($type)
937 if (api_user() === false) {
938 throw new ForbiddenException();
941 unset($_REQUEST["user_id"]);
942 unset($_GET["user_id"]);
944 unset($_REQUEST["screen_name"]);
945 unset($_GET["screen_name"]);
947 $skip_status = defaults($_REQUEST, 'skip_status', false);
949 $user_info = api_get_user($a);
951 // "verified" isn't used here in the standard
952 unset($user_info["verified"]);
954 // - Adding last status
956 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
958 $user_info['status'] = api_format_item($item, $type);
962 // "uid" and "self" are only needed for some internal stuff, so remove it from here
963 unset($user_info["uid"]);
964 unset($user_info["self"]);
966 return api_format_data("user", $type, ['user' => $user_info]);
969 /// @TODO move to top of file or somewhere better
970 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
973 * Get data from $_POST or $_GET
978 function requestdata($k)
980 if (!empty($_POST[$k])) {
983 if (!empty($_GET[$k])) {
990 * Deprecated function to upload media.
992 * @param string $type Return type (atom, rss, xml, json)
994 * @return array|string
995 * @throws BadRequestException
996 * @throws ForbiddenException
997 * @throws ImagickException
998 * @throws InternalServerErrorException
999 * @throws UnauthorizedException
1001 function api_statuses_mediap($type)
1005 if (api_user() === false) {
1006 Logger::log('api_statuses_update: no user');
1007 throw new ForbiddenException();
1009 $user_info = api_get_user($a);
1011 $_REQUEST['profile_uid'] = api_user();
1012 $_REQUEST['api_source'] = true;
1013 $txt = requestdata('status');
1014 /// @TODO old-lost code?
1015 //$txt = urldecode(requestdata('status'));
1017 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1018 $txt = HTML::toBBCodeVideo($txt);
1019 $config = HTMLPurifier_Config::createDefault();
1020 $config->set('Cache.DefinitionImpl', null);
1021 $purifier = new HTMLPurifier($config);
1022 $txt = $purifier->purify($txt);
1024 $txt = HTML::toBBCode($txt);
1026 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1028 $picture = wall_upload_post($a, false);
1030 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1031 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1032 $item_id = item_post($a);
1034 // output the post that we just posted.
1035 return api_status_show($type, $item_id);
1038 /// @TODO move this to top of file or somewhere better!
1039 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1042 * Updates the user’s current status.
1044 * @param string $type Return type (atom, rss, xml, json)
1046 * @return array|string
1047 * @throws BadRequestException
1048 * @throws ForbiddenException
1049 * @throws ImagickException
1050 * @throws InternalServerErrorException
1051 * @throws TooManyRequestsException
1052 * @throws UnauthorizedException
1053 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1055 function api_statuses_update($type)
1059 if (api_user() === false) {
1060 Logger::log('api_statuses_update: no user');
1061 throw new ForbiddenException();
1066 // convert $_POST array items to the form we use for web posts.
1067 if (requestdata('htmlstatus')) {
1068 $txt = requestdata('htmlstatus');
1069 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1070 $txt = HTML::toBBCodeVideo($txt);
1072 $config = HTMLPurifier_Config::createDefault();
1073 $config->set('Cache.DefinitionImpl', null);
1075 $purifier = new HTMLPurifier($config);
1076 $txt = $purifier->purify($txt);
1078 $_REQUEST['body'] = HTML::toBBCode($txt);
1081 $_REQUEST['body'] = requestdata('status');
1084 $_REQUEST['title'] = requestdata('title');
1086 $parent = requestdata('in_reply_to_status_id');
1088 // Twidere sends "-1" if it is no reply ...
1089 if ($parent == -1) {
1093 if (ctype_digit($parent)) {
1094 $_REQUEST['parent'] = $parent;
1096 $_REQUEST['parent_uri'] = $parent;
1099 if (requestdata('lat') && requestdata('long')) {
1100 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1102 $_REQUEST['profile_uid'] = api_user();
1105 // Check for throttling (maximum posts per day, week and month)
1106 $throttle_day = Config::get('system', 'throttle_limit_day');
1107 if ($throttle_day > 0) {
1108 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1110 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1111 $posts_day = DBA::count('thread', $condition);
1113 if ($posts_day > $throttle_day) {
1114 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1115 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1116 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));
1120 $throttle_week = Config::get('system', 'throttle_limit_week');
1121 if ($throttle_week > 0) {
1122 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1124 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1125 $posts_week = DBA::count('thread', $condition);
1127 if ($posts_week > $throttle_week) {
1128 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1129 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1130 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));
1134 $throttle_month = Config::get('system', 'throttle_limit_month');
1135 if ($throttle_month > 0) {
1136 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1138 $condition = ["`uid` = ? AND `wall` AND `created` > ?", api_user(), $datefrom];
1139 $posts_month = DBA::count('thread', $condition);
1141 if ($posts_month > $throttle_month) {
1142 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1143 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1144 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));
1149 if (!empty($_FILES['media'])) {
1150 // upload the image if we have one
1151 $picture = wall_upload_post($a, false);
1152 if (is_array($picture)) {
1153 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1157 // To-Do: Multiple IDs
1158 if (requestdata('media_ids')) {
1160 "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",
1161 intval(requestdata('media_ids')),
1164 if (DBA::isResult($r)) {
1165 $phototypes = Image::supportedTypes();
1166 $ext = $phototypes[$r[0]['type']];
1167 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1168 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1172 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1174 $_REQUEST['api_source'] = true;
1176 if (empty($_REQUEST['source'])) {
1177 $_REQUEST["source"] = api_source();
1180 // call out normal post function
1181 $item_id = item_post($a);
1183 // output the post that we just posted.
1184 return api_status_show($type, $item_id);
1187 /// @TODO move to top of file or somewhere better
1188 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1189 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1192 * Uploads an image to Friendica.
1195 * @throws BadRequestException
1196 * @throws ForbiddenException
1197 * @throws ImagickException
1198 * @throws InternalServerErrorException
1199 * @throws UnauthorizedException
1200 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1202 function api_media_upload()
1206 if (api_user() === false) {
1207 Logger::log('no user');
1208 throw new ForbiddenException();
1213 if (empty($_FILES['media'])) {
1215 throw new BadRequestException("No media.");
1218 $media = wall_upload_post($a, false);
1221 throw new InternalServerErrorException();
1225 $returndata["media_id"] = $media["id"];
1226 $returndata["media_id_string"] = (string)$media["id"];
1227 $returndata["size"] = $media["size"];
1228 $returndata["image"] = ["w" => $media["width"],
1229 "h" => $media["height"],
1230 "image_type" => $media["type"],
1231 "friendica_preview_url" => $media["preview"]];
1233 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1235 return ["media" => $returndata];
1238 /// @TODO move to top of file or somewhere better
1239 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1242 * @param string $type Return format (atom, rss, xml, json)
1243 * @param int $item_id
1247 function api_status_show($type, $item_id)
1249 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1253 $item = api_get_item(['id' => $item_id]);
1255 $status_info = api_format_item($item, $type);
1258 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1260 return api_format_data('statuses', $type, ['status' => $status_info]);
1264 * Retrieves the last public status of the provided user info
1266 * @param int $ownerId Public contact Id
1267 * @param int $uid User Id
1271 function api_get_last_status($ownerId, $uid)
1274 'owner-id' => $ownerId,
1276 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1280 $item = api_get_item($condition);
1286 * Retrieves a single item record based on the provided condition and converts it for API use.
1288 * @param array $condition Item table condition array
1292 function api_get_item(array $condition)
1294 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1300 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1301 * The author's most recent status will be returned inline.
1303 * @param string $type Return type (atom, rss, xml, json)
1304 * @return array|string
1305 * @throws BadRequestException
1306 * @throws ImagickException
1307 * @throws InternalServerErrorException
1308 * @throws UnauthorizedException
1309 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1311 function api_users_show($type)
1313 $a = \Friendica\BaseObject::getApp();
1315 $user_info = api_get_user($a);
1317 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1319 $user_info['status'] = api_format_item($item, $type);
1322 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1323 unset($user_info['uid']);
1324 unset($user_info['self']);
1326 return api_format_data('user', $type, ['user' => $user_info]);
1329 /// @TODO move to top of file or somewhere better
1330 api_register_func('api/users/show', 'api_users_show');
1331 api_register_func('api/externalprofile/show', 'api_users_show');
1334 * Search a public user account.
1336 * @param string $type Return type (atom, rss, xml, json)
1338 * @return array|string
1339 * @throws BadRequestException
1340 * @throws ImagickException
1341 * @throws InternalServerErrorException
1342 * @throws UnauthorizedException
1343 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1345 function api_users_search($type)
1351 if (!empty($_GET['q'])) {
1352 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1354 if (!DBA::isResult($r)) {
1355 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1358 if (DBA::isResult($r)) {
1360 foreach ($r as $user) {
1361 $user_info = api_get_user($a, $user["id"]);
1363 if ($type == "xml") {
1364 $userlist[$k++.":user"] = $user_info;
1366 $userlist[] = $user_info;
1369 $userlist = ["users" => $userlist];
1371 throw new BadRequestException("User ".$_GET["q"]." not found.");
1374 throw new BadRequestException("No user specified.");
1377 return api_format_data("users", $type, $userlist);
1380 /// @TODO move to top of file or somewhere better
1381 api_register_func('api/users/search', 'api_users_search');
1384 * Return user objects
1386 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1388 * @param string $type Return format: json or xml
1390 * @return array|string
1391 * @throws BadRequestException
1392 * @throws ImagickException
1393 * @throws InternalServerErrorException
1394 * @throws NotFoundException if the results are empty.
1395 * @throws UnauthorizedException
1397 function api_users_lookup($type)
1401 if (!empty($_REQUEST['user_id'])) {
1402 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1404 $users[] = api_get_user(get_app(), $id);
1409 if (empty($users)) {
1410 throw new NotFoundException;
1413 return api_format_data("users", $type, ['users' => $users]);
1416 /// @TODO move to top of file or somewhere better
1417 api_register_func('api/users/lookup', 'api_users_lookup', true);
1420 * Returns statuses that match a specified query.
1422 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1424 * @param string $type Return format: json, xml, atom, rss
1426 * @return array|string
1427 * @throws BadRequestException if the "q" parameter is missing.
1428 * @throws ForbiddenException
1429 * @throws ImagickException
1430 * @throws InternalServerErrorException
1431 * @throws UnauthorizedException
1433 function api_search($type)
1436 $user_info = api_get_user($a);
1438 if (api_user() === false || $user_info === false) { throw new ForbiddenException(); }
1440 if (empty($_REQUEST['q'])) {
1441 throw new BadRequestException('q parameter is required.');
1444 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1447 $data['status'] = [];
1449 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1450 if (!empty($_REQUEST['rpp'])) {
1451 $count = $_REQUEST['rpp'];
1452 } elseif (!empty($_REQUEST['count'])) {
1453 $count = $_REQUEST['count'];
1456 $since_id = defaults($_REQUEST, 'since_id', 0);
1457 $max_id = defaults($_REQUEST, 'max_id', 0);
1458 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1459 $start = $page * $count;
1460 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1461 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1462 $searchTerm = $matches[1];
1463 $condition = ["`oid` > ?
1464 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1465 AND `otype` = ? AND `type` = ? AND `term` = ?",
1466 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1468 $condition[0] .= ' AND `oid` <= ?';
1469 $condition[] = $max_id;
1471 $terms = DBA::select('term', ['oid'], $condition, []);
1473 while ($term = DBA::fetch($terms)) {
1474 $itemIds[] = $term['oid'];
1478 if (empty($itemIds)) {
1479 return api_format_data('statuses', $type, $data);
1482 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1483 if ($exclude_replies) {
1484 $preCondition[] = '`id` = `parent`';
1487 $condition = [implode(' AND ', $preCondition)];
1489 $condition = ["`id` > ?
1490 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1491 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1492 AND `body` LIKE CONCAT('%',?,'%')",
1493 $since_id, api_user(), $_REQUEST['q']];
1495 $condition[0] .= ' AND `id` <= ?';
1496 $condition[] = $max_id;
1500 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1502 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1504 bindComments($data['status']);
1506 return api_format_data('statuses', $type, $data);
1509 /// @TODO move to top of file or somewhere better
1510 api_register_func('api/search/tweets', 'api_search', true);
1511 api_register_func('api/search', 'api_search', true);
1514 * Returns the most recent statuses posted by the user and the users they follow.
1516 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1518 * @param string $type Return type (atom, rss, xml, json)
1520 * @return array|string
1521 * @throws BadRequestException
1522 * @throws ForbiddenException
1523 * @throws ImagickException
1524 * @throws InternalServerErrorException
1525 * @throws UnauthorizedException
1526 * @todo Optional parameters
1527 * @todo Add reply info
1529 function api_statuses_home_timeline($type)
1532 $user_info = api_get_user($a);
1534 if (api_user() === false || $user_info === false) {
1535 throw new ForbiddenException();
1538 unset($_REQUEST["user_id"]);
1539 unset($_GET["user_id"]);
1541 unset($_REQUEST["screen_name"]);
1542 unset($_GET["screen_name"]);
1544 // get last network messages
1547 $count = defaults($_REQUEST, 'count', 20);
1548 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
1552 $since_id = defaults($_REQUEST, 'since_id', 0);
1553 $max_id = defaults($_REQUEST, 'max_id', 0);
1554 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1555 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1557 $start = $page * $count;
1559 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1560 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1563 $condition[0] .= " AND `item`.`id` <= ?";
1564 $condition[] = $max_id;
1566 if ($exclude_replies) {
1567 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1569 if ($conversation_id > 0) {
1570 $condition[0] .= " AND `item`.`parent` = ?";
1571 $condition[] = $conversation_id;
1574 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1575 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1577 $items = Item::inArray($statuses);
1579 $ret = api_format_items($items, $user_info, false, $type);
1581 // Set all posts from the query above to seen
1583 foreach ($items as $item) {
1584 $idarray[] = intval($item["id"]);
1587 if (!empty($idarray)) {
1588 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1590 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1596 $data = ['status' => $ret];
1601 $data = api_rss_extra($a, $data, $user_info);
1605 return api_format_data("statuses", $type, $data);
1609 /// @TODO move to top of file or somewhere better
1610 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1611 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1614 * Returns the most recent statuses from public users.
1616 * @param string $type Return type (atom, rss, xml, json)
1618 * @return array|string
1619 * @throws BadRequestException
1620 * @throws ForbiddenException
1621 * @throws ImagickException
1622 * @throws InternalServerErrorException
1623 * @throws UnauthorizedException
1625 function api_statuses_public_timeline($type)
1628 $user_info = api_get_user($a);
1630 if (api_user() === false || $user_info === false) {
1631 throw new ForbiddenException();
1634 // get last network messages
1637 $count = defaults($_REQUEST, 'count', 20);
1638 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
1642 $since_id = defaults($_REQUEST, 'since_id', 0);
1643 $max_id = defaults($_REQUEST, 'max_id', 0);
1644 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1645 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
1647 $start = $page * $count;
1649 if ($exclude_replies && !$conversation_id) {
1650 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1651 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1654 $condition[0] .= " AND `thread`.`iid` <= ?";
1655 $condition[] = $max_id;
1658 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1659 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1661 $r = Item::inArray($statuses);
1663 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1664 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1667 $condition[0] .= " AND `item`.`id` <= ?";
1668 $condition[] = $max_id;
1670 if ($conversation_id > 0) {
1671 $condition[0] .= " AND `item`.`parent` = ?";
1672 $condition[] = $conversation_id;
1675 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1676 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1678 $r = Item::inArray($statuses);
1681 $ret = api_format_items($r, $user_info, false, $type);
1685 $data = ['status' => $ret];
1690 $data = api_rss_extra($a, $data, $user_info);
1694 return api_format_data("statuses", $type, $data);
1697 /// @TODO move to top of file or somewhere better
1698 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1701 * Returns the most recent statuses posted by users this node knows about.
1703 * @brief Returns the list of public federated posts this node knows about
1705 * @param string $type Return format: json, xml, atom, rss
1706 * @return array|string
1707 * @throws BadRequestException
1708 * @throws ForbiddenException
1709 * @throws ImagickException
1710 * @throws InternalServerErrorException
1711 * @throws UnauthorizedException
1713 function api_statuses_networkpublic_timeline($type)
1716 $user_info = api_get_user($a);
1718 if (api_user() === false || $user_info === false) {
1719 throw new ForbiddenException();
1722 $since_id = defaults($_REQUEST, 'since_id', 0);
1723 $max_id = defaults($_REQUEST, 'max_id', 0);
1726 $count = defaults($_REQUEST, 'count', 20);
1727 $page = defaults($_REQUEST, 'page', 1);
1731 $start = ($page - 1) * $count;
1733 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1734 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1737 $condition[0] .= " AND `thread`.`iid` <= ?";
1738 $condition[] = $max_id;
1741 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1742 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1744 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1748 $data = ['status' => $ret];
1753 $data = api_rss_extra($a, $data, $user_info);
1757 return api_format_data("statuses", $type, $data);
1760 /// @TODO move to top of file or somewhere better
1761 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1764 * Returns a single status.
1766 * @param string $type Return type (atom, rss, xml, json)
1768 * @return array|string
1769 * @throws BadRequestException
1770 * @throws ForbiddenException
1771 * @throws ImagickException
1772 * @throws InternalServerErrorException
1773 * @throws UnauthorizedException
1774 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1776 function api_statuses_show($type)
1779 $user_info = api_get_user($a);
1781 if (api_user() === false || $user_info === false) {
1782 throw new ForbiddenException();
1786 $id = intval(defaults($a->argv, 3, 0));
1789 $id = intval(defaults($_REQUEST, 'id', 0));
1794 $id = intval(defaults($a->argv, 4, 0));
1797 Logger::log('API: api_statuses_show: ' . $id);
1799 $conversation = !empty($_REQUEST['conversation']);
1801 // try to fetch the item for the local user - or the public item, if there is no local one
1802 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1803 if (!DBA::isResult($uri_item)) {
1804 throw new BadRequestException("There is no status with this id.");
1807 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1808 if (!DBA::isResult($item)) {
1809 throw new BadRequestException("There is no status with this id.");
1814 if ($conversation) {
1815 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1816 $params = ['order' => ['id' => true]];
1818 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1822 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1824 /// @TODO How about copying this to above methods which don't check $r ?
1825 if (!DBA::isResult($statuses)) {
1826 throw new BadRequestException("There is no status with this id.");
1829 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1831 if ($conversation) {
1832 $data = ['status' => $ret];
1833 return api_format_data("statuses", $type, $data);
1835 $data = ['status' => $ret[0]];
1836 return api_format_data("status", $type, $data);
1840 /// @TODO move to top of file or somewhere better
1841 api_register_func('api/statuses/show', 'api_statuses_show', true);
1845 * @param string $type Return type (atom, rss, xml, json)
1847 * @return array|string
1848 * @throws BadRequestException
1849 * @throws ForbiddenException
1850 * @throws ImagickException
1851 * @throws InternalServerErrorException
1852 * @throws UnauthorizedException
1853 * @todo nothing to say?
1855 function api_conversation_show($type)
1858 $user_info = api_get_user($a);
1860 if (api_user() === false || $user_info === false) {
1861 throw new ForbiddenException();
1865 $id = intval(defaults($a->argv , 3 , 0));
1866 $since_id = intval(defaults($_REQUEST, 'since_id', 0));
1867 $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
1868 $count = intval(defaults($_REQUEST, 'count' , 20));
1869 $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
1874 $start = $page * $count;
1877 $id = intval(defaults($_REQUEST, 'id', 0));
1882 $id = intval(defaults($a->argv, 4, 0));
1885 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1887 // try to fetch the item for the local user - or the public item, if there is no local one
1888 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1889 if (!DBA::isResult($item)) {
1890 throw new BadRequestException("There is no status with this id.");
1893 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1894 if (!DBA::isResult($parent)) {
1895 throw new BadRequestException("There is no status with this id.");
1898 $id = $parent['id'];
1900 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1901 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1904 $condition[0] .= " AND `item`.`id` <= ?";
1905 $condition[] = $max_id;
1908 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1909 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1911 if (!DBA::isResult($statuses)) {
1912 throw new BadRequestException("There is no status with id $id.");
1915 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1917 $data = ['status' => $ret];
1918 return api_format_data("statuses", $type, $data);
1921 /// @TODO move to top of file or somewhere better
1922 api_register_func('api/conversation/show', 'api_conversation_show', true);
1923 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1928 * @param string $type Return type (atom, rss, xml, json)
1930 * @return array|string
1931 * @throws BadRequestException
1932 * @throws ForbiddenException
1933 * @throws ImagickException
1934 * @throws InternalServerErrorException
1935 * @throws UnauthorizedException
1936 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1938 function api_statuses_repeat($type)
1944 if (api_user() === false) {
1945 throw new ForbiddenException();
1951 $id = intval(defaults($a->argv, 3, 0));
1954 $id = intval(defaults($_REQUEST, 'id', 0));
1959 $id = intval(defaults($a->argv, 4, 0));
1962 Logger::log('API: api_statuses_repeat: '.$id);
1964 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1965 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
1967 if (DBA::isResult($item) && $item['body'] != "") {
1968 if (strpos($item['body'], "[/share]") !== false) {
1969 $pos = strpos($item['body'], "[share");
1970 $post = substr($item['body'], $pos);
1972 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
1974 $post .= $item['body'];
1975 $post .= "[/share]";
1977 $_REQUEST['body'] = $post;
1978 $_REQUEST['profile_uid'] = api_user();
1979 $_REQUEST['api_source'] = true;
1981 if (empty($_REQUEST['source'])) {
1982 $_REQUEST["source"] = api_source();
1985 $item_id = item_post($a);
1987 throw new ForbiddenException();
1990 // output the post that we just posted.
1992 return api_status_show($type, $item_id);
1995 /// @TODO move to top of file or somewhere better
1996 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1999 * Destroys a specific status.
2001 * @param string $type Return type (atom, rss, xml, json)
2003 * @return array|string
2004 * @throws BadRequestException
2005 * @throws ForbiddenException
2006 * @throws ImagickException
2007 * @throws InternalServerErrorException
2008 * @throws UnauthorizedException
2009 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2011 function api_statuses_destroy($type)
2015 if (api_user() === false) {
2016 throw new ForbiddenException();
2022 $id = intval(defaults($a->argv, 3, 0));
2025 $id = intval(defaults($_REQUEST, 'id', 0));
2030 $id = intval(defaults($a->argv, 4, 0));
2033 Logger::log('API: api_statuses_destroy: '.$id);
2035 $ret = api_statuses_show($type);
2037 Item::deleteForUser(['id' => $id], api_user());
2042 /// @TODO move to top of file or somewhere better
2043 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2046 * Returns the most recent mentions.
2048 * @param string $type Return type (atom, rss, xml, json)
2050 * @return array|string
2051 * @throws BadRequestException
2052 * @throws ForbiddenException
2053 * @throws ImagickException
2054 * @throws InternalServerErrorException
2055 * @throws UnauthorizedException
2056 * @see http://developer.twitter.com/doc/get/statuses/mentions
2058 function api_statuses_mentions($type)
2061 $user_info = api_get_user($a);
2063 if (api_user() === false || $user_info === false) {
2064 throw new ForbiddenException();
2067 unset($_REQUEST["user_id"]);
2068 unset($_GET["user_id"]);
2070 unset($_REQUEST["screen_name"]);
2071 unset($_GET["screen_name"]);
2073 // get last network messages
2076 $since_id = defaults($_REQUEST, 'since_id', 0);
2077 $max_id = defaults($_REQUEST, 'max_id' , 0);
2078 $count = defaults($_REQUEST, 'count' , 20);
2079 $page = defaults($_REQUEST, 'page' , 1);
2084 $start = ($page - 1) * $count;
2086 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2087 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2088 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2091 $condition[0] .= " AND `item`.`id` <= ?";
2092 $condition[] = $max_id;
2095 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2096 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2098 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2100 $data = ['status' => $ret];
2105 $data = api_rss_extra($a, $data, $user_info);
2109 return api_format_data("statuses", $type, $data);
2112 /// @TODO move to top of file or somewhere better
2113 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2114 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2117 * Returns the most recent statuses posted by the user.
2119 * @brief Returns a user's public timeline
2121 * @param string $type Either "json" or "xml"
2122 * @return string|array
2123 * @throws BadRequestException
2124 * @throws ForbiddenException
2125 * @throws ImagickException
2126 * @throws InternalServerErrorException
2127 * @throws UnauthorizedException
2128 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2130 function api_statuses_user_timeline($type)
2133 $user_info = api_get_user($a);
2135 if (api_user() === false || $user_info === false) {
2136 throw new ForbiddenException();
2140 "api_statuses_user_timeline: api_user: ". api_user() .
2141 "\nuser_info: ".print_r($user_info, true) .
2142 "\n_REQUEST: ".print_r($_REQUEST, true),
2146 $since_id = defaults($_REQUEST, 'since_id', 0);
2147 $max_id = defaults($_REQUEST, 'max_id', 0);
2148 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2149 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
2152 $count = defaults($_REQUEST, 'count', 20);
2153 $page = defaults($_REQUEST, 'page', 1);
2157 $start = ($page - 1) * $count;
2159 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2160 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2162 if ($user_info['self'] == 1) {
2163 $condition[0] .= ' AND `item`.`wall` ';
2166 if ($exclude_replies) {
2167 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2170 if ($conversation_id > 0) {
2171 $condition[0] .= " AND `item`.`parent` = ?";
2172 $condition[] = $conversation_id;
2176 $condition[0] .= " AND `item`.`id` <= ?";
2177 $condition[] = $max_id;
2180 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2181 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2183 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2187 $data = ['status' => $ret];
2192 $data = api_rss_extra($a, $data, $user_info);
2196 return api_format_data("statuses", $type, $data);
2199 /// @TODO move to top of file or somewhere better
2200 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2203 * Star/unstar an item.
2204 * param: id : id of the item
2206 * @param string $type Return type (atom, rss, xml, json)
2208 * @return array|string
2209 * @throws BadRequestException
2210 * @throws ForbiddenException
2211 * @throws ImagickException
2212 * @throws InternalServerErrorException
2213 * @throws UnauthorizedException
2214 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2216 function api_favorites_create_destroy($type)
2220 if (api_user() === false) {
2221 throw new ForbiddenException();
2224 // for versioned api.
2225 /// @TODO We need a better global soluton
2226 $action_argv_id = 2;
2227 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2228 $action_argv_id = 3;
2231 if ($a->argc <= $action_argv_id) {
2232 throw new BadRequestException("Invalid request.");
2234 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2235 if ($a->argc == $action_argv_id + 2) {
2236 $itemid = intval(defaults($a->argv, $action_argv_id + 1, 0));
2238 $itemid = intval(defaults($_REQUEST, 'id', 0));
2241 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2243 if (!DBA::isResult($item)) {
2244 throw new BadRequestException("Invalid item.");
2249 $item['starred'] = 1;
2252 $item['starred'] = 0;
2255 throw new BadRequestException("Invalid action ".$action);
2258 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2261 throw new InternalServerErrorException("DB error");
2265 $user_info = api_get_user($a);
2266 $rets = api_format_items([$item], $user_info, false, $type);
2269 $data = ['status' => $ret];
2274 $data = api_rss_extra($a, $data, $user_info);
2278 return api_format_data("status", $type, $data);
2281 /// @TODO move to top of file or somewhere better
2282 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2283 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2286 * Returns the most recent favorite statuses.
2288 * @param string $type Return type (atom, rss, xml, json)
2290 * @return string|array
2291 * @throws BadRequestException
2292 * @throws ForbiddenException
2293 * @throws ImagickException
2294 * @throws InternalServerErrorException
2295 * @throws UnauthorizedException
2297 function api_favorites($type)
2302 $user_info = api_get_user($a);
2304 if (api_user() === false || $user_info === false) {
2305 throw new ForbiddenException();
2310 // in friendica starred item are private
2311 // return favorites only for self
2312 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2314 if ($user_info['self'] == 0) {
2318 $since_id = defaults($_REQUEST, 'since_id', 0);
2319 $max_id = defaults($_REQUEST, 'max_id', 0);
2320 $count = defaults($_GET, 'count', 20);
2321 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] -1 : 0);
2326 $start = $page*$count;
2328 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2329 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2331 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2334 $condition[0] .= " AND `item`.`id` <= ?";
2335 $condition[] = $max_id;
2338 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2340 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2345 $data = ['status' => $ret];
2350 $data = api_rss_extra($a, $data, $user_info);
2354 return api_format_data("statuses", $type, $data);
2357 /// @TODO move to top of file or somewhere better
2358 api_register_func('api/favorites', 'api_favorites', true);
2362 * @param array $item
2363 * @param array $recipient
2364 * @param array $sender
2367 * @throws InternalServerErrorException
2369 function api_format_messages($item, $recipient, $sender)
2371 // standard meta information
2373 'id' => $item['id'],
2374 'sender_id' => $sender['id'],
2376 'recipient_id' => $recipient['id'],
2377 'created_at' => api_date(defaults($item, 'created', DateTimeFormat::utcNow())),
2378 'sender_screen_name' => $sender['screen_name'],
2379 'recipient_screen_name' => $recipient['screen_name'],
2380 'sender' => $sender,
2381 'recipient' => $recipient,
2383 'friendica_seen' => defaults($item, 'seen', 0),
2384 'friendica_parent_uri' => defaults($item, 'parent-uri', ''),
2387 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2388 if (isset($ret['sender']['uid'])) {
2389 unset($ret['sender']['uid']);
2391 if (isset($ret['sender']['self'])) {
2392 unset($ret['sender']['self']);
2394 if (isset($ret['recipient']['uid'])) {
2395 unset($ret['recipient']['uid']);
2397 if (isset($ret['recipient']['self'])) {
2398 unset($ret['recipient']['self']);
2401 //don't send title to regular StatusNET requests to avoid confusing these apps
2402 if (!empty($_GET['getText'])) {
2403 $ret['title'] = $item['title'];
2404 if ($_GET['getText'] == 'html') {
2405 $ret['text'] = BBCode::convert($item['body'], false);
2406 } elseif ($_GET['getText'] == 'plain') {
2407 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2410 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2412 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2413 unset($ret['sender']);
2414 unset($ret['recipient']);
2422 * @param array $item
2425 * @throws InternalServerErrorException
2427 function api_convert_item($item)
2429 $body = $item['body'];
2430 $attachments = api_get_attachments($body);
2432 // Workaround for ostatus messages where the title is identically to the body
2433 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2434 $statusbody = trim(HTML::toPlaintext($html, 0));
2436 // handle data: images
2437 $statusbody = api_format_items_embeded_images($item, $statusbody);
2439 $statustitle = trim($item['title']);
2441 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2442 $statustext = trim($statusbody);
2444 $statustext = trim($statustitle."\n\n".$statusbody);
2447 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($statustext)> 1000)) {
2448 $statustext = substr($statustext, 0, 1000) . "... \n" . defaults($item, 'plink', '');
2451 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2453 // Workaround for clients with limited HTML parser functionality
2454 $search = ["<br>", "<blockquote>", "</blockquote>",
2455 "<h1>", "</h1>", "<h2>", "</h2>",
2456 "<h3>", "</h3>", "<h4>", "</h4>",
2457 "<h5>", "</h5>", "<h6>", "</h6>"];
2458 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2459 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2460 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2461 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2462 $statushtml = str_replace($search, $replace, $statushtml);
2464 if ($item['title'] != "") {
2465 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2469 $oldtext = $statushtml;
2470 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2471 } while ($oldtext != $statushtml);
2473 if (substr($statushtml, 0, 4) == '<br>') {
2474 $statushtml = substr($statushtml, 4);
2477 if (substr($statushtml, 0, -4) == '<br>') {
2478 $statushtml = substr($statushtml, -4);
2481 // feeds without body should contain the link
2482 if ((defaults($item, 'network', Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2483 $statushtml .= BBCode::convert($item['plink']);
2486 $entities = api_get_entitities($statustext, $body);
2489 "text" => $statustext,
2490 "html" => $statushtml,
2491 "attachments" => $attachments,
2492 "entities" => $entities
2498 * @param string $body
2501 * @throws InternalServerErrorException
2503 function api_get_attachments(&$body)
2506 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2508 $URLSearchString = "^\[\]";
2509 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2517 foreach ($images[1] as $image) {
2518 $imagedata = Image::getInfoFromURL($image);
2521 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2525 if (strstr(defaults($_SERVER, 'HTTP_USER_AGENT', ''), "AndStatus")) {
2526 foreach ($images[0] as $orig) {
2527 $body = str_replace($orig, "", $body);
2531 return $attachments;
2536 * @param string $text
2537 * @param string $bbcode
2540 * @throws InternalServerErrorException
2541 * @todo Links at the first character of the post
2543 function api_get_entitities(&$text, $bbcode)
2545 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
2547 if ($include_entities != "true") {
2548 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2550 foreach ($images[1] as $image) {
2551 $replace = ProxyUtils::proxifyUrl($image);
2552 $text = str_replace($image, $replace, $text);
2557 $bbcode = BBCode::cleanPictureLinks($bbcode);
2559 // Change pure links in text to bbcode uris
2560 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2563 $entities["hashtags"] = [];
2564 $entities["symbols"] = [];
2565 $entities["urls"] = [];
2566 $entities["user_mentions"] = [];
2568 $URLSearchString = "^\[\]";
2570 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2572 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2573 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2574 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2576 $bbcode = preg_replace(
2577 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2578 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2581 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2583 $bbcode = preg_replace(
2584 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2585 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2588 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2590 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2592 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2593 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2596 foreach ($urls[1] as $id => $url) {
2597 //$start = strpos($text, $url, $offset);
2598 $start = iconv_strpos($text, $url, 0, "UTF-8");
2599 if (!($start === false)) {
2600 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2604 ksort($ordered_urls);
2607 //foreach ($urls[1] AS $id=>$url) {
2608 foreach ($ordered_urls as $url) {
2609 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2610 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2612 $display_url = $url["title"];
2614 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2615 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2617 if (strlen($display_url) > 26) {
2618 $display_url = substr($display_url, 0, 25)."…";
2622 //$start = strpos($text, $url, $offset);
2623 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2624 if (!($start === false)) {
2625 $entities["urls"][] = ["url" => $url["url"],
2626 "expanded_url" => $url["url"],
2627 "display_url" => $display_url,
2628 "indices" => [$start, $start+strlen($url["url"])]];
2629 $offset = $start + 1;
2633 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2634 $ordered_images = [];
2635 foreach ($images[1] as $image) {
2636 //$start = strpos($text, $url, $offset);
2637 $start = iconv_strpos($text, $image, 0, "UTF-8");
2638 if (!($start === false)) {
2639 $ordered_images[$start] = $image;
2642 //$entities["media"] = array();
2645 foreach ($ordered_images as $url) {
2646 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2647 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2649 if (strlen($display_url) > 26) {
2650 $display_url = substr($display_url, 0, 25)."…";
2653 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2654 if (!($start === false)) {
2655 $image = Image::getInfoFromURL($url);
2657 // If image cache is activated, then use the following sizes:
2658 // thumb (150), small (340), medium (600) and large (1024)
2659 if (!Config::get("system", "proxy_disabled")) {
2660 $media_url = ProxyUtils::proxifyUrl($url);
2663 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2664 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2666 if (($image[0] > 150) || ($image[1] > 150)) {
2667 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2668 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2671 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2672 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2674 if (($image[0] > 600) || ($image[1] > 600)) {
2675 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2676 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2680 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2683 $entities["media"][] = [
2685 "id_str" => (string) ($start + 1),
2686 "indices" => [$start, $start+strlen($url)],
2687 "media_url" => Strings::normaliseLink($media_url),
2688 "media_url_https" => $media_url,
2690 "display_url" => $display_url,
2691 "expanded_url" => $url,
2695 $offset = $start + 1;
2704 * @param array $item
2705 * @param string $text
2709 function api_format_items_embeded_images($item, $text)
2711 $text = preg_replace_callback(
2712 '|data:image/([^;]+)[^=]+=*|m',
2713 function () use ($item) {
2714 return System::baseUrl() . '/display/' . $item['guid'];
2722 * @brief return <a href='url'>name</a> as array
2724 * @param string $txt text
2729 function api_contactlink_to_array($txt)
2732 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2733 if ($r && count($match)==3) {
2735 'name' => $match[2],
2749 * @brief return likes, dislikes and attend status for item
2751 * @param array $item array
2752 * @param string $type Return type (atom, rss, xml, json)
2755 * likes => int count,
2756 * dislikes => int count
2757 * @throws BadRequestException
2758 * @throws ImagickException
2759 * @throws InternalServerErrorException
2760 * @throws UnauthorizedException
2762 function api_format_items_activities($item, $type = "json")
2771 'attendmaybe' => [],
2774 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2775 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2777 while ($parent_item = Item::fetch($ret)) {
2778 // not used as result should be structured like other user data
2779 //builtin_activity_puller($i, $activities);
2781 // get user data and add it to the array of the activity
2782 $user = api_get_user($a, $parent_item['author-id']);
2783 switch ($parent_item['verb']) {
2785 $activities['like'][] = $user;
2787 case ACTIVITY_DISLIKE:
2788 $activities['dislike'][] = $user;
2790 case ACTIVITY_ATTEND:
2791 $activities['attendyes'][] = $user;
2793 case ACTIVITY_ATTENDNO:
2794 $activities['attendno'][] = $user;
2796 case ACTIVITY_ATTENDMAYBE:
2797 $activities['attendmaybe'][] = $user;
2806 if ($type == "xml") {
2807 $xml_activities = [];
2808 foreach ($activities as $k => $v) {
2809 // change xml element from "like" to "friendica:like"
2810 $xml_activities["friendica:".$k] = $v;
2811 // add user data into xml output
2813 foreach ($v as $user) {
2814 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2817 $activities = $xml_activities;
2825 * @brief return data from profiles
2827 * @param array $profile_row array containing data from db table 'profile'
2829 * @throws InternalServerErrorException
2831 function api_format_items_profiles($profile_row)
2834 'profile_id' => $profile_row['id'],
2835 'profile_name' => $profile_row['profile-name'],
2836 'is_default' => $profile_row['is-default'] ? true : false,
2837 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2838 'profile_photo' => $profile_row['photo'],
2839 'profile_thumb' => $profile_row['thumb'],
2840 'publish' => $profile_row['publish'] ? true : false,
2841 'net_publish' => $profile_row['net-publish'] ? true : false,
2842 'description' => $profile_row['pdesc'],
2843 'date_of_birth' => $profile_row['dob'],
2844 'address' => $profile_row['address'],
2845 'city' => $profile_row['locality'],
2846 'region' => $profile_row['region'],
2847 'postal_code' => $profile_row['postal-code'],
2848 'country' => $profile_row['country-name'],
2849 'hometown' => $profile_row['hometown'],
2850 'gender' => $profile_row['gender'],
2851 'marital' => $profile_row['marital'],
2852 'marital_with' => $profile_row['with'],
2853 'marital_since' => $profile_row['howlong'],
2854 'sexual' => $profile_row['sexual'],
2855 'politic' => $profile_row['politic'],
2856 'religion' => $profile_row['religion'],
2857 'public_keywords' => $profile_row['pub_keywords'],
2858 'private_keywords' => $profile_row['prv_keywords'],
2859 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2860 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2861 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2862 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2863 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2864 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2865 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2866 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2867 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2868 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2869 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2870 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2871 'homepage' => $profile_row['homepage'],
2878 * @brief format items to be returned by api
2880 * @param array $items array of items
2881 * @param array $user_info
2882 * @param bool $filter_user filter items by $user_info
2883 * @param string $type Return type (atom, rss, xml, json)
2885 * @throws BadRequestException
2886 * @throws ImagickException
2887 * @throws InternalServerErrorException
2888 * @throws UnauthorizedException
2890 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2892 $a = \Friendica\BaseObject::getApp();
2896 foreach ((array)$items as $item) {
2897 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2899 // Look if the posts are matching if they should be filtered by user id
2900 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2904 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2913 * @param array $item Item record
2914 * @param string $type Return format (atom, rss, xml, json)
2915 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2916 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2917 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2918 * @return array API-formatted status
2919 * @throws BadRequestException
2920 * @throws ImagickException
2921 * @throws InternalServerErrorException
2922 * @throws UnauthorizedException
2924 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2926 $a = \Friendica\BaseObject::getApp();
2928 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2929 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2932 localize_item($item);
2934 $in_reply_to = api_in_reply_to($item);
2936 $converted = api_convert_item($item);
2938 if ($type == "xml") {
2939 $geo = "georss:point";
2945 'text' => $converted["text"],
2946 'truncated' => false,
2947 'created_at'=> api_date($item['created']),
2948 'in_reply_to_status_id' => $in_reply_to['status_id'],
2949 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2950 'source' => (($item['app']) ? $item['app'] : 'web'),
2951 'id' => intval($item['id']),
2952 'id_str' => (string) intval($item['id']),
2953 'in_reply_to_user_id' => $in_reply_to['user_id'],
2954 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2955 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2957 'favorited' => $item['starred'] ? true : false,
2958 'user' => $status_user,
2959 'friendica_author' => $author_user,
2960 'friendica_owner' => $owner_user,
2961 'friendica_private' => $item['private'] == 1,
2962 //'entities' => NULL,
2963 'statusnet_html' => $converted["html"],
2964 'statusnet_conversation_id' => $item['parent'],
2965 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2966 'friendica_activities' => api_format_items_activities($item, $type),
2969 if (count($converted["attachments"]) > 0) {
2970 $status["attachments"] = $converted["attachments"];
2973 if (count($converted["entities"]) > 0) {
2974 $status["entities"] = $converted["entities"];
2977 if ($status["source"] == 'web') {
2978 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
2979 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
2980 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
2983 $retweeted_item = [];
2985 $announce = api_get_announce($item);
2986 if (!empty($announce) && ($item['owner-id'] == $item['author-id'])) {
2987 $retweeted_item = $item;
2989 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
2990 } elseif ($item["id"] == $item["parent"]) {
2991 $retweeted_item = api_share_as_retweet($item);
2994 if (!empty($retweeted_item)) {
2995 $retweeted_status = $status;
2996 $status['user'] = $status['friendica_owner'];
2998 $retweeted_status['friendica_author'] = $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
2999 } catch (BadRequestException $e) {
3000 // user not found. should be found?
3001 /// @todo check if the user should be always found
3002 $retweeted_status["user"] = [];
3005 $rt_converted = api_convert_item($retweeted_item);
3007 $retweeted_status['text'] = $rt_converted["text"];
3008 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3009 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3010 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3011 $retweeted_status['friendica_owner'] = $retweeted_status['friendica_author'];
3012 $status['retweeted_status'] = $retweeted_status;
3013 $status['friendica_author'] = $retweeted_status['friendica_author'];
3016 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3017 unset($status["user"]["uid"]);
3018 unset($status["user"]["self"]);
3020 if ($item["coord"] != "") {
3021 $coords = explode(' ', $item["coord"]);
3022 if (count($coords) == 2) {
3023 if ($type == "json") {
3024 $status["geo"] = ['type' => 'Point',
3025 'coordinates' => [(float) $coords[0],
3026 (float) $coords[1]]];
3027 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3028 $status["georss:point"] = $item["coord"];
3037 * Returns the remaining number of API requests available to the user before the API limit is reached.
3039 * @param string $type Return type (atom, rss, xml, json)
3041 * @return array|string
3044 function api_account_rate_limit_status($type)
3046 if ($type == "xml") {
3048 'remaining-hits' => '150',
3049 '@attributes' => ["type" => "integer"],
3050 'hourly-limit' => '150',
3051 '@attributes2' => ["type" => "integer"],
3052 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3053 '@attributes3' => ["type" => "datetime"],
3054 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3055 '@attributes4' => ["type" => "integer"],
3059 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3060 'remaining_hits' => '150',
3061 'hourly_limit' => '150',
3062 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3066 return api_format_data('hash', $type, ['hash' => $hash]);
3069 /// @TODO move to top of file or somewhere better
3070 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3073 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3075 * @param string $type Return type (atom, rss, xml, json)
3077 * @return array|string
3079 function api_help_test($type)
3081 if ($type == 'xml') {
3087 return api_format_data('ok', $type, ["ok" => $ok]);
3090 /// @TODO move to top of file or somewhere better
3091 api_register_func('api/help/test', 'api_help_test', false);
3094 * Returns all lists the user subscribes to.
3096 * @param string $type Return type (atom, rss, xml, json)
3098 * @return array|string
3099 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3101 function api_lists_list($type)
3104 /// @TODO $ret is not filled here?
3105 return api_format_data('lists', $type, ["lists_list" => $ret]);
3108 /// @TODO move to top of file or somewhere better
3109 api_register_func('api/lists/list', 'api_lists_list', true);
3110 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3113 * Returns all groups the user owns.
3115 * @param string $type Return type (atom, rss, xml, json)
3117 * @return array|string
3118 * @throws BadRequestException
3119 * @throws ForbiddenException
3120 * @throws ImagickException
3121 * @throws InternalServerErrorException
3122 * @throws UnauthorizedException
3123 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3125 function api_lists_ownerships($type)
3129 if (api_user() === false) {
3130 throw new ForbiddenException();
3134 $user_info = api_get_user($a);
3135 $uid = $user_info['uid'];
3137 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3139 // loop through all groups
3141 foreach ($groups as $group) {
3142 if ($group['visible']) {
3148 'name' => $group['name'],
3149 'id' => intval($group['id']),
3150 'id_str' => (string) $group['id'],
3151 'user' => $user_info,
3155 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3158 /// @TODO move to top of file or somewhere better
3159 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3162 * Returns recent statuses from users in the specified group.
3164 * @param string $type Return type (atom, rss, xml, json)
3166 * @return array|string
3167 * @throws BadRequestException
3168 * @throws ForbiddenException
3169 * @throws ImagickException
3170 * @throws InternalServerErrorException
3171 * @throws UnauthorizedException
3172 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3174 function api_lists_statuses($type)
3178 $user_info = api_get_user($a);
3179 if (api_user() === false || $user_info === false) {
3180 throw new ForbiddenException();
3183 unset($_REQUEST["user_id"]);
3184 unset($_GET["user_id"]);
3186 unset($_REQUEST["screen_name"]);
3187 unset($_GET["screen_name"]);
3189 if (empty($_REQUEST['list_id'])) {
3190 throw new BadRequestException('list_id not specified');
3194 $count = defaults($_REQUEST, 'count', 20);
3195 $page = (!empty($_REQUEST['page']) ? $_REQUEST['page'] - 1 : 0);
3199 $since_id = defaults($_REQUEST, 'since_id', 0);
3200 $max_id = defaults($_REQUEST, 'max_id', 0);
3201 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3202 $conversation_id = defaults($_REQUEST, 'conversation_id', 0);
3204 $start = $page * $count;
3206 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3207 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3210 $condition[0] .= " AND `item`.`id` <= ?";
3211 $condition[] = $max_id;
3213 if ($exclude_replies > 0) {
3214 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3216 if ($conversation_id > 0) {
3217 $condition[0] .= " AND `item`.`parent` = ?";
3218 $condition[] = $conversation_id;
3221 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3222 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3224 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3226 $data = ['status' => $items];
3231 $data = api_rss_extra($a, $data, $user_info);
3235 return api_format_data("statuses", $type, $data);
3238 /// @TODO move to top of file or somewhere better
3239 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3242 * Considers friends and followers lists to be private and won't return
3243 * anything if any user_id parameter is passed.
3245 * @brief Returns either the friends of the follower list
3247 * @param string $qtype Either "friends" or "followers"
3248 * @return boolean|array
3249 * @throws BadRequestException
3250 * @throws ForbiddenException
3251 * @throws ImagickException
3252 * @throws InternalServerErrorException
3253 * @throws UnauthorizedException
3255 function api_statuses_f($qtype)
3259 if (api_user() === false) {
3260 throw new ForbiddenException();
3264 $count = defaults($_GET, 'count', 20);
3265 $page = defaults($_GET, 'page', 1);
3269 $start = ($page - 1) * $count;
3271 $user_info = api_get_user($a);
3273 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3274 /* this is to stop Hotot to load friends multiple times
3275 * I'm not sure if I'm missing return something or
3276 * is a bug in hotot. Workaround, meantime
3280 return array('$users' => $ret);*/
3285 if ($qtype == 'friends') {
3286 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3287 } elseif ($qtype == 'followers') {
3288 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3291 // friends and followers only for self
3292 if ($user_info['self'] == 0) {
3293 $sql_extra = " AND false ";
3296 if ($qtype == 'blocks') {
3297 $sql_filter = 'AND `blocked` AND NOT `pending`';
3298 } elseif ($qtype == 'incoming') {
3299 $sql_filter = 'AND `pending`';
3301 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3319 foreach ($r as $cid) {
3320 $user = api_get_user($a, $cid['nurl']);
3321 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3322 unset($user["uid"]);
3323 unset($user["self"]);
3330 return ['user' => $ret];
3335 * Returns the user's friends.
3337 * @brief Returns the list of friends of the provided user
3339 * @deprecated By Twitter API in favor of friends/list
3341 * @param string $type Either "json" or "xml"
3342 * @return boolean|string|array
3343 * @throws BadRequestException
3344 * @throws ForbiddenException
3346 function api_statuses_friends($type)
3348 $data = api_statuses_f("friends");
3349 if ($data === false) {
3352 return api_format_data("users", $type, $data);
3356 * Returns the user's followers.
3358 * @brief Returns the list of followers of the provided user
3360 * @deprecated By Twitter API in favor of friends/list
3362 * @param string $type Either "json" or "xml"
3363 * @return boolean|string|array
3364 * @throws BadRequestException
3365 * @throws ForbiddenException
3367 function api_statuses_followers($type)
3369 $data = api_statuses_f("followers");
3370 if ($data === false) {
3373 return api_format_data("users", $type, $data);
3376 /// @TODO move to top of file or somewhere better
3377 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3378 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3381 * Returns the list of blocked users
3383 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3385 * @param string $type Either "json" or "xml"
3387 * @return boolean|string|array
3388 * @throws BadRequestException
3389 * @throws ForbiddenException
3391 function api_blocks_list($type)
3393 $data = api_statuses_f('blocks');
3394 if ($data === false) {
3397 return api_format_data("users", $type, $data);
3400 /// @TODO move to top of file or somewhere better
3401 api_register_func('api/blocks/list', 'api_blocks_list', true);
3404 * Returns the list of pending users IDs
3406 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3408 * @param string $type Either "json" or "xml"
3410 * @return boolean|string|array
3411 * @throws BadRequestException
3412 * @throws ForbiddenException
3414 function api_friendships_incoming($type)
3416 $data = api_statuses_f('incoming');
3417 if ($data === false) {
3422 foreach ($data['user'] as $user) {
3423 $ids[] = $user['id'];
3426 return api_format_data("ids", $type, ['id' => $ids]);
3429 /// @TODO move to top of file or somewhere better
3430 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3433 * Returns the instance's configuration information.
3435 * @param string $type Return type (atom, rss, xml, json)
3437 * @return array|string
3438 * @throws InternalServerErrorException
3440 function api_statusnet_config($type)
3444 $name = Config::get('config', 'sitename');
3445 $server = $a->getHostName();
3446 $logo = System::baseUrl() . '/images/friendica-64.png';
3447 $email = Config::get('config', 'admin_email');
3448 $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3449 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3450 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3451 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3452 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3455 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3456 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3457 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3458 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3459 'shorturllength' => '30',
3461 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3462 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3463 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3464 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3469 return api_format_data('config', $type, ['config' => $config]);
3472 /// @TODO move to top of file or somewhere better
3473 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3474 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3478 * @param string $type Return type (atom, rss, xml, json)
3480 * @return array|string
3482 function api_statusnet_version($type)
3485 $fake_statusnet_version = "0.9.7";
3487 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3490 /// @TODO move to top of file or somewhere better
3491 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3492 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3496 * @param string $type Return type (atom, rss, xml, json)
3498 * @return array|string|void
3499 * @throws BadRequestException
3500 * @throws ForbiddenException
3501 * @throws ImagickException
3502 * @throws InternalServerErrorException
3503 * @throws UnauthorizedException
3504 * @todo use api_format_data() to return data
3506 function api_ff_ids($type)
3509 throw new ForbiddenException();
3516 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3519 "SELECT `pcontact`.`id` FROM `contact`
3520 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3521 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3524 if (!DBA::isResult($r)) {
3529 foreach ($r as $rr) {
3530 if ($stringify_ids) {
3533 $ids[] = intval($rr['id']);
3537 return api_format_data("ids", $type, ['id' => $ids]);
3541 * Returns the ID of every user the user is following.
3543 * @param string $type Return type (atom, rss, xml, json)
3545 * @return array|string
3546 * @throws BadRequestException
3547 * @throws ForbiddenException
3548 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3550 function api_friends_ids($type)
3552 return api_ff_ids($type);
3556 * Returns the ID of every user following the user.
3558 * @param string $type Return type (atom, rss, xml, json)
3560 * @return array|string
3561 * @throws BadRequestException
3562 * @throws ForbiddenException
3563 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3565 function api_followers_ids($type)
3567 return api_ff_ids($type);
3570 /// @TODO move to top of file or somewhere better
3571 api_register_func('api/friends/ids', 'api_friends_ids', true);
3572 api_register_func('api/followers/ids', 'api_followers_ids', true);
3575 * Sends a new direct message.
3577 * @param string $type Return type (atom, rss, xml, json)
3579 * @return array|string
3580 * @throws BadRequestException
3581 * @throws ForbiddenException
3582 * @throws ImagickException
3583 * @throws InternalServerErrorException
3584 * @throws NotFoundException
3585 * @throws UnauthorizedException
3586 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3588 function api_direct_messages_new($type)
3592 if (api_user() === false) {
3593 throw new ForbiddenException();
3596 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3600 $sender = api_get_user($a);
3603 if (!empty($_POST['screen_name'])) {
3605 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3607 DBA::escape($_POST['screen_name'])
3610 if (DBA::isResult($r)) {
3611 // Selecting the id by priority, friendica first
3612 api_best_nickname($r);
3614 $recipient = api_get_user($a, $r[0]['nurl']);
3617 $recipient = api_get_user($a, $_POST['user_id']);
3620 if (empty($recipient)) {
3621 throw new NotFoundException('Recipient not found');
3625 if (!empty($_REQUEST['replyto'])) {
3627 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3629 intval($_REQUEST['replyto'])
3631 $replyto = $r[0]['parent-uri'];
3632 $sub = $r[0]['title'];
3634 if (!empty($_REQUEST['title'])) {
3635 $sub = $_REQUEST['title'];
3637 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3641 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3644 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3645 $ret = api_format_messages($r[0], $recipient, $sender);
3647 $ret = ["error"=>$id];
3650 $data = ['direct_message'=>$ret];
3656 $data = api_rss_extra($a, $data, $sender);
3660 return api_format_data("direct-messages", $type, $data);
3663 /// @TODO move to top of file or somewhere better
3664 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3667 * Destroys a direct message.
3669 * @brief delete a direct_message from mail table through api
3671 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3672 * @return string|array
3673 * @throws BadRequestException
3674 * @throws ForbiddenException
3675 * @throws ImagickException
3676 * @throws InternalServerErrorException
3677 * @throws UnauthorizedException
3678 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3680 function api_direct_messages_destroy($type)
3684 if (api_user() === false) {
3685 throw new ForbiddenException();
3689 $user_info = api_get_user($a);
3691 $id = defaults($_REQUEST, 'id', 0);
3693 $parenturi = defaults($_REQUEST, 'friendica_parenturi', "");
3694 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3695 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3697 $uid = $user_info['uid'];
3698 // error if no id or parenturi specified (for clients posting parent-uri as well)
3699 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3700 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3701 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3704 // BadRequestException if no id specified (for clients using Twitter API)
3706 throw new BadRequestException('Message id not specified');
3709 // add parent-uri to sql command if specified by calling app
3710 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3712 // get data of the specified message id
3714 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3719 // error message if specified id is not in database
3720 if (!DBA::isResult($r)) {
3721 if ($verbose == "true") {
3722 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3723 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3725 /// @todo BadRequestException ok for Twitter API clients?
3726 throw new BadRequestException('message id not in database');
3731 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3736 if ($verbose == "true") {
3739 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3740 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3742 $answer = ['result' => 'error', 'message' => 'unknown error'];
3743 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3746 /// @todo return JSON data like Twitter API not yet implemented
3749 /// @TODO move to top of file or somewhere better
3750 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3755 * @brief unfollow contact
3757 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3758 * @return string|array
3759 * @throws BadRequestException
3760 * @throws ForbiddenException
3761 * @throws ImagickException
3762 * @throws InternalServerErrorException
3763 * @throws NotFoundException
3764 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3766 function api_friendships_destroy($type)
3770 if ($uid === false) {
3771 throw new ForbiddenException();
3774 $contact_id = defaults($_REQUEST, 'user_id');
3776 if (empty($contact_id)) {
3777 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3778 throw new BadRequestException("no user_id specified");
3781 // Get Contact by given id
3782 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3784 if(!DBA::isResult($contact)) {
3785 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3786 throw new NotFoundException("no contact found to given ID");
3789 $url = $contact["url"];
3791 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3792 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3793 Strings::normaliseLink($url), $url];
3794 $contact = DBA::selectFirst('contact', [], $condition);
3796 if (!DBA::isResult($contact)) {
3797 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3798 throw new NotFoundException("Not following Contact");
3801 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3802 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3803 throw new ExpectationFailedException("Not supported");
3806 $dissolve = ($contact['rel'] == Contact::SHARING);
3808 $owner = User::getOwnerDataById($uid);
3810 Contact::terminateFriendship($owner, $contact, $dissolve);
3813 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3814 throw new NotFoundException("Error Processing Request");
3817 // Sharing-only contacts get deleted as there no relationship any more
3819 Contact::remove($contact['id']);
3821 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3824 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3825 unset($contact["uid"]);
3826 unset($contact["self"]);
3828 // Set screen_name since Twidere requests it
3829 $contact["screen_name"] = $contact["nick"];
3831 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3833 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3837 * @param string $type Return type (atom, rss, xml, json)
3838 * @param string $box
3839 * @param string $verbose
3841 * @return array|string
3842 * @throws BadRequestException
3843 * @throws ForbiddenException
3844 * @throws ImagickException
3845 * @throws InternalServerErrorException
3846 * @throws UnauthorizedException
3848 function api_direct_messages_box($type, $box, $verbose)
3851 if (api_user() === false) {
3852 throw new ForbiddenException();
3855 $count = defaults($_GET, 'count', 20);
3856 $page = defaults($_REQUEST, 'page', 1) - 1;
3861 $since_id = defaults($_REQUEST, 'since_id', 0);
3862 $max_id = defaults($_REQUEST, 'max_id', 0);
3864 $user_id = defaults($_REQUEST, 'user_id', '');
3865 $screen_name = defaults($_REQUEST, 'screen_name', '');
3868 unset($_REQUEST["user_id"]);
3869 unset($_GET["user_id"]);
3871 unset($_REQUEST["screen_name"]);
3872 unset($_GET["screen_name"]);
3874 $user_info = api_get_user($a);
3875 if ($user_info === false) {
3876 throw new ForbiddenException();
3878 $profile_url = $user_info["url"];
3881 $start = $page * $count;
3886 if ($box=="sentbox") {
3887 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3888 } elseif ($box == "conversation") {
3889 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape(defaults($_GET, 'uri', '')) . "'";
3890 } elseif ($box == "all") {
3891 $sql_extra = "true";
3892 } elseif ($box == "inbox") {
3893 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3897 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3900 if ($user_id != "") {
3901 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3902 } elseif ($screen_name !="") {
3903 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3907 "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",
3913 if ($verbose == "true" && !DBA::isResult($r)) {
3914 $answer = ['result' => 'error', 'message' => 'no mails available'];
3915 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3919 foreach ($r as $item) {
3920 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3921 $recipient = $user_info;
3922 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3923 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3924 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3925 $sender = $user_info;
3928 if (isset($recipient) && isset($sender)) {
3929 $ret[] = api_format_messages($item, $recipient, $sender);
3934 $data = ['direct_message' => $ret];
3939 $data = api_rss_extra($a, $data, $user_info);
3943 return api_format_data("direct-messages", $type, $data);
3947 * Returns the most recent direct messages sent by the user.
3949 * @param string $type Return type (atom, rss, xml, json)
3951 * @return array|string
3952 * @throws BadRequestException
3953 * @throws ForbiddenException
3954 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3956 function api_direct_messages_sentbox($type)
3958 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3959 return api_direct_messages_box($type, "sentbox", $verbose);
3963 * Returns the most recent direct messages sent to the user.
3965 * @param string $type Return type (atom, rss, xml, json)
3967 * @return array|string
3968 * @throws BadRequestException
3969 * @throws ForbiddenException
3970 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3972 function api_direct_messages_inbox($type)
3974 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3975 return api_direct_messages_box($type, "inbox", $verbose);
3980 * @param string $type Return type (atom, rss, xml, json)
3982 * @return array|string
3983 * @throws BadRequestException
3984 * @throws ForbiddenException
3986 function api_direct_messages_all($type)
3988 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3989 return api_direct_messages_box($type, "all", $verbose);
3994 * @param string $type Return type (atom, rss, xml, json)
3996 * @return array|string
3997 * @throws BadRequestException
3998 * @throws ForbiddenException
4000 function api_direct_messages_conversation($type)
4002 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4003 return api_direct_messages_box($type, "conversation", $verbose);
4006 /// @TODO move to top of file or somewhere better
4007 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4008 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4009 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4010 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4013 * Returns an OAuth Request Token.
4015 * @see https://oauth.net/core/1.0/#auth_step1
4017 function api_oauth_request_token()
4019 $oauth1 = new FKOAuth1();
4021 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4022 } catch (Exception $e) {
4023 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4031 * Returns an OAuth Access Token.
4033 * @return array|string
4034 * @see https://oauth.net/core/1.0/#auth_step3
4036 function api_oauth_access_token()
4038 $oauth1 = new FKOAuth1();
4040 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4041 } catch (Exception $e) {
4042 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4049 /// @TODO move to top of file or somewhere better
4050 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4051 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4055 * @brief delete a complete photoalbum with all containing photos from database through api
4057 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4058 * @return string|array
4059 * @throws BadRequestException
4060 * @throws ForbiddenException
4061 * @throws InternalServerErrorException
4063 function api_fr_photoalbum_delete($type)
4065 if (api_user() === false) {
4066 throw new ForbiddenException();
4069 $album = defaults($_REQUEST, 'album', "");
4071 // we do not allow calls without album string
4073 throw new BadRequestException("no albumname specified");
4075 // check if album is existing
4077 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4081 if (!DBA::isResult($r)) {
4082 throw new BadRequestException("album not available");
4085 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4086 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4087 foreach ($r as $rr) {
4088 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4089 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4091 if (!DBA::isResult($photo_item)) {
4092 throw new InternalServerErrorException("problem with deleting items occured");
4094 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4097 // now let's delete all photos from the album
4098 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4100 // return success of deletion or error message
4102 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4103 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4105 throw new InternalServerErrorException("unknown error - deleting from database failed");
4110 * @brief update the name of the album for all photos of an album
4112 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4113 * @return string|array
4114 * @throws BadRequestException
4115 * @throws ForbiddenException
4116 * @throws InternalServerErrorException
4118 function api_fr_photoalbum_update($type)
4120 if (api_user() === false) {
4121 throw new ForbiddenException();
4124 $album = defaults($_REQUEST, 'album', "");
4125 $album_new = defaults($_REQUEST, 'album_new', "");
4127 // we do not allow calls without album string
4129 throw new BadRequestException("no albumname specified");
4131 if ($album_new == "") {
4132 throw new BadRequestException("no new albumname specified");
4134 // check if album is existing
4135 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4136 throw new BadRequestException("album not available");
4138 // now let's update all photos to the albumname
4139 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4141 // return success of updating or error message
4143 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4144 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4146 throw new InternalServerErrorException("unknown error - updating in database failed");
4152 * @brief list all photos of the authenticated user
4154 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4155 * @return string|array
4156 * @throws ForbiddenException
4157 * @throws InternalServerErrorException
4159 function api_fr_photos_list($type)
4161 if (api_user() === false) {
4162 throw new ForbiddenException();
4165 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4166 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4167 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4168 intval(local_user())
4171 'image/jpeg' => 'jpg',
4172 'image/png' => 'png',
4173 'image/gif' => 'gif'
4175 $data = ['photo'=>[]];
4176 if (DBA::isResult($r)) {
4177 foreach ($r as $rr) {
4179 $photo['id'] = $rr['resource-id'];
4180 $photo['album'] = $rr['album'];
4181 $photo['filename'] = $rr['filename'];
4182 $photo['type'] = $rr['type'];
4183 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4184 $photo['created'] = $rr['created'];
4185 $photo['edited'] = $rr['edited'];
4186 $photo['desc'] = $rr['desc'];
4188 if ($type == "xml") {
4189 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4191 $photo['thumb'] = $thumb;
4192 $data['photo'][] = $photo;
4196 return api_format_data("photos", $type, $data);
4200 * @brief upload a new photo or change an existing photo
4202 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4203 * @return string|array
4204 * @throws BadRequestException
4205 * @throws ForbiddenException
4206 * @throws ImagickException
4207 * @throws InternalServerErrorException
4208 * @throws NotFoundException
4210 function api_fr_photo_create_update($type)
4212 if (api_user() === false) {
4213 throw new ForbiddenException();
4216 $photo_id = defaults($_REQUEST, 'photo_id', null);
4217 $desc = defaults($_REQUEST, 'desc', (array_key_exists('desc', $_REQUEST) ? "" : null)) ; // extra check necessary to distinguish between 'not provided' and 'empty string'
4218 $album = defaults($_REQUEST, 'album', null);
4219 $album_new = defaults($_REQUEST, 'album_new', null);
4220 $allow_cid = defaults($_REQUEST, 'allow_cid', (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4221 $deny_cid = defaults($_REQUEST, 'deny_cid' , (array_key_exists('deny_cid' , $_REQUEST) ? " " : null));
4222 $allow_gid = defaults($_REQUEST, 'allow_gid', (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4223 $deny_gid = defaults($_REQUEST, 'deny_gid' , (array_key_exists('deny_gid' , $_REQUEST) ? " " : null));
4224 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4226 // do several checks on input parameters
4227 // we do not allow calls without album string
4228 if ($album == null) {
4229 throw new BadRequestException("no albumname specified");
4231 // if photo_id == null --> we are uploading a new photo
4232 if ($photo_id == null) {
4235 // error if no media posted in create-mode
4236 if (empty($_FILES['media'])) {
4238 throw new BadRequestException("no media data submitted");
4241 // album_new will be ignored in create-mode
4246 // check if photo is existing in databasei
4247 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4248 throw new BadRequestException("photo not available");
4252 // checks on acl strings provided by clients
4253 $acl_input_error = false;
4254 $acl_input_error |= check_acl_input($allow_cid);
4255 $acl_input_error |= check_acl_input($deny_cid);
4256 $acl_input_error |= check_acl_input($allow_gid);
4257 $acl_input_error |= check_acl_input($deny_gid);
4258 if ($acl_input_error) {
4259 throw new BadRequestException("acl data invalid");
4261 // now let's upload the new media in create-mode
4262 if ($mode == "create") {
4263 $media = $_FILES['media'];
4264 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4266 // return success of updating or error message
4267 if (!is_null($data)) {
4268 return api_format_data("photo_create", $type, $data);
4270 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4274 // now let's do the changes in update-mode
4275 if ($mode == "update") {
4276 $updated_fields = [];
4278 if (!is_null($desc)) {
4279 $updated_fields['desc'] = $desc;
4282 if (!is_null($album_new)) {
4283 $updated_fields['album'] = $album_new;
4286 if (!is_null($allow_cid)) {
4287 $allow_cid = trim($allow_cid);
4288 $updated_fields['allow_cid'] = $allow_cid;
4291 if (!is_null($deny_cid)) {
4292 $deny_cid = trim($deny_cid);
4293 $updated_fields['deny_cid'] = $deny_cid;
4296 if (!is_null($allow_gid)) {
4297 $allow_gid = trim($allow_gid);
4298 $updated_fields['allow_gid'] = $allow_gid;
4301 if (!is_null($deny_gid)) {
4302 $deny_gid = trim($deny_gid);
4303 $updated_fields['deny_gid'] = $deny_gid;
4307 if (count($updated_fields) > 0) {
4308 $nothingtodo = false;
4309 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4311 $nothingtodo = true;
4314 if (!empty($_FILES['media'])) {
4315 $nothingtodo = false;
4316 $media = $_FILES['media'];
4317 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4318 if (!is_null($data)) {
4319 return api_format_data("photo_update", $type, $data);
4323 // return success of updating or error message
4325 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4326 return api_format_data("photo_update", $type, ['$result' => $answer]);
4329 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4330 return api_format_data("photo_update", $type, ['$result' => $answer]);
4332 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4335 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4339 * @brief delete a single photo from the database through api
4341 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4342 * @return string|array
4343 * @throws BadRequestException
4344 * @throws ForbiddenException
4345 * @throws InternalServerErrorException
4347 function api_fr_photo_delete($type)
4349 if (api_user() === false) {
4350 throw new ForbiddenException();
4354 $photo_id = defaults($_REQUEST, 'photo_id', null);
4356 // do several checks on input parameters
4357 // we do not allow calls without photo id
4358 if ($photo_id == null) {
4359 throw new BadRequestException("no photo_id specified");
4362 // check if photo is existing in database
4363 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4364 throw new BadRequestException("photo not available");
4367 // now we can perform on the deletion of the photo
4368 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4370 // return success of deletion or error message
4372 // retrieve the id of the parent element (the photo element)
4373 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4374 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4376 if (!DBA::isResult($photo_item)) {
4377 throw new InternalServerErrorException("problem with deleting items occured");
4379 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4380 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4381 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4383 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4384 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4386 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4392 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4394 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4395 * @return string|array
4396 * @throws BadRequestException
4397 * @throws ForbiddenException
4398 * @throws InternalServerErrorException
4399 * @throws NotFoundException
4401 function api_fr_photo_detail($type)
4403 if (api_user() === false) {
4404 throw new ForbiddenException();
4406 if (empty($_REQUEST['photo_id'])) {
4407 throw new BadRequestException("No photo id.");
4410 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4411 $photo_id = $_REQUEST['photo_id'];
4413 // prepare json/xml output with data from database for the requested photo
4414 $data = prepare_photo_data($type, $scale, $photo_id);
4416 return api_format_data("photo_detail", $type, $data);
4421 * Updates the user’s profile image.
4423 * @brief updates the profile image for the user (either a specified profile or the default profile)
4425 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4427 * @return string|array
4428 * @throws BadRequestException
4429 * @throws ForbiddenException
4430 * @throws ImagickException
4431 * @throws InternalServerErrorException
4432 * @throws NotFoundException
4433 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4435 function api_account_update_profile_image($type)
4437 if (api_user() === false) {
4438 throw new ForbiddenException();
4441 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4443 // error if image data is missing
4444 if (empty($_FILES['image'])) {
4445 throw new BadRequestException("no media data submitted");
4448 // check if specified profile id is valid
4449 if ($profile_id != 0) {
4450 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4451 // error message if specified profile id is not in database
4452 if (!DBA::isResult($profile)) {
4453 throw new BadRequestException("profile_id not available");
4455 $is_default_profile = $profile['is-default'];
4457 $is_default_profile = 1;
4460 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4462 if (!empty($_FILES['image'])) {
4463 $media = $_FILES['image'];
4464 } elseif (!empty($_FILES['media'])) {
4465 $media = $_FILES['media'];
4467 // save new profile image
4468 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4471 if (is_array($media['type'])) {
4472 $filetype = $media['type'][0];
4474 $filetype = $media['type'];
4476 if ($filetype == "image/jpeg") {
4478 } elseif ($filetype == "image/png") {
4481 throw new InternalServerErrorException('Unsupported filetype');
4484 // change specified profile or all profiles to the new resource-id
4485 if ($is_default_profile) {
4486 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4487 Photo::update(['profile' => false], $condition);
4489 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4490 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4491 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4494 Contact::updateSelfFromUserID(api_user(), true);
4496 // Update global directory in background
4497 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4498 if ($url && strlen(Config::get('system', 'directory'))) {
4499 Worker::add(PRIORITY_LOW, "Directory", $url);
4502 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4504 // output for client
4506 return api_account_verify_credentials($type);
4508 // SaveMediaToDatabase failed for some reason
4509 throw new InternalServerErrorException("image upload failed");
4513 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4514 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4515 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4516 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4517 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4518 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4519 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4520 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4521 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4524 * Update user profile
4526 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4528 * @return array|string
4529 * @throws BadRequestException
4530 * @throws ForbiddenException
4531 * @throws ImagickException
4532 * @throws InternalServerErrorException
4533 * @throws UnauthorizedException
4535 function api_account_update_profile($type)
4537 $local_user = api_user();
4538 $api_user = api_get_user(get_app());
4540 if (!empty($_POST['name'])) {
4541 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4542 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4543 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4544 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4547 if (isset($_POST['description'])) {
4548 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4549 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4550 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4553 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4554 // Update global directory in background
4555 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4556 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4559 return api_account_verify_credentials($type);
4562 /// @TODO move to top of file or somewhere better
4563 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4567 * @param string $acl_string
4571 function check_acl_input($acl_string)
4573 if ($acl_string == null || $acl_string == " ") {
4576 $contact_not_found = false;
4578 // split <x><y><z> into array of cid's
4579 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4581 // check for each cid if it is available on server
4582 $cid_array = $array[0];
4583 foreach ($cid_array as $cid) {
4584 $cid = str_replace("<", "", $cid);
4585 $cid = str_replace(">", "", $cid);
4586 $condition = ['id' => $cid, 'uid' => api_user()];
4587 $contact_not_found |= !DBA::exists('contact', $condition);
4589 return $contact_not_found;
4594 * @param string $mediatype
4595 * @param array $media
4596 * @param string $type
4597 * @param string $album
4598 * @param string $allow_cid
4599 * @param string $deny_cid
4600 * @param string $allow_gid
4601 * @param string $deny_gid
4602 * @param string $desc
4603 * @param integer $profile
4604 * @param boolean $visibility
4605 * @param string $photo_id
4607 * @throws BadRequestException
4608 * @throws ForbiddenException
4609 * @throws ImagickException
4610 * @throws InternalServerErrorException
4611 * @throws NotFoundException
4613 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)
4621 if (is_array($media)) {
4622 if (is_array($media['tmp_name'])) {
4623 $src = $media['tmp_name'][0];
4625 $src = $media['tmp_name'];
4627 if (is_array($media['name'])) {
4628 $filename = basename($media['name'][0]);
4630 $filename = basename($media['name']);
4632 if (is_array($media['size'])) {
4633 $filesize = intval($media['size'][0]);
4635 $filesize = intval($media['size']);
4637 if (is_array($media['type'])) {
4638 $filetype = $media['type'][0];
4640 $filetype = $media['type'];
4644 if ($filetype == "") {
4645 $filetype=Image::guessType($filename);
4647 $imagedata = @getimagesize($src);
4649 $filetype = $imagedata['mime'];
4652 "File upload src: " . $src . " - filename: " . $filename .
4653 " - size: " . $filesize . " - type: " . $filetype,
4657 // check if there was a php upload error
4658 if ($filesize == 0 && $media['error'] == 1) {
4659 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4661 // check against max upload size within Friendica instance
4662 $maximagesize = Config::get('system', 'maximagesize');
4663 if ($maximagesize && ($filesize > $maximagesize)) {
4664 $formattedBytes = Strings::formatBytes($maximagesize);
4665 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4668 // create Photo instance with the data of the image
4669 $imagedata = @file_get_contents($src);
4670 $Image = new Image($imagedata, $filetype);
4671 if (!$Image->isValid()) {
4672 throw new InternalServerErrorException("unable to process image data");
4675 // check orientation of image
4676 $Image->orient($src);
4679 // check max length of images on server
4680 $max_length = Config::get('system', 'max_image_length');
4682 $max_length = MAX_IMAGE_LENGTH;
4684 if ($max_length > 0) {
4685 $Image->scaleDown($max_length);
4686 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4688 $width = $Image->getWidth();
4689 $height = $Image->getHeight();
4691 // create a new resource-id if not already provided
4692 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4694 if ($mediatype == "photo") {
4695 // upload normal image (scales 0, 1, 2)
4696 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4698 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4700 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4702 if ($width > 640 || $height > 640) {
4703 $Image->scaleDown(640);
4704 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4706 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4710 if ($width > 320 || $height > 320) {
4711 $Image->scaleDown(320);
4712 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4714 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4717 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4718 } elseif ($mediatype == "profileimage") {
4719 // upload profile image (scales 4, 5, 6)
4720 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4722 if ($width > 300 || $height > 300) {
4723 $Image->scaleDown(300);
4724 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4726 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4730 if ($width > 80 || $height > 80) {
4731 $Image->scaleDown(80);
4732 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4734 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4738 if ($width > 48 || $height > 48) {
4739 $Image->scaleDown(48);
4740 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4742 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4745 $Image->__destruct();
4746 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4749 if (isset($r) && $r) {
4750 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4751 if ($photo_id == null && $mediatype == "photo") {
4752 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4754 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4755 return prepare_photo_data($type, false, $hash);
4757 throw new InternalServerErrorException("image upload failed");
4763 * @param string $hash
4764 * @param string $allow_cid
4765 * @param string $deny_cid
4766 * @param string $allow_gid
4767 * @param string $deny_gid
4768 * @param string $filetype
4769 * @param boolean $visibility
4770 * @throws InternalServerErrorException
4772 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4774 // get data about the api authenticated user
4775 $uri = Item::newURI(intval(api_user()));
4776 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4779 $arr['guid'] = System::createUUID();
4780 $arr['uid'] = intval(api_user());
4782 $arr['parent-uri'] = $uri;
4783 $arr['type'] = 'photo';
4785 $arr['resource-id'] = $hash;
4786 $arr['contact-id'] = $owner_record['id'];
4787 $arr['owner-name'] = $owner_record['name'];
4788 $arr['owner-link'] = $owner_record['url'];
4789 $arr['owner-avatar'] = $owner_record['thumb'];
4790 $arr['author-name'] = $owner_record['name'];
4791 $arr['author-link'] = $owner_record['url'];
4792 $arr['author-avatar'] = $owner_record['thumb'];
4794 $arr['allow_cid'] = $allow_cid;
4795 $arr['allow_gid'] = $allow_gid;
4796 $arr['deny_cid'] = $deny_cid;
4797 $arr['deny_gid'] = $deny_gid;
4798 $arr['visible'] = $visibility;
4802 'image/jpeg' => 'jpg',
4803 'image/png' => 'png',
4804 'image/gif' => 'gif'
4807 // adds link to the thumbnail scale photo
4808 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4809 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4812 // do the magic for storing the item in the database and trigger the federation to other contacts
4818 * @param string $type
4820 * @param string $photo_id
4823 * @throws BadRequestException
4824 * @throws ForbiddenException
4825 * @throws ImagickException
4826 * @throws InternalServerErrorException
4827 * @throws NotFoundException
4828 * @throws UnauthorizedException
4830 function prepare_photo_data($type, $scale, $photo_id)
4833 $user_info = api_get_user($a);
4835 if ($user_info === false) {
4836 throw new ForbiddenException();
4839 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4840 $data_sql = ($scale === false ? "" : "data, ");
4842 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4843 // clients needs to convert this in their way for further processing
4845 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4846 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4847 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4848 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4850 intval(local_user()),
4851 DBA::escape($photo_id),
4856 'image/jpeg' => 'jpg',
4857 'image/png' => 'png',
4858 'image/gif' => 'gif'
4861 // prepare output data for photo
4862 if (DBA::isResult($r)) {
4863 $data = ['photo' => $r[0]];
4864 $data['photo']['id'] = $data['photo']['resource-id'];
4865 if ($scale !== false) {
4866 $data['photo']['data'] = base64_encode($data['photo']['data']);
4868 unset($data['photo']['datasize']); //needed only with scale param
4870 if ($type == "xml") {
4871 $data['photo']['links'] = [];
4872 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4873 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4875 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4878 $data['photo']['link'] = [];
4879 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4881 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4882 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4886 unset($data['photo']['resource-id']);
4887 unset($data['photo']['minscale']);
4888 unset($data['photo']['maxscale']);
4890 throw new NotFoundException();
4893 // retrieve item element for getting activities (like, dislike etc.) related to photo
4894 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4895 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4897 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4899 // retrieve comments on photo
4900 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4901 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4903 $statuses = Item::selectForUser(api_user(), [], $condition);
4905 // prepare output of comments
4906 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
4908 if ($type == "xml") {
4910 foreach ($commentData as $comment) {
4911 $comments[$k++ . ":comment"] = $comment;
4914 foreach ($commentData as $comment) {
4915 $comments[] = $comment;
4918 $data['photo']['friendica_comments'] = $comments;
4920 // include info if rights on photo and rights on item are mismatching
4921 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4922 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4923 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4924 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4925 $data['photo']['rights_mismatch'] = $rights_mismatch;
4932 * Similar as /mod/redir.php
4933 * redirect to 'url' after dfrn auth
4935 * Why this when there is mod/redir.php already?
4936 * This use api_user() and api_login()
4939 * c_url: url of remote contact to auth to
4940 * url: string, url to redirect after auth
4942 function api_friendica_remoteauth()
4944 $url = defaults($_GET, 'url', '');
4945 $c_url = defaults($_GET, 'c_url', '');
4947 if ($url === '' || $c_url === '') {
4948 throw new BadRequestException("Wrong parameters.");
4951 $c_url = Strings::normaliseLink($c_url);
4955 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4957 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
4958 throw new BadRequestException("Unknown contact");
4961 $cid = $contact['id'];
4963 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4965 if ($contact['duplex'] && $contact['issued-id']) {
4966 $orig_id = $contact['issued-id'];
4967 $dfrn_id = '1:' . $orig_id;
4969 if ($contact['duplex'] && $contact['dfrn-id']) {
4970 $orig_id = $contact['dfrn-id'];
4971 $dfrn_id = '0:' . $orig_id;
4974 $sec = Strings::getRandomHex();
4976 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4977 'sec' => $sec, 'expire' => time() + 45];
4978 DBA::insert('profile_check', $fields);
4980 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
4981 $dest = ($url ? '&destination_url=' . $url : '');
4983 System::externalRedirect(
4984 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4985 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4986 . '&type=profile&sec=' . $sec . $dest
4989 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4992 * Return an item with announcer data if it had been announced
4994 * @param array $item Item array
4995 * @return array Item array with announce data
4997 function api_get_announce($item)
4999 // Quit if the item already has got a different owner and author
5000 if ($item['owner-id'] != $item['author-id']) {
5004 // Don't change original or Diaspora posts
5005 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5009 // Quit if we do now the original author and it had been a post from a native network
5010 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5014 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5015 $activity = Item::activityToIndex(ACTIVITY2_ANNOUNCE);
5016 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5017 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['created' => true]]);
5018 if (!DBA::isResult($announce)) {
5022 return array_merge($item, $announce);
5026 * @brief Return the item shared, if the item contains only the [share] tag
5028 * @param array $item Sharer item
5029 * @return array|false Shared item or false if not a reshare
5030 * @throws ImagickException
5031 * @throws InternalServerErrorException
5033 function api_share_as_retweet(&$item)
5035 $body = trim($item["body"]);
5037 if (Diaspora::isReshare($body, false) === false) {
5038 if ($item['author-id'] == $item['owner-id']) {
5041 // Reshares from OStatus, ActivityPub and Twitter
5042 $reshared_item = $item;
5043 $reshared_item['owner-id'] = $reshared_item['author-id'];
5044 $reshared_item['owner-link'] = $reshared_item['author-link'];
5045 $reshared_item['owner-name'] = $reshared_item['author-name'];
5046 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5047 return $reshared_item;
5051 /// @TODO "$1" should maybe mean '$1' ?
5052 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
5054 * Skip if there is no shared message in there
5055 * we already checked this in diaspora::isReshare()
5056 * but better one more than one less...
5058 if (($body == $attributes) || empty($attributes)) {
5062 // build the fake reshared item
5063 $reshared_item = $item;
5066 preg_match("/author='(.*?)'/ism", $attributes, $matches);
5067 if (!empty($matches[1])) {
5068 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
5071 preg_match('/author="(.*?)"/ism', $attributes, $matches);
5072 if (!empty($matches[1])) {
5073 $author = $matches[1];
5077 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
5078 if (!empty($matches[1])) {
5079 $profile = $matches[1];
5082 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
5083 if (!empty($matches[1])) {
5084 $profile = $matches[1];
5088 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
5089 if (!empty($matches[1])) {
5090 $avatar = $matches[1];
5093 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
5094 if (!empty($matches[1])) {
5095 $avatar = $matches[1];
5099 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5100 if (!empty($matches[1])) {
5101 $link = $matches[1];
5104 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5105 if (!empty($matches[1])) {
5106 $link = $matches[1];
5110 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5111 if (!empty($matches[1])) {
5112 $posted = $matches[1];
5115 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5116 if (!empty($matches[1])) {
5117 $posted = $matches[1];
5120 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5122 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5126 $reshared_item["body"] = $shared_body;
5127 $reshared_item["author-id"] = Contact::getIdForURL($profile, 0, true);
5128 $reshared_item["author-name"] = $author;
5129 $reshared_item["author-link"] = $profile;
5130 $reshared_item["author-avatar"] = $avatar;
5131 $reshared_item["plink"] = $link;
5132 $reshared_item["created"] = $posted;
5133 $reshared_item["edited"] = $posted;
5135 return $reshared_item;
5140 * @param string $profile
5142 * @return string|false
5143 * @throws InternalServerErrorException
5144 * @todo remove trailing junk from profile url
5145 * @todo pump.io check has to check the website
5147 function api_get_nick($profile)
5152 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5153 DBA::escape(Strings::normaliseLink($profile))
5156 if (DBA::isResult($r)) {
5157 $nick = $r[0]["nick"];
5162 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5163 DBA::escape(Strings::normaliseLink($profile))
5166 if (DBA::isResult($r)) {
5167 $nick = $r[0]["nick"];
5172 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5173 if ($friendica != $profile) {
5179 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5180 if ($diaspora != $profile) {
5186 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5187 if ($twitter != $profile) {
5194 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5195 if ($StatusnetHost != $profile) {
5196 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5197 if ($StatusnetUser != $profile) {
5198 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5199 $user = json_decode($UserData);
5201 $nick = $user->screen_name;
5207 // To-Do: look at the page if its really a pumpio site
5208 //if (!$nick == "") {
5209 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5210 // if ($pumpio != $profile)
5212 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5225 * @param array $item
5230 function api_in_reply_to($item)
5234 $in_reply_to['status_id'] = null;
5235 $in_reply_to['user_id'] = null;
5236 $in_reply_to['status_id_str'] = null;
5237 $in_reply_to['user_id_str'] = null;
5238 $in_reply_to['screen_name'] = null;
5240 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5241 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5242 if (DBA::isResult($parent)) {
5243 $in_reply_to['status_id'] = intval($parent['id']);
5245 $in_reply_to['status_id'] = intval($item['parent']);
5248 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5250 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5251 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5253 if (DBA::isResult($parent)) {
5254 if ($parent['author-nick'] == "") {
5255 $parent['author-nick'] = api_get_nick($parent['author-link']);
5258 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5259 $in_reply_to['user_id'] = intval($parent['author-id']);
5260 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5263 // There seems to be situation, where both fields are identical:
5264 // https://github.com/friendica/friendica/issues/1010
5265 // This is a bugfix for that.
5266 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5267 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']]);
5268 $in_reply_to['status_id'] = null;
5269 $in_reply_to['user_id'] = null;
5270 $in_reply_to['status_id_str'] = null;
5271 $in_reply_to['user_id_str'] = null;
5272 $in_reply_to['screen_name'] = null;
5276 return $in_reply_to;
5281 * @param string $text
5284 * @throws InternalServerErrorException
5286 function api_clean_plain_items($text)
5288 $include_entities = strtolower(defaults($_REQUEST, 'include_entities', "false"));
5290 $text = BBCode::cleanPictureLinks($text);
5291 $URLSearchString = "^\[\]";
5293 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5295 if ($include_entities == "true") {
5296 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5299 // Simplify "attachment" element
5300 $text = api_clean_attachments($text);
5306 * @brief Removes most sharing information for API text export
5308 * @param string $body The original body
5310 * @return string Cleaned body
5311 * @throws InternalServerErrorException
5313 function api_clean_attachments($body)
5315 $data = BBCode::getAttachmentData($body);
5322 if (isset($data["text"])) {
5323 $body = $data["text"];
5325 if (($body == "") && isset($data["title"])) {
5326 $body = $data["title"];
5328 if (isset($data["url"])) {
5329 $body .= "\n".$data["url"];
5331 $body .= $data["after"];
5338 * @param array $contacts
5342 function api_best_nickname(&$contacts)
5346 if (count($contacts) == 0) {
5350 foreach ($contacts as $contact) {
5351 if ($contact["network"] == "") {
5352 $contact["network"] = "dfrn";
5353 $best_contact = [$contact];
5357 if (sizeof($best_contact) == 0) {
5358 foreach ($contacts as $contact) {
5359 if ($contact["network"] == "dfrn") {
5360 $best_contact = [$contact];
5365 if (sizeof($best_contact) == 0) {
5366 foreach ($contacts as $contact) {
5367 if ($contact["network"] == "dspr") {
5368 $best_contact = [$contact];
5373 if (sizeof($best_contact) == 0) {
5374 foreach ($contacts as $contact) {
5375 if ($contact["network"] == "stat") {
5376 $best_contact = [$contact];
5381 if (sizeof($best_contact) == 0) {
5382 foreach ($contacts as $contact) {
5383 if ($contact["network"] == "pump") {
5384 $best_contact = [$contact];
5389 if (sizeof($best_contact) == 0) {
5390 foreach ($contacts as $contact) {
5391 if ($contact["network"] == "twit") {
5392 $best_contact = [$contact];
5397 if (sizeof($best_contact) == 1) {
5398 $contacts = $best_contact;
5400 $contacts = [$contacts[0]];
5405 * Return all or a specified group of the user with the containing contacts.
5407 * @param string $type Return type (atom, rss, xml, json)
5409 * @return array|string
5410 * @throws BadRequestException
5411 * @throws ForbiddenException
5412 * @throws ImagickException
5413 * @throws InternalServerErrorException
5414 * @throws UnauthorizedException
5416 function api_friendica_group_show($type)
5420 if (api_user() === false) {
5421 throw new ForbiddenException();
5425 $user_info = api_get_user($a);
5426 $gid = defaults($_REQUEST, 'gid', 0);
5427 $uid = $user_info['uid'];
5429 // get data of the specified group id or all groups if not specified
5432 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5436 // error message if specified gid is not in database
5437 if (!DBA::isResult($r)) {
5438 throw new BadRequestException("gid not available");
5442 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5447 // loop through all groups and retrieve all members for adding data in the user array
5449 foreach ($r as $rr) {
5450 $members = Contact::getByGroupId($rr['id']);
5453 if ($type == "xml") {
5454 $user_element = "users";
5456 foreach ($members as $member) {
5457 $user = api_get_user($a, $member['nurl']);
5458 $users[$k++.":user"] = $user;
5461 $user_element = "user";
5462 foreach ($members as $member) {
5463 $user = api_get_user($a, $member['nurl']);
5467 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5469 return api_format_data("groups", $type, ['group' => $grps]);
5471 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5475 * Delete the specified group of the user.
5477 * @param string $type Return type (atom, rss, xml, json)
5479 * @return array|string
5480 * @throws BadRequestException
5481 * @throws ForbiddenException
5482 * @throws ImagickException
5483 * @throws InternalServerErrorException
5484 * @throws UnauthorizedException
5486 function api_friendica_group_delete($type)
5490 if (api_user() === false) {
5491 throw new ForbiddenException();
5495 $user_info = api_get_user($a);
5496 $gid = defaults($_REQUEST, 'gid', 0);
5497 $name = defaults($_REQUEST, 'name', "");
5498 $uid = $user_info['uid'];
5500 // error if no gid specified
5501 if ($gid == 0 || $name == "") {
5502 throw new BadRequestException('gid or name not specified');
5505 // get data of the specified group id
5507 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5511 // error message if specified gid is not in database
5512 if (!DBA::isResult($r)) {
5513 throw new BadRequestException('gid not available');
5516 // get data of the specified group id and group name
5518 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5523 // error message if specified gid is not in database
5524 if (!DBA::isResult($rname)) {
5525 throw new BadRequestException('wrong group name');
5529 $ret = Group::removeByName($uid, $name);
5532 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5533 return api_format_data("group_delete", $type, ['result' => $success]);
5535 throw new BadRequestException('other API error');
5538 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5543 * @param string $type Return type (atom, rss, xml, json)
5545 * @return array|string
5546 * @throws BadRequestException
5547 * @throws ForbiddenException
5548 * @throws ImagickException
5549 * @throws InternalServerErrorException
5550 * @throws UnauthorizedException
5551 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5553 function api_lists_destroy($type)
5557 if (api_user() === false) {
5558 throw new ForbiddenException();
5562 $user_info = api_get_user($a);
5563 $gid = defaults($_REQUEST, 'list_id', 0);
5564 $uid = $user_info['uid'];
5566 // error if no gid specified
5568 throw new BadRequestException('gid not specified');
5571 // get data of the specified group id
5572 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5573 // error message if specified gid is not in database
5575 throw new BadRequestException('gid not available');
5578 if (Group::remove($gid)) {
5580 'name' => $group['name'],
5581 'id' => intval($gid),
5582 'id_str' => (string) $gid,
5583 'user' => $user_info
5586 return api_format_data("lists", $type, ['lists' => $list]);
5589 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5592 * Add a new group to the database.
5594 * @param string $name Group name
5595 * @param int $uid User ID
5596 * @param array $users List of users to add to the group
5599 * @throws BadRequestException
5601 function group_create($name, $uid, $users = [])
5603 // error if no name specified
5605 throw new BadRequestException('group name not specified');
5608 // get data of the specified group name
5610 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5614 // error message if specified group name already exists
5615 if (DBA::isResult($rname)) {
5616 throw new BadRequestException('group name already exists');
5619 // check if specified group name is a deleted group
5621 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5625 // error message if specified group name already exists
5626 if (DBA::isResult($rname)) {
5627 $reactivate_group = true;
5631 $ret = Group::create($uid, $name);
5633 $gid = Group::getIdByName($uid, $name);
5635 throw new BadRequestException('other API error');
5639 $erroraddinguser = false;
5641 foreach ($users as $user) {
5642 $cid = $user['cid'];
5643 // check if user really exists as contact
5645 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5649 if (count($contact)) {
5650 Group::addMember($gid, $cid);
5652 $erroraddinguser = true;
5653 $errorusers[] = $cid;
5657 // return success message incl. missing users in array
5658 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5660 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5664 * Create the specified group with the posted array of contacts.
5666 * @param string $type Return type (atom, rss, xml, json)
5668 * @return array|string
5669 * @throws BadRequestException
5670 * @throws ForbiddenException
5671 * @throws ImagickException
5672 * @throws InternalServerErrorException
5673 * @throws UnauthorizedException
5675 function api_friendica_group_create($type)
5679 if (api_user() === false) {
5680 throw new ForbiddenException();
5684 $user_info = api_get_user($a);
5685 $name = defaults($_REQUEST, 'name', "");
5686 $uid = $user_info['uid'];
5687 $json = json_decode($_POST['json'], true);
5688 $users = $json['user'];
5690 $success = group_create($name, $uid, $users);
5692 return api_format_data("group_create", $type, ['result' => $success]);
5694 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5697 * Create a new group.
5699 * @param string $type Return type (atom, rss, xml, json)
5701 * @return array|string
5702 * @throws BadRequestException
5703 * @throws ForbiddenException
5704 * @throws ImagickException
5705 * @throws InternalServerErrorException
5706 * @throws UnauthorizedException
5707 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5709 function api_lists_create($type)
5713 if (api_user() === false) {
5714 throw new ForbiddenException();
5718 $user_info = api_get_user($a);
5719 $name = defaults($_REQUEST, 'name', "");
5720 $uid = $user_info['uid'];
5722 $success = group_create($name, $uid);
5723 if ($success['success']) {
5725 'name' => $success['name'],
5726 'id' => intval($success['gid']),
5727 'id_str' => (string) $success['gid'],
5728 'user' => $user_info
5731 return api_format_data("lists", $type, ['lists'=>$grp]);
5734 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5737 * Update the specified group with the posted array of contacts.
5739 * @param string $type Return type (atom, rss, xml, json)
5741 * @return array|string
5742 * @throws BadRequestException
5743 * @throws ForbiddenException
5744 * @throws ImagickException
5745 * @throws InternalServerErrorException
5746 * @throws UnauthorizedException
5748 function api_friendica_group_update($type)
5752 if (api_user() === false) {
5753 throw new ForbiddenException();
5757 $user_info = api_get_user($a);
5758 $uid = $user_info['uid'];
5759 $gid = defaults($_REQUEST, 'gid', 0);
5760 $name = defaults($_REQUEST, 'name', "");
5761 $json = json_decode($_POST['json'], true);
5762 $users = $json['user'];
5764 // error if no name specified
5766 throw new BadRequestException('group name not specified');
5769 // error if no gid specified
5771 throw new BadRequestException('gid not specified');
5775 $members = Contact::getByGroupId($gid);
5776 foreach ($members as $member) {
5777 $cid = $member['id'];
5778 foreach ($users as $user) {
5779 $found = ($user['cid'] == $cid ? true : false);
5781 if (!isset($found) || !$found) {
5782 Group::removeMemberByName($uid, $name, $cid);
5787 $erroraddinguser = false;
5789 foreach ($users as $user) {
5790 $cid = $user['cid'];
5791 // check if user really exists as contact
5793 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5798 if (count($contact)) {
5799 Group::addMember($gid, $cid);
5801 $erroraddinguser = true;
5802 $errorusers[] = $cid;
5806 // return success message incl. missing users in array
5807 $status = ($erroraddinguser ? "missing user" : "ok");
5808 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5809 return api_format_data("group_update", $type, ['result' => $success]);
5812 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5815 * Update information about a group.
5817 * @param string $type Return type (atom, rss, xml, json)
5819 * @return array|string
5820 * @throws BadRequestException
5821 * @throws ForbiddenException
5822 * @throws ImagickException
5823 * @throws InternalServerErrorException
5824 * @throws UnauthorizedException
5825 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5827 function api_lists_update($type)
5831 if (api_user() === false) {
5832 throw new ForbiddenException();
5836 $user_info = api_get_user($a);
5837 $gid = defaults($_REQUEST, 'list_id', 0);
5838 $name = defaults($_REQUEST, 'name', "");
5839 $uid = $user_info['uid'];
5841 // error if no gid specified
5843 throw new BadRequestException('gid not specified');
5846 // get data of the specified group id
5847 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5848 // error message if specified gid is not in database
5850 throw new BadRequestException('gid not available');
5853 if (Group::update($gid, $name)) {
5856 'id' => intval($gid),
5857 'id_str' => (string) $gid,
5858 'user' => $user_info
5861 return api_format_data("lists", $type, ['lists' => $list]);
5865 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5869 * @param string $type Return type (atom, rss, xml, json)
5871 * @return array|string
5872 * @throws BadRequestException
5873 * @throws ForbiddenException
5874 * @throws ImagickException
5875 * @throws InternalServerErrorException
5877 function api_friendica_activity($type)
5881 if (api_user() === false) {
5882 throw new ForbiddenException();
5884 $verb = strtolower($a->argv[3]);
5885 $verb = preg_replace("|\..*$|", "", $verb);
5887 $id = defaults($_REQUEST, 'id', 0);
5889 $res = Item::performLike($id, $verb);
5892 if ($type == "xml") {
5897 return api_format_data('ok', $type, ['ok' => $ok]);
5899 throw new BadRequestException('Error adding activity');
5903 /// @TODO move to top of file or somewhere better
5904 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5905 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5906 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5907 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5908 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5909 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5910 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5911 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5912 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5913 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5916 * @brief Returns notifications
5918 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5919 * @return string|array
5920 * @throws BadRequestException
5921 * @throws ForbiddenException
5922 * @throws InternalServerErrorException
5924 function api_friendica_notification($type)
5928 if (api_user() === false) {
5929 throw new ForbiddenException();
5932 throw new BadRequestException("Invalid argument count");
5934 $nm = new NotificationsManager();
5936 $notes = $nm->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
5938 if ($type == "xml") {
5940 if (!empty($notes)) {
5941 foreach ($notes as $note) {
5942 $xmlnotes[] = ["@attributes" => $note];
5948 return api_format_data("notes", $type, ['note' => $notes]);
5952 * POST request with 'id' param as notification id
5954 * @brief Set notification as seen and returns associated item (if possible)
5956 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5957 * @return string|array
5958 * @throws BadRequestException
5959 * @throws ForbiddenException
5960 * @throws ImagickException
5961 * @throws InternalServerErrorException
5962 * @throws UnauthorizedException
5964 function api_friendica_notification_seen($type)
5967 $user_info = api_get_user($a);
5969 if (api_user() === false || $user_info === false) {
5970 throw new ForbiddenException();
5973 throw new BadRequestException("Invalid argument count");
5976 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5978 $nm = new NotificationsManager();
5979 $note = $nm->getByID($id);
5980 if (is_null($note)) {
5981 throw new BadRequestException("Invalid argument");
5984 $nm->setSeen($note);
5985 if ($note['otype']=='item') {
5986 // would be really better with an ItemsManager and $im->getByID() :-P
5987 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5988 if (DBA::isResult($item)) {
5989 // we found the item, return it to the user
5990 $ret = api_format_items([$item], $user_info, false, $type);
5991 $data = ['status' => $ret];
5992 return api_format_data("status", $type, $data);
5994 // the item can't be found, but we set the note as seen, so we count this as a success
5996 return api_format_data('result', $type, ['result' => "success"]);
5999 /// @TODO move to top of file or somewhere better
6000 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
6001 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
6004 * @brief update a direct_message to seen state
6006 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6007 * @return string|array (success result=ok, error result=error with error message)
6008 * @throws BadRequestException
6009 * @throws ForbiddenException
6010 * @throws ImagickException
6011 * @throws InternalServerErrorException
6012 * @throws UnauthorizedException
6014 function api_friendica_direct_messages_setseen($type)
6017 if (api_user() === false) {
6018 throw new ForbiddenException();
6022 $user_info = api_get_user($a);
6023 $uid = $user_info['uid'];
6024 $id = defaults($_REQUEST, 'id', 0);
6026 // return error if id is zero
6028 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6029 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6032 // error message if specified id is not in database
6033 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6034 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6035 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6038 // update seen indicator
6039 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6043 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6044 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6046 $answer = ['result' => 'error', 'message' => 'unknown error'];
6047 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6051 /// @TODO move to top of file or somewhere better
6052 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6055 * @brief search for direct_messages containing a searchstring through api
6057 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6058 * @param string $box
6059 * @return string|array (success: success=true if found and search_result contains found messages,
6060 * success=false if nothing was found, search_result='nothing found',
6061 * error: result=error with error message)
6062 * @throws BadRequestException
6063 * @throws ForbiddenException
6064 * @throws ImagickException
6065 * @throws InternalServerErrorException
6066 * @throws UnauthorizedException
6068 function api_friendica_direct_messages_search($type, $box = "")
6072 if (api_user() === false) {
6073 throw new ForbiddenException();
6077 $user_info = api_get_user($a);
6078 $searchstring = defaults($_REQUEST, 'searchstring', "");
6079 $uid = $user_info['uid'];
6081 // error if no searchstring specified
6082 if ($searchstring == "") {
6083 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6084 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6087 // get data for the specified searchstring
6089 "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",
6091 DBA::escape('%'.$searchstring.'%')
6094 $profile_url = $user_info["url"];
6096 // message if nothing was found
6097 if (!DBA::isResult($r)) {
6098 $success = ['success' => false, 'search_results' => 'problem with query'];
6099 } elseif (count($r) == 0) {
6100 $success = ['success' => false, 'search_results' => 'nothing found'];
6103 foreach ($r as $item) {
6104 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6105 $recipient = $user_info;
6106 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6107 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6108 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6109 $sender = $user_info;
6112 if (isset($recipient) && isset($sender)) {
6113 $ret[] = api_format_messages($item, $recipient, $sender);
6116 $success = ['success' => true, 'search_results' => $ret];
6119 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6122 /// @TODO move to top of file or somewhere better
6123 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6126 * @brief return data of all the profiles a user has to the client
6128 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6129 * @return string|array
6130 * @throws BadRequestException
6131 * @throws ForbiddenException
6132 * @throws ImagickException
6133 * @throws InternalServerErrorException
6134 * @throws UnauthorizedException
6136 function api_friendica_profile_show($type)
6140 if (api_user() === false) {
6141 throw new ForbiddenException();
6145 $profile_id = defaults($_REQUEST, 'profile_id', 0);
6147 // retrieve general information about profiles for user
6148 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6149 $directory = Config::get('system', 'directory');
6151 // get data of the specified profile id or all profiles of the user if not specified
6152 if ($profile_id != 0) {
6154 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
6159 // error message if specified gid is not in database
6160 if (!DBA::isResult($r)) {
6161 throw new BadRequestException("profile_id not available");
6165 "SELECT * FROM `profile` WHERE `uid` = %d",
6169 // loop through all returned profiles and retrieve data and users
6172 foreach ($r as $rr) {
6173 $profile = api_format_items_profiles($rr);
6175 // select all users from contact table, loop and prepare standard return for user data
6178 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
6183 foreach ($nurls as $nurl) {
6184 $user = api_get_user($a, $nurl['nurl']);
6185 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6187 $profile['users'] = $users;
6189 // add prepared profile data to array for final return
6190 if ($type == "xml") {
6191 $profiles[$k++ . ":profile"] = $profile;
6193 $profiles[] = $profile;
6197 // return settings, authenticated user and profiles data
6198 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6200 $result = ['multi_profiles' => $multi_profiles ? true : false,
6201 'global_dir' => $directory,
6202 'friendica_owner' => api_get_user($a, $self['nurl']),
6203 'profiles' => $profiles];
6204 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6206 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6209 * Returns a list of saved searches.
6211 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6213 * @param string $type Return format: json or xml
6215 * @return string|array
6218 function api_saved_searches_list($type)
6220 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6223 while ($term = $terms->fetch()) {
6225 'created_at' => api_date(time()),
6226 'id' => intval($term['id']),
6227 'id_str' => $term['id'],
6228 'name' => $term['term'],
6230 'query' => $term['term']
6236 return api_format_data("terms", $type, ['terms' => $result]);
6239 /// @TODO move to top of file or somewhere better
6240 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6243 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6245 * @brief Number of comments
6247 * @param object $data [Status, Status]
6251 function bindComments(&$data)
6253 if (count($data) == 0) {
6259 foreach ($data as $item) {
6260 $ids[] = $item['id'];
6263 $idStr = DBA::escape(implode(', ', $ids));
6264 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6265 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6266 $itemsData = DBA::toArray($items);
6268 foreach ($itemsData as $item) {
6269 $comments[$item['parent']] = $item['comments'];
6272 foreach ($data as $idx => $item) {
6274 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6279 @TODO Maybe open to implement?
6281 [pagename] => api/1.1/statuses/lookup.json
6282 [id] => 605138389168451584
6283 [include_cards] => true
6284 [cards_platform] => Android-12
6285 [include_entities] => true
6286 [include_my_retweet] => 1
6288 [include_reply_count] => true
6289 [include_descendent_reply_count] => true
6293 Not implemented by now:
6294 statuses/retweets_of_me
6299 account/update_location
6300 account/update_profile_background_image
6303 friendica/profile/update
6304 friendica/profile/create
6305 friendica/profile/delete
6307 Not implemented in status.net:
6308 statuses/retweeted_to_me
6309 statuses/retweeted_by_me
6310 direct_messages/destroy
6312 account/update_delivery_device
6313 notifications/follow