3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\Content\ContactSelector;
11 use Friendica\Content\Feature;
12 use Friendica\Content\Text\BBCode;
13 use Friendica\Content\Text\HTML;
14 use Friendica\Core\Addon;
15 use Friendica\Core\Config;
16 use Friendica\Core\L10n;
17 use Friendica\Core\NotificationsManager;
18 use Friendica\Core\PConfig;
19 use Friendica\Core\System;
20 use Friendica\Core\Worker;
21 use Friendica\Database\DBM;
22 use Friendica\Model\Contact;
23 use Friendica\Model\Group;
24 use Friendica\Model\Item;
25 use Friendica\Model\Mail;
26 use Friendica\Model\Photo;
27 use Friendica\Model\User;
28 use Friendica\Network\FKOAuth1;
29 use Friendica\Network\HTTPException;
30 use Friendica\Network\HTTPException\BadRequestException;
31 use Friendica\Network\HTTPException\ForbiddenException;
32 use Friendica\Network\HTTPException\InternalServerErrorException;
33 use Friendica\Network\HTTPException\MethodNotAllowedException;
34 use Friendica\Network\HTTPException\NotFoundException;
35 use Friendica\Network\HTTPException\NotImplementedException;
36 use Friendica\Network\HTTPException\TooManyRequestsException;
37 use Friendica\Network\HTTPException\UnauthorizedException;
38 use Friendica\Object\Image;
39 use Friendica\Protocol\Diaspora;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Network;
42 use Friendica\Util\XML;
44 require_once 'include/conversation.php';
45 require_once 'mod/share.php';
46 require_once 'mod/item.php';
47 require_once 'include/security.php';
48 require_once 'mod/wall_upload.php';
49 require_once 'mod/proxy.php';
51 define('API_METHOD_ANY', '*');
52 define('API_METHOD_GET', 'GET');
53 define('API_METHOD_POST', 'POST,PUT');
54 define('API_METHOD_DELETE', 'POST,DELETE');
60 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
61 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
62 * into a page, and visitors will post something without noticing it).
64 * @brief Auth API user
68 if (x($_SESSION, 'allow_api')) {
76 * Clients can send 'source' parameter to be show in post metadata
77 * as "sent via <source>".
78 * Some clients doesn't send a source param, we support ones we know
81 * @brief Get source name from API client
84 * Client source name, default to "api" if unset/unknown
88 if (requestdata('source')) {
89 return requestdata('source');
92 // Support for known clients that doesn't send a source name
93 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
94 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
98 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
101 logger("Empty user-agent", LOGGER_DEBUG);
107 * @brief Format date for API
109 * @param string $str Source date, as UTC
110 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
112 function api_date($str)
114 // Wed May 23 06:01:13 +0000 2007
115 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
119 * Register a function to be the endpoint for defined API path.
121 * @brief Register API endpoint
123 * @param string $path API URL path, relative to System::baseUrl()
124 * @param string $func Function name to call on path request
125 * @param bool $auth API need logged user
126 * @param string $method HTTP method reqiured to call this endpoint.
127 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
128 * Default to API_METHOD_ANY
130 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
140 // Workaround for hotot
141 $path = str_replace("api/", "api/1.1/", $path);
151 * Log in user via OAuth1 or Simple HTTP Auth.
152 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
154 * @brief Login API user
156 * @param object $a App
157 * @hook 'authenticate'
159 * 'username' => username from login form
160 * 'password' => password from login form
161 * 'authenticated' => return status,
162 * 'user_record' => return authenticated user record
164 * array $user logged user record
166 function api_login(App $a)
168 $oauth1 = new FKOAuth1();
171 list($consumer, $token) = $oauth1->verify_request(OAuthRequest::from_request());
172 if (!is_null($token)) {
173 $oauth1->loginUser($token->uid);
174 Addon::callHooks('logged_in', $a->user);
177 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
178 var_dump($consumer, $token);
180 } catch (Exception $e) {
184 // workaround for HTTP-auth in CGI mode
185 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
186 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
187 if (strlen($userpass)) {
188 list($name, $password) = explode(':', $userpass);
189 $_SERVER['PHP_AUTH_USER'] = $name;
190 $_SERVER['PHP_AUTH_PW'] = $password;
194 if (!x($_SERVER, 'PHP_AUTH_USER')) {
195 logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
196 header('WWW-Authenticate: Basic realm="Friendica"');
197 throw new UnauthorizedException("This API requires login");
200 $user = defaults($_SERVER, 'PHP_AUTH_USER', '');
201 $password = defaults($_SERVER, 'PHP_AUTH_PW', '');
203 // allow "user@server" login (but ignore 'server' part)
204 $at = strstr($user, "@", true);
209 // next code from mod/auth.php. needs better solution
213 'username' => trim($user),
214 'password' => trim($password),
215 'authenticated' => 0,
216 'user_record' => null,
220 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
221 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
222 * and later addons should not interfere with an earlier one that succeeded.
224 Addon::callHooks('authenticate', $addon_auth);
226 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
227 $record = $addon_auth['user_record'];
229 $user_id = User::authenticate(trim($user), trim($password));
230 if ($user_id !== false) {
231 $record = dba::selectFirst('user', [], ['uid' => $user_id]);
235 if (!DBM::is_result($record)) {
236 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
237 header('WWW-Authenticate: Basic realm="Friendica"');
238 //header('HTTP/1.0 401 Unauthorized');
239 //die('This api requires login');
240 throw new UnauthorizedException("This API requires login");
243 authenticate_success($record);
245 $_SESSION["allow_api"] = true;
247 Addon::callHooks('logged_in', $a->user);
251 * API endpoints can define which HTTP method to accept when called.
252 * This function check the current HTTP method agains endpoint
255 * @brief Check HTTP method of called API
257 * @param string $method Required methods, uppercase, separated by comma
260 function api_check_method($method)
262 if ($method == "*") {
265 return (stripos($method, defaults($_SERVER, 'REQUEST_METHOD', 'GET')) !== false);
269 * Authenticate user, call registered API function, set HTTP headers
271 * @brief Main API entry point
273 * @param object $a App
274 * @return string|array API call result
276 function api_call(App $a)
278 global $API, $called_api;
281 if (strpos($a->query_string, ".xml") > 0) {
284 if (strpos($a->query_string, ".json") > 0) {
287 if (strpos($a->query_string, ".rss") > 0) {
290 if (strpos($a->query_string, ".atom") > 0) {
295 foreach ($API as $p => $info) {
296 if (strpos($a->query_string, $p) === 0) {
297 if (!api_check_method($info['method'])) {
298 throw new MethodNotAllowedException();
301 $called_api = explode("/", $p);
302 //unset($_SERVER['PHP_AUTH_USER']);
304 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
305 if (!empty($info['auth']) && api_user() === false) {
309 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
310 logger('API parameters: ' . print_r($_REQUEST, true));
312 $stamp = microtime(true);
313 $return = call_user_func($info['func'], $type);
314 $duration = (float) (microtime(true) - $stamp);
315 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
317 if (Config::get("system", "profiler")) {
318 $duration = microtime(true)-$a->performance["start"];
320 /// @TODO round() really everywhere?
322 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
323 "Database: %s/%s, Cache %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
324 round($a->performance["database"] - $a->performance["database_write"], 3),
325 round($a->performance["database_write"], 3),
326 round($a->performance["cache"], 3),
327 round($a->performance["cache_write"], 3),
328 round($a->performance["network"], 2),
329 round($a->performance["file"], 2),
330 round($duration - ($a->performance["database"]
331 + $a->performance["cache"] + $a->performance["cache_write"]
332 + $a->performance["network"] + $a->performance["file"]), 2),
338 if (Config::get("rendertime", "callstack")) {
339 $o = "Database Read:\n";
340 foreach ($a->callstack["database"] as $func => $time) {
341 $time = round($time, 3);
343 $o .= $func . ": " . $time . "\n";
346 $o .= "\nDatabase Write:\n";
347 foreach ($a->callstack["database_write"] as $func => $time) {
348 $time = round($time, 3);
350 $o .= $func . ": " . $time . "\n";
354 $o = "Cache Read:\n";
355 foreach ($a->callstack["cache"] as $func => $time) {
356 $time = round($time, 3);
358 $o .= $func . ": " . $time . "\n";
361 $o .= "\nCache Write:\n";
362 foreach ($a->callstack["cache_write"] as $func => $time) {
363 $time = round($time, 3);
365 $o .= $func . ": " . $time . "\n";
369 $o .= "\nNetwork:\n";
370 foreach ($a->callstack["network"] as $func => $time) {
371 $time = round($time, 3);
373 $o .= $func . ": " . $time . "\n";
376 logger($o, LOGGER_DEBUG);
380 if (false === $return) {
382 * api function returned false withour throw an
383 * exception. This should not happend, throw a 500
385 throw new InternalServerErrorException();
390 header("Content-Type: text/xml");
393 header("Content-Type: application/json");
394 $json = json_encode(end($return));
395 if (x($_GET, 'callback')) {
396 $json = $_GET['callback'] . "(" . $json . ")";
401 header("Content-Type: application/rss+xml");
402 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
405 header("Content-Type: application/atom+xml");
406 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
413 logger('API call not implemented: ' . $a->query_string);
414 throw new NotImplementedException();
415 } catch (HTTPException $e) {
416 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
417 return api_error($type, $e);
422 * @brief Format API error string
424 * @param string $type Return type (xml, json, rss, as)
425 * @param object $e HTTPException Error object
426 * @return string|array error message formatted as $type
428 function api_error($type, $e)
432 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
433 /// @TODO: https://dev.twitter.com/overview/api/response-codes
435 $error = ["error" => $error,
436 "code" => $e->httpcode . " " . $e->httpdesc,
437 "request" => $a->query_string];
439 $return = api_format_data('status', $type, ['status' => $error]);
443 header("Content-Type: text/xml");
446 header("Content-Type: application/json");
447 $return = json_encode($return);
450 header("Content-Type: application/rss+xml");
453 header("Content-Type: application/atom+xml");
461 * @brief Set values for RSS template
464 * @param array $arr Array to be passed to template
465 * @param array $user_info User info
467 * @todo find proper type-hints
469 function api_rss_extra(App $a, $arr, $user_info)
471 if (is_null($user_info)) {
472 $user_info = api_get_user($a);
475 $arr['$user'] = $user_info;
477 'alternate' => $user_info['url'],
478 'self' => System::baseUrl() . "/" . $a->query_string,
479 'base' => System::baseUrl(),
480 'updated' => api_date(null),
481 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
482 'language' => $user_info['language'],
483 'logo' => System::baseUrl() . "/images/friendica-32.png",
491 * @brief Unique contact to contact url.
493 * @param int $id Contact id
494 * @return bool|string
495 * Contact url or False if contact id is unknown
497 function api_unique_id_to_nurl($id)
499 $r = dba::selectFirst('contact', ['nurl'], ['id' => $id]);
501 if (DBM::is_result($r)) {
509 * @brief Get user info array.
511 * @param object $a App
512 * @param int|string $contact_id Contact ID or URL
514 function api_get_user(App $a, $contact_id = null)
522 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
524 // Searching for contact URL
525 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
526 $user = dbesc(normalise_link($contact_id));
528 $extra_query = "AND `contact`.`nurl` = '%s' ";
529 if (api_user() !== false) {
530 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
534 // Searching for contact id with uid = 0
535 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
536 $user = dbesc(api_unique_id_to_nurl(intval($contact_id)));
539 throw new BadRequestException("User ID ".$contact_id." not found.");
543 $extra_query = "AND `contact`.`nurl` = '%s' ";
544 if (api_user() !== false) {
545 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
549 if (is_null($user) && x($_GET, 'user_id')) {
550 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
553 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
557 $extra_query = "AND `contact`.`nurl` = '%s' ";
558 if (api_user() !== false) {
559 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
562 if (is_null($user) && x($_GET, 'screen_name')) {
563 $user = dbesc($_GET['screen_name']);
564 $extra_query = "AND `contact`.`nick` = '%s' ";
565 if (api_user() !== false) {
566 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
570 if (is_null($user) && x($_GET, 'profileurl')) {
571 $user = dbesc(normalise_link($_GET['profileurl']));
572 $extra_query = "AND `contact`.`nurl` = '%s' ";
573 if (api_user() !== false) {
574 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
578 // $called_api is the API path exploded on / and is expected to have at least 2 elements
579 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
580 $argid = count($called_api);
581 list($user, $null) = explode(".", $a->argv[$argid]);
582 if (is_numeric($user)) {
583 $user = dbesc(api_unique_id_to_nurl(intval($user)));
587 $extra_query = "AND `contact`.`nurl` = '%s' ";
588 if (api_user() !== false) {
589 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
593 $user = dbesc($user);
594 $extra_query = "AND `contact`.`nick` = '%s' ";
595 if (api_user() !== false) {
596 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
601 logger("api_get_user: user ".$user, LOGGER_DEBUG);
604 if (api_user() === false) {
608 $user = $_SESSION['uid'];
609 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
613 logger('api_user: ' . $extra_query . ', user: ' . $user);
617 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
623 // Selecting the id by priority, friendica first
624 if (is_array($uinfo)) {
625 api_best_nickname($uinfo);
628 // if the contact wasn't found, fetch it from the contacts with uid = 0
629 if (!DBM::is_result($uinfo)) {
633 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
636 if (DBM::is_result($r)) {
637 $network_name = ContactSelector::networkToName($r[0]['network'], $r[0]['url']);
639 // If no nick where given, extract it from the address
640 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
641 $r[0]['nick'] = api_get_nick($r[0]["url"]);
646 'id_str' => (string) $r[0]["id"],
647 'name' => $r[0]["name"],
648 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
649 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
650 'description' => $r[0]["about"],
651 'profile_image_url' => $r[0]["micro"],
652 'profile_image_url_https' => $r[0]["micro"],
653 'profile_image_url_profile_size' => $r[0]["thumb"],
654 'profile_image_url_large' => $r[0]["photo"],
655 'url' => $r[0]["url"],
656 'protected' => false,
657 'followers_count' => 0,
658 'friends_count' => 0,
660 'created_at' => api_date($r[0]["created"]),
661 'favourites_count' => 0,
663 'time_zone' => 'UTC',
664 'geo_enabled' => false,
666 'statuses_count' => 0,
668 'contributors_enabled' => false,
669 'is_translator' => false,
670 'is_translation_enabled' => false,
671 'following' => false,
672 'follow_request_sent' => false,
673 'statusnet_blocking' => false,
674 'notifications' => false,
675 'statusnet_profile_url' => $r[0]["url"],
677 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
678 'pid' => Contact::getIdForURL($r[0]["url"], 0, true),
680 'network' => $r[0]["network"],
685 throw new BadRequestException("User ".$url." not found.");
689 if ($uinfo[0]['self']) {
690 if ($uinfo[0]['network'] == "") {
691 $uinfo[0]['network'] = NETWORK_DFRN;
694 $usr = dba::selectFirst('user', ['default-location'], ['uid' => api_user()]);
695 $profile = dba::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
702 // Add a nick if it isn't present there
703 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
704 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
707 $network_name = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
709 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
711 if (!empty($profile['about'])) {
712 $description = $profile['about'];
714 $description = $uinfo[0]["about"];
717 if (!empty($usr['default-location'])) {
718 $location = $usr['default-location'];
719 } elseif (!empty($uinfo[0]["location"])) {
720 $location = $uinfo[0]["location"];
722 $location = $network_name;
726 'id' => intval($pcontact_id),
727 'id_str' => (string) intval($pcontact_id),
728 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
729 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
730 'location' => $location,
731 'description' => $description,
732 'profile_image_url' => $uinfo[0]['micro'],
733 'profile_image_url_https' => $uinfo[0]['micro'],
734 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
735 'profile_image_url_large' => $uinfo[0]["photo"],
736 'url' => $uinfo[0]['url'],
737 'protected' => false,
738 'followers_count' => intval($countfollowers),
739 'friends_count' => intval($countfriends),
741 'created_at' => api_date($uinfo[0]['created']),
742 'favourites_count' => intval($starred),
744 'time_zone' => 'UTC',
745 'geo_enabled' => false,
747 'statuses_count' => intval($countitems),
749 'contributors_enabled' => false,
750 'is_translator' => false,
751 'is_translation_enabled' => false,
752 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
753 'follow_request_sent' => false,
754 'statusnet_blocking' => false,
755 'notifications' => false,
757 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
758 'statusnet_profile_url' => $uinfo[0]['url'],
759 'uid' => intval($uinfo[0]['uid']),
760 'cid' => intval($uinfo[0]['cid']),
761 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
762 'self' => $uinfo[0]['self'],
763 'network' => $uinfo[0]['network'],
766 // If this is a local user and it uses Frio, we can get its color preferences.
768 $theme_info = dba::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
769 if ($theme_info['theme'] === 'frio') {
770 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
771 if ($schema && ($schema != '---')) {
772 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
773 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
774 require_once $schemefile;
777 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
778 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
779 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
781 if (empty($nav_bg)) {
784 if (empty($link_color)) {
785 $link_color = "#6fdbe8";
787 if (empty($bgcolor)) {
788 $bgcolor = "#ededed";
791 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
792 $ret['profile_link_color'] = str_replace('#', '', $link_color);
793 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
801 * @brief return api-formatted array for item's author and owner
803 * @param object $a App
804 * @param array $item item from db
805 * @return array(array:author, array:owner)
807 function api_item_get_user(App $a, $item)
809 $status_user = api_get_user($a, defaults($item, 'author-id', null));
811 $status_user["protected"] = defaults($item, 'private', 0);
813 if (defaults($item, 'thr-parent', '') == defaults($item, 'uri', '')) {
814 $owner_user = api_get_user($a, defaults($item, 'author-id', null));
816 $owner_user = $status_user;
819 return ([$status_user, $owner_user]);
823 * @brief walks recursively through an array with the possibility to change value and key
825 * @param array $array The array to walk through
826 * @param string $callback The callback function
828 * @return array the transformed array
830 function api_walk_recursive(array &$array, callable $callback)
834 foreach ($array as $k => $v) {
836 if ($callback($v, $k)) {
837 $new_array[$k] = api_walk_recursive($v, $callback);
840 if ($callback($v, $k)) {
851 * @brief Callback function to transform the array in an array that can be transformed in a XML file
853 * @param mixed $item Array item value
854 * @param string $key Array key
856 * @return boolean Should the array item be deleted?
858 function api_reformat_xml(&$item, &$key)
860 if (is_bool($item)) {
861 $item = ($item ? "true" : "false");
864 if (substr($key, 0, 10) == "statusnet_") {
865 $key = "statusnet:".substr($key, 10);
866 } elseif (substr($key, 0, 10) == "friendica_") {
867 $key = "friendica:".substr($key, 10);
869 /// @TODO old-lost code?
871 // $key = "default:".$key;
877 * @brief Creates the XML from a JSON style array
879 * @param array $data JSON style array
880 * @param string $root_element Name of the root element
882 * @return string The XML data
884 function api_create_xml(array $data, $root_element)
886 $childname = key($data);
887 $data2 = array_pop($data);
890 $namespaces = ["" => "http://api.twitter.com",
891 "statusnet" => "http://status.net/schema/api/1/",
892 "friendica" => "http://friendi.ca/schema/api/1/",
893 "georss" => "http://www.georss.org/georss"];
895 /// @todo Auto detection of needed namespaces
896 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
900 if (is_array($data2)) {
901 api_walk_recursive($data2, "api_reformat_xml");
908 foreach ($data2 as $item) {
909 $data4[$i++ . ":" . $childname] = $item;
915 $data3 = [$root_element => $data2];
917 $ret = XML::fromArray($data3, $xml, false, $namespaces);
922 * @brief Formats the data according to the data type
924 * @param string $root_element Name of the root element
925 * @param string $type Return type (atom, rss, xml, json)
926 * @param array $data JSON style array
928 * @return (string|array) XML data or JSON data
930 function api_format_data($root_element, $type, $data)
936 $ret = api_create_xml($data, $root_element);
952 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
953 * returns a 401 status code and an error message if not.
954 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
956 * @param string $type Return type (atom, rss, xml, json)
958 function api_account_verify_credentials($type)
963 if (api_user() === false) {
964 throw new ForbiddenException();
967 unset($_REQUEST["user_id"]);
968 unset($_GET["user_id"]);
970 unset($_REQUEST["screen_name"]);
971 unset($_GET["screen_name"]);
973 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
975 $user_info = api_get_user($a);
977 // "verified" isn't used here in the standard
978 unset($user_info["verified"]);
980 // - Adding last status
982 $user_info["status"] = api_status_show("raw");
983 if (!count($user_info["status"])) {
984 unset($user_info["status"]);
986 unset($user_info["status"]["user"]);
990 // "uid" and "self" are only needed for some internal stuff, so remove it from here
991 unset($user_info["uid"]);
992 unset($user_info["self"]);
994 return api_format_data("user", $type, ['user' => $user_info]);
997 /// @TODO move to top of file or somewhere better
998 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1001 * Get data from $_POST or $_GET
1005 function requestdata($k)
1007 if (x($_POST, $k)) {
1017 * Deprecated function to upload media.
1019 * @param string $type Return type (atom, rss, xml, json)
1021 * @return array|string
1023 function api_statuses_mediap($type)
1027 if (api_user() === false) {
1028 logger('api_statuses_update: no user');
1029 throw new ForbiddenException();
1031 $user_info = api_get_user($a);
1033 $_REQUEST['type'] = 'wall';
1034 $_REQUEST['profile_uid'] = api_user();
1035 $_REQUEST['api_source'] = true;
1036 $txt = requestdata('status');
1037 /// @TODO old-lost code?
1038 //$txt = urldecode(requestdata('status'));
1040 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1041 $txt = html2bb_video($txt);
1042 $config = HTMLPurifier_Config::createDefault();
1043 $config->set('Cache.DefinitionImpl', null);
1044 $purifier = new HTMLPurifier($config);
1045 $txt = $purifier->purify($txt);
1047 $txt = HTML::toBBCode($txt);
1049 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1051 $picture = wall_upload_post($a, false);
1053 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1054 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1057 // this should output the last post (the one we just posted).
1058 return api_status_show($type);
1061 /// @TODO move this to top of file or somewhere better!
1062 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1065 * Updates the user’s current status.
1067 * @param string $type Return type (atom, rss, xml, json)
1069 * @return array|string
1070 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1072 function api_statuses_update($type)
1077 if (api_user() === false) {
1078 logger('api_statuses_update: no user');
1079 throw new ForbiddenException();
1084 // convert $_POST array items to the form we use for web posts.
1085 if (requestdata('htmlstatus')) {
1086 $txt = requestdata('htmlstatus');
1087 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1088 $txt = html2bb_video($txt);
1090 $config = HTMLPurifier_Config::createDefault();
1091 $config->set('Cache.DefinitionImpl', null);
1093 $purifier = new HTMLPurifier($config);
1094 $txt = $purifier->purify($txt);
1096 $_REQUEST['body'] = HTML::toBBCode($txt);
1099 $_REQUEST['body'] = requestdata('status');
1102 $_REQUEST['title'] = requestdata('title');
1104 $parent = requestdata('in_reply_to_status_id');
1106 // Twidere sends "-1" if it is no reply ...
1107 if ($parent == -1) {
1111 if (ctype_digit($parent)) {
1112 $_REQUEST['parent'] = $parent;
1114 $_REQUEST['parent_uri'] = $parent;
1117 if (requestdata('lat') && requestdata('long')) {
1118 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1120 $_REQUEST['profile_uid'] = api_user();
1123 $_REQUEST['type'] = 'net-comment';
1125 // Check for throttling (maximum posts per day, week and month)
1126 $throttle_day = Config::get('system', 'throttle_limit_day');
1127 if ($throttle_day > 0) {
1128 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1130 $condition = ["`uid` = ? AND `wall` AND `created` > ? AND `id` = `parent`", api_user(), $datefrom];
1131 $posts_day = dba::count('item', $condition);
1133 if ($posts_day > $throttle_day) {
1134 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1135 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1136 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));
1140 $throttle_week = Config::get('system', 'throttle_limit_week');
1141 if ($throttle_week > 0) {
1142 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1144 $condition = ["`uid` = ? AND `wall` AND `created` > ? AND `id` = `parent`", api_user(), $datefrom];
1145 $posts_week = dba::count('item', $condition);
1147 if ($posts_week > $throttle_week) {
1148 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1149 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1150 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));
1154 $throttle_month = Config::get('system', 'throttle_limit_month');
1155 if ($throttle_month > 0) {
1156 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1158 $condition = ["`uid` = ? AND `wall` AND `created` > ? AND `id` = `parent`", api_user(), $datefrom];
1159 $posts_month = dba::count('item', $condition);
1161 if ($posts_month > $throttle_month) {
1162 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1163 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1164 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));
1168 $_REQUEST['type'] = 'wall';
1171 if (x($_FILES, 'media')) {
1172 // upload the image if we have one
1173 $picture = wall_upload_post($a, false);
1174 if (is_array($picture)) {
1175 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1179 // To-Do: Multiple IDs
1180 if (requestdata('media_ids')) {
1182 "SELECT `resource-id`, `scale`, `nickname`, `type` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1",
1183 intval(requestdata('media_ids')),
1186 if (DBM::is_result($r)) {
1187 $phototypes = Image::supportedTypes();
1188 $ext = $phototypes[$r[0]['type']];
1189 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1190 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1194 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1196 $_REQUEST['api_source'] = true;
1198 if (!x($_REQUEST, "source")) {
1199 $_REQUEST["source"] = api_source();
1202 // call out normal post function
1205 // this should output the last post (the one we just posted).
1206 return api_status_show($type);
1209 /// @TODO move to top of file or somewhere better
1210 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1211 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1214 * Uploads an image to Friendica.
1217 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1219 function api_media_upload()
1223 if (api_user() === false) {
1225 throw new ForbiddenException();
1230 if (!x($_FILES, 'media')) {
1232 throw new BadRequestException("No media.");
1235 $media = wall_upload_post($a, false);
1238 throw new InternalServerErrorException();
1242 $returndata["media_id"] = $media["id"];
1243 $returndata["media_id_string"] = (string)$media["id"];
1244 $returndata["size"] = $media["size"];
1245 $returndata["image"] = ["w" => $media["width"],
1246 "h" => $media["height"],
1247 "image_type" => $media["type"]];
1249 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1251 return ["media" => $returndata];
1254 /// @TODO move to top of file or somewhere better
1255 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1259 * @param string $type Return type (atom, rss, xml, json)
1261 * @return array|string
1263 function api_status_show($type)
1267 $user_info = api_get_user($a);
1269 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1271 if ($type == "raw") {
1272 $privacy_sql = "AND NOT `private`";
1277 // get last public wall message
1278 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1279 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1280 $lastwall = dba::selectFirst('item', [], $condition, ['order' => ['id' => true]]);
1282 if (DBM::is_result($lastwall)) {
1283 $in_reply_to = api_in_reply_to($lastwall);
1285 $converted = api_convert_item($lastwall);
1287 if ($type == "xml") {
1288 $geo = "georss:point";
1294 'created_at' => api_date($lastwall['created']),
1295 'id' => intval($lastwall['id']),
1296 'id_str' => (string) $lastwall['id'],
1297 'text' => $converted["text"],
1298 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1299 'truncated' => false,
1300 'in_reply_to_status_id' => $in_reply_to['status_id'],
1301 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1302 'in_reply_to_user_id' => $in_reply_to['user_id'],
1303 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1304 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1305 'user' => $user_info,
1307 'coordinates' => "",
1309 'contributors' => "",
1310 'is_quote_status' => false,
1311 'retweet_count' => 0,
1312 'favorite_count' => 0,
1313 'favorited' => $lastwall['starred'] ? true : false,
1314 'retweeted' => false,
1315 'possibly_sensitive' => false,
1317 'statusnet_html' => $converted["html"],
1318 'statusnet_conversation_id' => $lastwall['parent'],
1319 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1322 if (count($converted["attachments"]) > 0) {
1323 $status_info["attachments"] = $converted["attachments"];
1326 if (count($converted["entities"]) > 0) {
1327 $status_info["entities"] = $converted["entities"];
1330 if ($status_info["source"] == 'web') {
1331 $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $user_info['url']);
1332 } elseif (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $status_info["source"]) {
1333 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $user_info['url']).')');
1336 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1337 unset($status_info["user"]["uid"]);
1338 unset($status_info["user"]["self"]);
1340 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1342 if ($type == "raw") {
1343 return $status_info;
1346 return api_format_data("statuses", $type, ['status' => $status_info]);
1351 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1352 * The author's most recent status will be returned inline.
1354 * @param string $type Return type (atom, rss, xml, json)
1355 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1357 function api_users_show($type)
1361 $user_info = api_get_user($a);
1363 $condition = ['owner-id' => $user_info['pid'], 'uid' => api_user(),
1364 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'private' => false];
1365 $lastwall = dba::selectFirst('item', [], $condition, ['order' => ['id' => true]]);
1367 if (DBM::is_result($lastwall)) {
1368 $in_reply_to = api_in_reply_to($lastwall);
1370 $converted = api_convert_item($lastwall);
1372 if ($type == "xml") {
1373 $geo = "georss:point";
1378 $user_info['status'] = [
1379 'text' => $converted["text"],
1380 'truncated' => false,
1381 'created_at' => api_date($lastwall['created']),
1382 'in_reply_to_status_id' => $in_reply_to['status_id'],
1383 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1384 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1385 'id' => intval($lastwall['contact-id']),
1386 'id_str' => (string) $lastwall['contact-id'],
1387 'in_reply_to_user_id' => $in_reply_to['user_id'],
1388 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1389 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1391 'favorited' => $lastwall['starred'] ? true : false,
1392 'statusnet_html' => $converted["html"],
1393 'statusnet_conversation_id' => $lastwall['parent'],
1394 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1397 if (count($converted["attachments"]) > 0) {
1398 $user_info["status"]["attachments"] = $converted["attachments"];
1401 if (count($converted["entities"]) > 0) {
1402 $user_info["status"]["entities"] = $converted["entities"];
1405 if ($user_info["status"]["source"] == 'web') {
1406 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $user_info['url']);
1409 if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
1410 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $user_info['url']) . ')');
1414 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1415 unset($user_info["uid"]);
1416 unset($user_info["self"]);
1418 return api_format_data("user", $type, ['user' => $user_info]);
1421 /// @TODO move to top of file or somewhere better
1422 api_register_func('api/users/show', 'api_users_show');
1423 api_register_func('api/externalprofile/show', 'api_users_show');
1426 * Search a public user account.
1428 * @param string $type Return type (atom, rss, xml, json)
1430 * @return array|string
1431 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1433 function api_users_search($type)
1439 if (x($_GET, 'q')) {
1440 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1442 if (!DBM::is_result($r)) {
1443 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1446 if (DBM::is_result($r)) {
1448 foreach ($r as $user) {
1449 $user_info = api_get_user($a, $user["id"]);
1451 if ($type == "xml") {
1452 $userlist[$k++.":user"] = $user_info;
1454 $userlist[] = $user_info;
1457 $userlist = ["users" => $userlist];
1459 throw new BadRequestException("User ".$_GET["q"]." not found.");
1462 throw new BadRequestException("No user specified.");
1465 return api_format_data("users", $type, $userlist);
1468 /// @TODO move to top of file or somewhere better
1469 api_register_func('api/users/search', 'api_users_search');
1472 * Return user objects
1474 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1476 * @param string $type Return format: json or xml
1478 * @return array|string
1479 * @throws NotFoundException if the results are empty.
1481 function api_users_lookup($type)
1485 if (!empty($_REQUEST['user_id'])) {
1486 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1488 $users[] = api_get_user(get_app(), $id);
1493 if (empty($users)) {
1494 throw new NotFoundException;
1497 return api_format_data("users", $type, ['users' => $users]);
1500 /// @TODO move to top of file or somewhere better
1501 api_register_func('api/users/lookup', 'api_users_lookup', true);
1504 * Returns statuses that match a specified query.
1506 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1508 * @param string $type Return format: json, xml, atom, rss
1510 * @return array|string
1511 * @throws BadRequestException if the "q" parameter is missing.
1513 function api_search($type)
1516 $user_info = api_get_user($a);
1518 if (api_user() === false || $user_info === false) {
1519 throw new ForbiddenException();
1524 if (!x($_REQUEST, 'q')) {
1525 throw new BadRequestException("q parameter is required.");
1528 if (x($_REQUEST, 'rpp')) {
1529 $count = $_REQUEST['rpp'];
1530 } elseif (x($_REQUEST, 'count')) {
1531 $count = $_REQUEST['count'];
1536 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1537 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1538 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1540 $start = $page * $count;
1542 $condition = ["`gravity` IN (?, ?) AND `item`.`id` > ?
1543 AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1544 AND `item`.`body` LIKE CONCAT('%',?,'%')",
1545 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, api_user(), $_REQUEST['q']];
1548 $condition[0] .= " AND `item`.`id` <= ?";
1549 $condition[] = $max_id;
1552 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1553 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1555 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1557 return api_format_data("statuses", $type, $data);
1560 /// @TODO move to top of file or somewhere better
1561 api_register_func('api/search/tweets', 'api_search', true);
1562 api_register_func('api/search', 'api_search', true);
1565 * Returns the most recent statuses posted by the user and the users they follow.
1567 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1569 * @param string $type Return type (atom, rss, xml, json)
1571 * @todo Optional parameters
1572 * @todo Add reply info
1574 function api_statuses_home_timeline($type)
1577 $user_info = api_get_user($a);
1579 if (api_user() === false || $user_info === false) {
1580 throw new ForbiddenException();
1583 unset($_REQUEST["user_id"]);
1584 unset($_GET["user_id"]);
1586 unset($_REQUEST["screen_name"]);
1587 unset($_GET["screen_name"]);
1589 // get last network messages
1592 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1593 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1597 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1598 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1599 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1600 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1601 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1603 $start = $page * $count;
1605 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1606 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1609 $condition[0] .= " AND `item`.`id` <= ?";
1610 $condition[] = $max_id;
1612 if ($exclude_replies > 0) {
1613 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1615 if ($conversation_id > 0) {
1616 $condition[0] .= " AND `item`.`parent` = ?";
1617 $condition[] = $conversation_id;
1620 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1621 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1623 $items = Item::inArray($statuses);
1625 $ret = api_format_items($items, $user_info, false, $type);
1627 // Set all posts from the query above to seen
1629 foreach ($items as $item) {
1630 $idarray[] = intval($item["id"]);
1633 if (!empty($idarray)) {
1634 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1636 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1640 $data = ['status' => $ret];
1644 $data = api_rss_extra($a, $data, $user_info);
1648 return api_format_data("statuses", $type, $data);
1651 /// @TODO move to top of file or somewhere better
1652 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1653 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1656 * Returns the most recent statuses from public users.
1658 * @param string $type Return type (atom, rss, xml, json)
1660 * @return array|string
1662 function api_statuses_public_timeline($type)
1665 $user_info = api_get_user($a);
1667 if (api_user() === false || $user_info === false) {
1668 throw new ForbiddenException();
1671 // get last network messages
1674 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1675 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1679 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1680 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1681 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1682 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1683 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1685 $start = $page * $count;
1688 if ($exclude_replies && !$conversation_id) {
1689 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall`",
1690 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1693 $condition[0] .= " AND `thread`.`iid` <= ?";
1694 $condition[] = $max_id;
1697 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1698 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1700 $r = Item::inArray($statuses);
1702 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin`",
1703 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1706 $condition[0] .= " AND `item`.`id` <= ?";
1707 $condition[] = $max_id;
1709 if ($conversation_id > 0) {
1710 $condition[0] .= " AND `item`.`parent` = ?";
1711 $condition[] = $conversation_id;
1714 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1715 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1717 $r = Item::inArray($statuses);
1720 $ret = api_format_items($r, $user_info, false, $type);
1722 $data = ['status' => $ret];
1726 $data = api_rss_extra($a, $data, $user_info);
1730 return api_format_data("statuses", $type, $data);
1733 /// @TODO move to top of file or somewhere better
1734 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1737 * Returns the most recent statuses posted by users this node knows about.
1739 * @brief Returns the list of public federated posts this node knows about
1741 * @param string $type Return format: json, xml, atom, rss
1742 * @return array|string
1743 * @throws ForbiddenException
1745 function api_statuses_networkpublic_timeline($type)
1748 $user_info = api_get_user($a);
1750 if (api_user() === false || $user_info === false) {
1751 throw new ForbiddenException();
1754 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1755 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1758 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1759 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1763 $start = ($page - 1) * $count;
1765 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1766 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1769 $condition[0] .= " AND `thread`.`iid` <= ?";
1770 $condition[] = $max_id;
1773 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1774 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1776 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1778 $data = ['status' => $ret];
1782 $data = api_rss_extra($a, $data, $user_info);
1786 return api_format_data("statuses", $type, $data);
1789 /// @TODO move to top of file or somewhere better
1790 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1793 * Returns a single status.
1795 * @param string $type Return type (atom, rss, xml, json)
1797 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1799 function api_statuses_show($type)
1802 $user_info = api_get_user($a);
1804 if (api_user() === false || $user_info === false) {
1805 throw new ForbiddenException();
1809 $id = intval(defaults($a->argv, 3, 0));
1812 $id = intval(defaults($_REQUEST, 'id', 0));
1817 $id = intval(defaults($a->argv, 4, 0));
1820 logger('API: api_statuses_show: ' . $id);
1822 $conversation = !empty($_REQUEST['conversation']);
1824 // try to fetch the item for the local user - or the public item, if there is no local one
1825 $uri_item = dba::selectFirst('item', ['uri'], ['id' => $id]);
1826 if (!DBM::is_result($uri_item)) {
1827 throw new BadRequestException("There is no status with this id.");
1830 $item = dba::selectFirst('item', ['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1831 if (!DBM::is_result($item)) {
1832 throw new BadRequestException("There is no status with this id.");
1837 if ($conversation) {
1838 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1839 $params = ['order' => ['id' => true]];
1841 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1845 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1847 /// @TODO How about copying this to above methods which don't check $r ?
1848 if (!DBM::is_result($statuses)) {
1849 throw new BadRequestException("There is no status with this id.");
1852 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1854 if ($conversation) {
1855 $data = ['status' => $ret];
1856 return api_format_data("statuses", $type, $data);
1858 $data = ['status' => $ret[0]];
1859 return api_format_data("status", $type, $data);
1863 /// @TODO move to top of file or somewhere better
1864 api_register_func('api/statuses/show', 'api_statuses_show', true);
1868 * @param string $type Return type (atom, rss, xml, json)
1870 * @todo nothing to say?
1872 function api_conversation_show($type)
1875 $user_info = api_get_user($a);
1877 if (api_user() === false || $user_info === false) {
1878 throw new ForbiddenException();
1882 $id = intval(defaults($a->argv , 3 , 0));
1883 $since_id = intval(defaults($_REQUEST, 'since_id', 0));
1884 $max_id = intval(defaults($_REQUEST, 'max_id' , 0));
1885 $count = intval(defaults($_REQUEST, 'count' , 20));
1886 $page = intval(defaults($_REQUEST, 'page' , 1)) - 1;
1891 $start = $page * $count;
1894 $id = intval(defaults($_REQUEST, 'id', 0));
1899 $id = intval(defaults($a->argv, 4, 0));
1902 logger('API: api_conversation_show: '.$id);
1904 // try to fetch the item for the local user - or the public item, if there is no local one
1905 $item = dba::selectFirst('item', ['parent-uri'], ['id' => $id]);
1906 if (!DBM::is_result($item)) {
1907 throw new BadRequestException("There is no status with this id.");
1910 $parent = dba::selectFirst('item', ['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1911 if (!DBM::is_result($parent)) {
1912 throw new BadRequestException("There is no status with this id.");
1915 $id = $parent['id'];
1917 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1918 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1921 $condition[0] .= " AND `item`.`id` <= ?";
1922 $condition[] = $max_id;
1925 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1926 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1928 if (!DBM::is_result($statuses)) {
1929 throw new BadRequestException("There is no status with id $id.");
1932 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1934 $data = ['status' => $ret];
1935 return api_format_data("statuses", $type, $data);
1938 /// @TODO move to top of file or somewhere better
1939 api_register_func('api/conversation/show', 'api_conversation_show', true);
1940 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1945 * @param string $type Return type (atom, rss, xml, json)
1947 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1949 function api_statuses_repeat($type)
1955 if (api_user() === false) {
1956 throw new ForbiddenException();
1962 $id = intval($a->argv[3]);
1965 $id = intval($_REQUEST["id"]);
1970 $id = intval($a->argv[4]);
1973 logger('API: api_statuses_repeat: '.$id);
1975 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1976 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
1978 if (DBM::is_result($item) && $item['body'] != "") {
1979 if (strpos($item['body'], "[/share]") !== false) {
1980 $pos = strpos($item['body'], "[share");
1981 $post = substr($item['body'], $pos);
1983 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
1985 $post .= $item['body'];
1986 $post .= "[/share]";
1988 $_REQUEST['body'] = $post;
1989 $_REQUEST['profile_uid'] = api_user();
1990 $_REQUEST['type'] = 'wall';
1991 $_REQUEST['api_source'] = true;
1993 if (!x($_REQUEST, "source")) {
1994 $_REQUEST["source"] = api_source();
1999 throw new ForbiddenException();
2002 // this should output the last post (the one we just posted).
2004 return api_status_show($type);
2007 /// @TODO move to top of file or somewhere better
2008 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2011 * Destroys a specific status.
2013 * @param string $type Return type (atom, rss, xml, json)
2015 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2017 function api_statuses_destroy($type)
2021 if (api_user() === false) {
2022 throw new ForbiddenException();
2028 $id = intval($a->argv[3]);
2031 $id = intval($_REQUEST["id"]);
2036 $id = intval($a->argv[4]);
2039 logger('API: api_statuses_destroy: '.$id);
2041 $ret = api_statuses_show($type);
2043 Item::deleteForUser(['id' => $id], api_user());
2048 /// @TODO move to top of file or somewhere better
2049 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2052 * Returns the most recent mentions.
2054 * @param string $type Return type (atom, rss, xml, json)
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];
2104 $data = api_rss_extra($a, $data, $user_info);
2108 return api_format_data("statuses", $type, $data);
2111 /// @TODO move to top of file or somewhere better
2112 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2113 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2116 * Returns the most recent statuses posted by the user.
2118 * @brief Returns a user's public timeline
2120 * @param string $type Either "json" or "xml"
2121 * @return string|array
2122 * @throws ForbiddenException
2123 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2125 function api_statuses_user_timeline($type)
2128 $user_info = api_get_user($a);
2130 if (api_user() === false || $user_info === false) {
2131 throw new ForbiddenException();
2135 "api_statuses_user_timeline: api_user: ". api_user() .
2136 "\nuser_info: ".print_r($user_info, true) .
2137 "\n_REQUEST: ".print_r($_REQUEST, true),
2141 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2142 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2143 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2144 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2147 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2148 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2152 $start = ($page - 1) * $count;
2154 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2155 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2157 if ($user_info['self'] == 1) {
2158 $condition[0] .= ' AND `item`.`wall` ';
2161 if ($exclude_replies > 0) {
2162 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2165 if ($conversation_id > 0) {
2166 $condition[0] .= " AND `item`.`parent` = ?";
2167 $condition[] = $conversation_id;
2171 $condition[0] .= " AND `item`.`id` <= ?";
2172 $condition[] = $max_id;
2175 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2176 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2178 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2180 $data = ['status' => $ret];
2184 $data = api_rss_extra($a, $data, $user_info);
2188 return api_format_data("statuses", $type, $data);
2191 /// @TODO move to top of file or somewhere better
2192 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2195 * Star/unstar an item.
2196 * param: id : id of the item
2198 * @param string $type Return type (atom, rss, xml, json)
2200 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2202 function api_favorites_create_destroy($type)
2206 if (api_user() === false) {
2207 throw new ForbiddenException();
2210 // for versioned api.
2211 /// @TODO We need a better global soluton
2212 $action_argv_id = 2;
2213 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2214 $action_argv_id = 3;
2217 if ($a->argc <= $action_argv_id) {
2218 throw new BadRequestException("Invalid request.");
2220 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2221 if ($a->argc == $action_argv_id + 2) {
2222 $itemid = intval($a->argv[$action_argv_id + 1]);
2224 /// @TODO use x() to check if _REQUEST contains 'id'
2225 $itemid = intval($_REQUEST['id']);
2228 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2230 if (!DBM::is_result($item)) {
2231 throw new BadRequestException("Invalid item.");
2236 $item['starred'] = 1;
2239 $item['starred'] = 0;
2242 throw new BadRequestException("Invalid action ".$action);
2245 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2248 throw new InternalServerErrorException("DB error");
2252 $user_info = api_get_user($a);
2253 $rets = api_format_items([$item], $user_info, false, $type);
2256 $data = ['status' => $ret];
2260 $data = api_rss_extra($a, $data, $user_info);
2263 return api_format_data("status", $type, $data);
2266 /// @TODO move to top of file or somewhere better
2267 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2268 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2271 * Returns the most recent favorite statuses.
2273 * @param string $type Return type (atom, rss, xml, json)
2275 * @return string|array
2277 function api_favorites($type)
2282 $user_info = api_get_user($a);
2284 if (api_user() === false || $user_info === false) {
2285 throw new ForbiddenException();
2290 // in friendica starred item are private
2291 // return favorites only for self
2292 logger('api_favorites: self:' . $user_info['self']);
2294 if ($user_info['self'] == 0) {
2298 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2299 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2300 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2301 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2306 $start = $page*$count;
2308 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2309 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2311 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2314 $condition[0] .= " AND `item`.`id` <= ?";
2315 $condition[] = $max_id;
2318 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2320 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2323 $data = ['status' => $ret];
2327 $data = api_rss_extra($a, $data, $user_info);
2330 return api_format_data("statuses", $type, $data);
2333 /// @TODO move to top of file or somewhere better
2334 api_register_func('api/favorites', 'api_favorites', true);
2338 * @param array $item
2339 * @param array $recipient
2340 * @param array $sender
2344 function api_format_messages($item, $recipient, $sender)
2346 // standard meta information
2348 'id' => $item['id'],
2349 'sender_id' => $sender['id'] ,
2351 'recipient_id' => $recipient['id'],
2352 'created_at' => api_date($item['created']),
2353 'sender_screen_name' => $sender['screen_name'],
2354 'recipient_screen_name' => $recipient['screen_name'],
2355 'sender' => $sender,
2356 'recipient' => $recipient,
2358 'friendica_seen' => $item['seen'],
2359 'friendica_parent_uri' => $item['parent-uri'],
2362 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2363 unset($ret["sender"]["uid"]);
2364 unset($ret["sender"]["self"]);
2365 unset($ret["recipient"]["uid"]);
2366 unset($ret["recipient"]["self"]);
2368 //don't send title to regular StatusNET requests to avoid confusing these apps
2369 if (x($_GET, 'getText')) {
2370 $ret['title'] = $item['title'];
2371 if ($_GET['getText'] == 'html') {
2372 $ret['text'] = BBCode::convert($item['body'], false);
2373 } elseif ($_GET['getText'] == 'plain') {
2374 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2377 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2379 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2380 unset($ret['sender']);
2381 unset($ret['recipient']);
2389 * @param array $item
2393 function api_convert_item($item)
2395 $body = $item['body'];
2396 $attachments = api_get_attachments($body);
2398 // Workaround for ostatus messages where the title is identically to the body
2399 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2400 $statusbody = trim(HTML::toPlaintext($html, 0));
2402 // handle data: images
2403 $statusbody = api_format_items_embeded_images($item, $statusbody);
2405 $statustitle = trim($item['title']);
2407 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2408 $statustext = trim($statusbody);
2410 $statustext = trim($statustitle."\n\n".$statusbody);
2413 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2414 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2417 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2419 // Workaround for clients with limited HTML parser functionality
2420 $search = ["<br>", "<blockquote>", "</blockquote>",
2421 "<h1>", "</h1>", "<h2>", "</h2>",
2422 "<h3>", "</h3>", "<h4>", "</h4>",
2423 "<h5>", "</h5>", "<h6>", "</h6>"];
2424 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2425 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2426 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2427 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2428 $statushtml = str_replace($search, $replace, $statushtml);
2430 if ($item['title'] != "") {
2431 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2435 $oldtext = $statushtml;
2436 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2437 } while ($oldtext != $statushtml);
2439 if (substr($statushtml, 0, 4) == '<br>') {
2440 $statushtml = substr($statushtml, 4);
2443 if (substr($statushtml, 0, -4) == '<br>') {
2444 $statushtml = substr($statushtml, -4);
2447 // feeds without body should contain the link
2448 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2449 $statushtml .= BBCode::convert($item['plink']);
2452 $entities = api_get_entitities($statustext, $body);
2455 "text" => $statustext,
2456 "html" => $statushtml,
2457 "attachments" => $attachments,
2458 "entities" => $entities
2464 * @param string $body
2468 function api_get_attachments(&$body)
2471 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2473 $URLSearchString = "^\[\]";
2474 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2482 foreach ($images[1] as $image) {
2483 $imagedata = Image::getInfoFromURL($image);
2486 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2490 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2491 foreach ($images[0] as $orig) {
2492 $body = str_replace($orig, "", $body);
2496 return $attachments;
2501 * @param string $text
2502 * @param string $bbcode
2505 * @todo Links at the first character of the post
2507 function api_get_entitities(&$text, $bbcode)
2509 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2511 if ($include_entities != "true") {
2512 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2514 foreach ($images[1] as $image) {
2515 $replace = proxy_url($image);
2516 $text = str_replace($image, $replace, $text);
2521 $bbcode = BBCode::cleanPictureLinks($bbcode);
2523 // Change pure links in text to bbcode uris
2524 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2527 $entities["hashtags"] = [];
2528 $entities["symbols"] = [];
2529 $entities["urls"] = [];
2530 $entities["user_mentions"] = [];
2532 $URLSearchString = "^\[\]";
2534 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2536 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2537 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2538 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2540 $bbcode = preg_replace(
2541 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2542 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2545 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2547 $bbcode = preg_replace(
2548 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2549 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2552 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2554 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2556 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2557 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2560 foreach ($urls[1] as $id => $url) {
2561 //$start = strpos($text, $url, $offset);
2562 $start = iconv_strpos($text, $url, 0, "UTF-8");
2563 if (!($start === false)) {
2564 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2568 ksort($ordered_urls);
2571 //foreach ($urls[1] AS $id=>$url) {
2572 foreach ($ordered_urls as $url) {
2573 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2574 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2576 $display_url = $url["title"];
2578 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2579 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2581 if (strlen($display_url) > 26) {
2582 $display_url = substr($display_url, 0, 25)."…";
2586 //$start = strpos($text, $url, $offset);
2587 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2588 if (!($start === false)) {
2589 $entities["urls"][] = ["url" => $url["url"],
2590 "expanded_url" => $url["url"],
2591 "display_url" => $display_url,
2592 "indices" => [$start, $start+strlen($url["url"])]];
2593 $offset = $start + 1;
2597 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2598 $ordered_images = [];
2599 foreach ($images[1] as $image) {
2600 //$start = strpos($text, $url, $offset);
2601 $start = iconv_strpos($text, $image, 0, "UTF-8");
2602 if (!($start === false)) {
2603 $ordered_images[$start] = $image;
2606 //$entities["media"] = array();
2609 foreach ($ordered_images as $url) {
2610 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2611 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2613 if (strlen($display_url) > 26) {
2614 $display_url = substr($display_url, 0, 25)."…";
2617 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2618 if (!($start === false)) {
2619 $image = Image::getInfoFromURL($url);
2621 // If image cache is activated, then use the following sizes:
2622 // thumb (150), small (340), medium (600) and large (1024)
2623 if (!Config::get("system", "proxy_disabled")) {
2624 $media_url = proxy_url($url);
2627 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2628 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2630 if (($image[0] > 150) || ($image[1] > 150)) {
2631 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2632 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2635 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2636 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2638 if (($image[0] > 600) || ($image[1] > 600)) {
2639 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2640 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2644 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2647 $entities["media"][] = [
2649 "id_str" => (string)$start+1,
2650 "indices" => [$start, $start+strlen($url)],
2651 "media_url" => normalise_link($media_url),
2652 "media_url_https" => $media_url,
2654 "display_url" => $display_url,
2655 "expanded_url" => $url,
2659 $offset = $start + 1;
2668 * @param array $item
2669 * @param string $text
2673 function api_format_items_embeded_images($item, $text)
2675 $text = preg_replace_callback(
2676 '|data:image/([^;]+)[^=]+=*|m',
2677 function () use ($item) {
2678 return System::baseUrl() . '/display/' . $item['guid'];
2686 * @brief return <a href='url'>name</a> as array
2688 * @param string $txt text
2693 function api_contactlink_to_array($txt)
2696 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2697 if ($r && count($match)==3) {
2699 'name' => $match[2],
2713 * @brief return likes, dislikes and attend status for item
2715 * @param array $item array
2716 * @param string $type Return type (atom, rss, xml, json)
2719 * likes => int count,
2720 * dislikes => int count
2722 function api_format_items_activities(&$item, $type = "json")
2731 'attendmaybe' => [],
2734 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2735 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2737 while ($item = Item::fetch($ret)) {
2738 // not used as result should be structured like other user data
2739 //builtin_activity_puller($i, $activities);
2741 // get user data and add it to the array of the activity
2742 $user = api_get_user($a, $item['author-id']);
2743 switch ($item['verb']) {
2745 $activities['like'][] = $user;
2747 case ACTIVITY_DISLIKE:
2748 $activities['dislike'][] = $user;
2750 case ACTIVITY_ATTEND:
2751 $activities['attendyes'][] = $user;
2753 case ACTIVITY_ATTENDNO:
2754 $activities['attendno'][] = $user;
2756 case ACTIVITY_ATTENDMAYBE:
2757 $activities['attendmaybe'][] = $user;
2766 if ($type == "xml") {
2767 $xml_activities = [];
2768 foreach ($activities as $k => $v) {
2769 // change xml element from "like" to "friendica:like"
2770 $xml_activities["friendica:".$k] = $v;
2771 // add user data into xml output
2773 foreach ($v as $user) {
2774 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2777 $activities = $xml_activities;
2785 * @brief return data from profiles
2787 * @param array $profile_row array containing data from db table 'profile'
2790 function api_format_items_profiles($profile_row)
2793 'profile_id' => $profile_row['id'],
2794 'profile_name' => $profile_row['profile-name'],
2795 'is_default' => $profile_row['is-default'] ? true : false,
2796 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2797 'profile_photo' => $profile_row['photo'],
2798 'profile_thumb' => $profile_row['thumb'],
2799 'publish' => $profile_row['publish'] ? true : false,
2800 'net_publish' => $profile_row['net-publish'] ? true : false,
2801 'description' => $profile_row['pdesc'],
2802 'date_of_birth' => $profile_row['dob'],
2803 'address' => $profile_row['address'],
2804 'city' => $profile_row['locality'],
2805 'region' => $profile_row['region'],
2806 'postal_code' => $profile_row['postal-code'],
2807 'country' => $profile_row['country-name'],
2808 'hometown' => $profile_row['hometown'],
2809 'gender' => $profile_row['gender'],
2810 'marital' => $profile_row['marital'],
2811 'marital_with' => $profile_row['with'],
2812 'marital_since' => $profile_row['howlong'],
2813 'sexual' => $profile_row['sexual'],
2814 'politic' => $profile_row['politic'],
2815 'religion' => $profile_row['religion'],
2816 'public_keywords' => $profile_row['pub_keywords'],
2817 'private_keywords' => $profile_row['prv_keywords'],
2818 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2819 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2820 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2821 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2822 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2823 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2824 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2825 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2826 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2827 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2828 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2829 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2830 'homepage' => $profile_row['homepage'],
2837 * @brief format items to be returned by api
2839 * @param array $r array of items
2840 * @param array $user_info
2841 * @param bool $filter_user filter items by $user_info
2842 * @param string $type Return type (atom, rss, xml, json)
2844 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2850 foreach ($r as $item) {
2851 localize_item($item);
2852 list($status_user, $owner_user) = api_item_get_user($a, $item);
2854 // Look if the posts are matching if they should be filtered by user id
2855 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2859 $in_reply_to = api_in_reply_to($item);
2861 $converted = api_convert_item($item);
2863 if ($type == "xml") {
2864 $geo = "georss:point";
2870 'text' => $converted["text"],
2871 'truncated' => false,
2872 'created_at'=> api_date($item['created']),
2873 'in_reply_to_status_id' => $in_reply_to['status_id'],
2874 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2875 'source' => (($item['app']) ? $item['app'] : 'web'),
2876 'id' => intval($item['id']),
2877 'id_str' => (string) intval($item['id']),
2878 'in_reply_to_user_id' => $in_reply_to['user_id'],
2879 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2880 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2882 'favorited' => $item['starred'] ? true : false,
2883 'user' => $status_user ,
2884 'friendica_owner' => $owner_user,
2885 //'entities' => NULL,
2886 'statusnet_html' => $converted["html"],
2887 'statusnet_conversation_id' => $item['parent'],
2888 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2889 'friendica_activities' => api_format_items_activities($item, $type),
2892 if (count($converted["attachments"]) > 0) {
2893 $status["attachments"] = $converted["attachments"];
2896 if (count($converted["entities"]) > 0) {
2897 $status["entities"] = $converted["entities"];
2900 if ($status["source"] == 'web') {
2901 $status["source"] = ContactSelector::networkToName($item['network'], $user_info['url']);
2902 } elseif (ContactSelector::networkToName($item['network'], $user_info['url']) != $status["source"]) {
2903 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $user_info['url']).')');
2906 if ($item["id"] == $item["parent"]) {
2907 $retweeted_item = api_share_as_retweet($item);
2908 if ($retweeted_item !== false) {
2909 $retweeted_status = $status;
2911 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
2912 } catch (BadRequestException $e) {
2913 // user not found. should be found?
2914 /// @todo check if the user should be always found
2915 $retweeted_status["user"] = [];
2918 $rt_converted = api_convert_item($retweeted_item);
2920 $retweeted_status['text'] = $rt_converted["text"];
2921 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2922 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2923 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2924 $status['retweeted_status'] = $retweeted_status;
2928 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2929 unset($status["user"]["uid"]);
2930 unset($status["user"]["self"]);
2932 if ($item["coord"] != "") {
2933 $coords = explode(' ', $item["coord"]);
2934 if (count($coords) == 2) {
2935 if ($type == "json") {
2936 $status["geo"] = ['type' => 'Point',
2937 'coordinates' => [(float) $coords[0],
2938 (float) $coords[1]]];
2939 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2940 $status["georss:point"] = $item["coord"];
2950 * Returns the remaining number of API requests available to the user before the API limit is reached.
2952 * @param string $type Return type (atom, rss, xml, json)
2954 * @return array|string
2956 function api_account_rate_limit_status($type)
2958 if ($type == "xml") {
2960 'remaining-hits' => '150',
2961 '@attributes' => ["type" => "integer"],
2962 'hourly-limit' => '150',
2963 '@attributes2' => ["type" => "integer"],
2964 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
2965 '@attributes3' => ["type" => "datetime"],
2966 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2967 '@attributes4' => ["type" => "integer"],
2971 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2972 'remaining_hits' => '150',
2973 'hourly_limit' => '150',
2974 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
2978 return api_format_data('hash', $type, ['hash' => $hash]);
2981 /// @TODO move to top of file or somewhere better
2982 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
2985 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
2987 * @param string $type Return type (atom, rss, xml, json)
2989 * @return array|string
2991 function api_help_test($type)
2993 if ($type == 'xml') {
2999 return api_format_data('ok', $type, ["ok" => $ok]);
3002 /// @TODO move to top of file or somewhere better
3003 api_register_func('api/help/test', 'api_help_test', false);
3006 * Returns all lists the user subscribes to.
3008 * @param string $type Return type (atom, rss, xml, json)
3010 * @return array|string
3011 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3013 function api_lists_list($type)
3016 /// @TODO $ret is not filled here?
3017 return api_format_data('lists', $type, ["lists_list" => $ret]);
3020 /// @TODO move to top of file or somewhere better
3021 api_register_func('api/lists/list', 'api_lists_list', true);
3022 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3025 * Returns all groups the user owns.
3027 * @param string $type Return type (atom, rss, xml, json)
3029 * @return array|string
3030 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3032 function api_lists_ownerships($type)
3036 if (api_user() === false) {
3037 throw new ForbiddenException();
3041 $user_info = api_get_user($a);
3042 $uid = $user_info['uid'];
3044 $groups = dba::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3046 // loop through all groups
3048 foreach ($groups as $group) {
3049 if ($group['visible']) {
3055 'name' => $group['name'],
3056 'id' => intval($group['id']),
3057 'id_str' => (string) $group['id'],
3058 'user' => $user_info,
3062 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3065 /// @TODO move to top of file or somewhere better
3066 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3069 * Returns recent statuses from users in the specified group.
3071 * @param string $type Return type (atom, rss, xml, json)
3073 * @return array|string
3074 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3076 function api_lists_statuses($type)
3080 $user_info = api_get_user($a);
3081 if (api_user() === false || $user_info === false) {
3082 throw new ForbiddenException();
3085 unset($_REQUEST["user_id"]);
3086 unset($_GET["user_id"]);
3088 unset($_REQUEST["screen_name"]);
3089 unset($_GET["screen_name"]);
3091 if (empty($_REQUEST['list_id'])) {
3092 throw new BadRequestException('list_id not specified');
3096 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
3097 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
3101 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3102 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3103 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
3104 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
3106 $start = $page * $count;
3108 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3109 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3112 $condition[0] .= " AND `item`.`id` <= ?";
3113 $condition[] = $max_id;
3115 if ($exclude_replies > 0) {
3116 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3118 if ($conversation_id > 0) {
3119 $condition[0] .= " AND `item`.`parent` = ?";
3120 $condition[] = $conversation_id;
3123 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3124 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3126 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3128 $data = ['status' => $items];
3132 $data = api_rss_extra($a, $data, $user_info);
3136 return api_format_data("statuses", $type, $data);
3139 /// @TODO move to top of file or somewhere better
3140 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3143 * Considers friends and followers lists to be private and won't return
3144 * anything if any user_id parameter is passed.
3146 * @brief Returns either the friends of the follower list
3148 * @param string $qtype Either "friends" or "followers"
3149 * @return boolean|array
3150 * @throws ForbiddenException
3152 function api_statuses_f($qtype)
3156 if (api_user() === false) {
3157 throw new ForbiddenException();
3161 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3162 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3166 $start = ($page - 1) * $count;
3168 $user_info = api_get_user($a);
3170 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3171 /* this is to stop Hotot to load friends multiple times
3172 * I'm not sure if I'm missing return something or
3173 * is a bug in hotot. Workaround, meantime
3177 return array('$users' => $ret);*/
3182 if ($qtype == 'friends') {
3183 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3184 } elseif ($qtype == 'followers') {
3185 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3188 // friends and followers only for self
3189 if ($user_info['self'] == 0) {
3190 $sql_extra = " AND false ";
3193 if ($qtype == 'blocks') {
3194 $sql_filter = 'AND `blocked` AND NOT `pending`';
3195 } elseif ($qtype == 'incoming') {
3196 $sql_filter = 'AND `pending`';
3198 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3216 foreach ($r as $cid) {
3217 $user = api_get_user($a, $cid['nurl']);
3218 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3219 unset($user["uid"]);
3220 unset($user["self"]);
3227 return ['user' => $ret];
3232 * Returns the user's friends.
3234 * @brief Returns the list of friends of the provided user
3236 * @deprecated By Twitter API in favor of friends/list
3238 * @param string $type Either "json" or "xml"
3239 * @return boolean|string|array
3241 function api_statuses_friends($type)
3243 $data = api_statuses_f("friends");
3244 if ($data === false) {
3247 return api_format_data("users", $type, $data);
3251 * Returns the user's followers.
3253 * @brief Returns the list of followers of the provided user
3255 * @deprecated By Twitter API in favor of friends/list
3257 * @param string $type Either "json" or "xml"
3258 * @return boolean|string|array
3260 function api_statuses_followers($type)
3262 $data = api_statuses_f("followers");
3263 if ($data === false) {
3266 return api_format_data("users", $type, $data);
3269 /// @TODO move to top of file or somewhere better
3270 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3271 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3274 * Returns the list of blocked users
3276 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3278 * @param string $type Either "json" or "xml"
3280 * @return boolean|string|array
3282 function api_blocks_list($type)
3284 $data = api_statuses_f('blocks');
3285 if ($data === false) {
3288 return api_format_data("users", $type, $data);
3291 /// @TODO move to top of file or somewhere better
3292 api_register_func('api/blocks/list', 'api_blocks_list', true);
3295 * Returns the list of pending users IDs
3297 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3299 * @param string $type Either "json" or "xml"
3301 * @return boolean|string|array
3303 function api_friendships_incoming($type)
3305 $data = api_statuses_f('incoming');
3306 if ($data === false) {
3311 foreach ($data['user'] as $user) {
3312 $ids[] = $user['id'];
3315 return api_format_data("ids", $type, ['id' => $ids]);
3318 /// @TODO move to top of file or somewhere better
3319 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3322 * Returns the instance's configuration information.
3324 * @param string $type Return type (atom, rss, xml, json)
3326 * @return array|string
3328 function api_statusnet_config($type)
3332 $name = $a->config['sitename'];
3333 $server = $a->get_hostname();
3334 $logo = System::baseUrl() . '/images/friendica-64.png';
3335 $email = $a->config['admin_email'];
3336 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3337 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3338 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3339 if ($a->config['api_import_size']) {
3340 $textlimit = (string) $a->config['api_import_size'];
3342 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3343 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3346 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3347 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3348 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3349 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3350 'shorturllength' => '30',
3352 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3353 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3354 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3355 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3360 return api_format_data('config', $type, ['config' => $config]);
3363 /// @TODO move to top of file or somewhere better
3364 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3365 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3369 * @param string $type Return type (atom, rss, xml, json)
3371 * @return array|string
3373 function api_statusnet_version($type)
3376 $fake_statusnet_version = "0.9.7";
3378 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3381 /// @TODO move to top of file or somewhere better
3382 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3383 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3387 * @param string $type Return type (atom, rss, xml, json)
3389 * @todo use api_format_data() to return data
3391 function api_ff_ids($type)
3394 throw new ForbiddenException();
3401 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3404 "SELECT `pcontact`.`id` FROM `contact`
3405 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3406 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3409 if (!DBM::is_result($r)) {
3414 foreach ($r as $rr) {
3415 if ($stringify_ids) {
3418 $ids[] = intval($rr['id']);
3422 return api_format_data("ids", $type, ['id' => $ids]);
3426 * Returns the ID of every user the user is following.
3428 * @param string $type Return type (atom, rss, xml, json)
3430 * @return array|string
3431 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3433 function api_friends_ids($type)
3435 return api_ff_ids($type);
3439 * Returns the ID of every user following the user.
3441 * @param string $type Return type (atom, rss, xml, json)
3443 * @return array|string
3444 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3446 function api_followers_ids($type)
3448 return api_ff_ids($type);
3451 /// @TODO move to top of file or somewhere better
3452 api_register_func('api/friends/ids', 'api_friends_ids', true);
3453 api_register_func('api/followers/ids', 'api_followers_ids', true);
3456 * Sends a new direct message.
3458 * @param string $type Return type (atom, rss, xml, json)
3460 * @return array|string
3461 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3463 function api_direct_messages_new($type)
3468 if (api_user() === false) {
3469 throw new ForbiddenException();
3472 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3476 $sender = api_get_user($a);
3478 if ($_POST['screen_name']) {
3480 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3482 dbesc($_POST['screen_name'])
3485 // Selecting the id by priority, friendica first
3486 api_best_nickname($r);
3488 $recipient = api_get_user($a, $r[0]['nurl']);
3490 $recipient = api_get_user($a, $_POST['user_id']);
3495 if (x($_REQUEST, 'replyto')) {
3497 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3499 intval($_REQUEST['replyto'])
3501 $replyto = $r[0]['parent-uri'];
3502 $sub = $r[0]['title'];
3504 if (x($_REQUEST, 'title')) {
3505 $sub = $_REQUEST['title'];
3507 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3511 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3514 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3515 $ret = api_format_messages($r[0], $recipient, $sender);
3517 $ret = ["error"=>$id];
3520 $data = ['direct_message'=>$ret];
3525 $data = api_rss_extra($a, $data, $sender);
3528 return api_format_data("direct-messages", $type, $data);
3531 /// @TODO move to top of file or somewhere better
3532 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3535 * Destroys a direct message.
3537 * @brief delete a direct_message from mail table through api
3539 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3540 * @return string|array
3541 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3543 function api_direct_messages_destroy($type)
3547 if (api_user() === false) {
3548 throw new ForbiddenException();
3552 $user_info = api_get_user($a);
3554 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3556 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3557 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3558 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3560 $uid = $user_info['uid'];
3561 // error if no id or parenturi specified (for clients posting parent-uri as well)
3562 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3563 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3564 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3567 // BadRequestException if no id specified (for clients using Twitter API)
3569 throw new BadRequestException('Message id not specified');
3572 // add parent-uri to sql command if specified by calling app
3573 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3575 // get data of the specified message id
3577 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3582 // error message if specified id is not in database
3583 if (!DBM::is_result($r)) {
3584 if ($verbose == "true") {
3585 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3586 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3588 /// @todo BadRequestException ok for Twitter API clients?
3589 throw new BadRequestException('message id not in database');
3594 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3599 if ($verbose == "true") {
3602 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3603 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3605 $answer = ['result' => 'error', 'message' => 'unknown error'];
3606 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3609 /// @todo return JSON data like Twitter API not yet implemented
3612 /// @TODO move to top of file or somewhere better
3613 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3617 * @param string $type Return type (atom, rss, xml, json)
3618 * @param string $box
3619 * @param string $verbose
3621 * @return array|string
3623 function api_direct_messages_box($type, $box, $verbose)
3626 if (api_user() === false) {
3627 throw new ForbiddenException();
3630 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3631 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3636 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3637 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3639 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3640 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3643 unset($_REQUEST["user_id"]);
3644 unset($_GET["user_id"]);
3646 unset($_REQUEST["screen_name"]);
3647 unset($_GET["screen_name"]);
3649 $user_info = api_get_user($a);
3650 if ($user_info === false) {
3651 throw new ForbiddenException();
3653 $profile_url = $user_info["url"];
3656 $start = $page * $count;
3661 if ($box=="sentbox") {
3662 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3663 } elseif ($box == "conversation") {
3664 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3665 } elseif ($box == "all") {
3666 $sql_extra = "true";
3667 } elseif ($box == "inbox") {
3668 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3672 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3675 if ($user_id != "") {
3676 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3677 } elseif ($screen_name !="") {
3678 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3682 "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",
3688 if ($verbose == "true" && !DBM::is_result($r)) {
3689 $answer = ['result' => 'error', 'message' => 'no mails available'];
3690 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3694 foreach ($r as $item) {
3695 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3696 $recipient = $user_info;
3697 $sender = api_get_user($a, normalise_link($item['contact-url']));
3698 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3699 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3700 $sender = $user_info;
3703 if (isset($recipient) && isset($sender)) {
3704 $ret[] = api_format_messages($item, $recipient, $sender);
3709 $data = ['direct_message' => $ret];
3713 $data = api_rss_extra($a, $data, $user_info);
3716 return api_format_data("direct-messages", $type, $data);
3720 * Returns the most recent direct messages sent by the user.
3722 * @param string $type Return type (atom, rss, xml, json)
3724 * @return array|string
3725 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3727 function api_direct_messages_sentbox($type)
3729 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3730 return api_direct_messages_box($type, "sentbox", $verbose);
3734 * Returns the most recent direct messages sent to the user.
3736 * @param string $type Return type (atom, rss, xml, json)
3738 * @return array|string
3739 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3741 function api_direct_messages_inbox($type)
3743 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3744 return api_direct_messages_box($type, "inbox", $verbose);
3749 * @param string $type Return type (atom, rss, xml, json)
3751 * @return array|string
3753 function api_direct_messages_all($type)
3755 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3756 return api_direct_messages_box($type, "all", $verbose);
3761 * @param string $type Return type (atom, rss, xml, json)
3763 * @return array|string
3765 function api_direct_messages_conversation($type)
3767 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3768 return api_direct_messages_box($type, "conversation", $verbose);
3771 /// @TODO move to top of file or somewhere better
3772 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3773 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3774 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3775 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3778 * Returns an OAuth Request Token.
3780 * @see https://oauth.net/core/1.0/#auth_step1
3782 function api_oauth_request_token()
3784 $oauth1 = new FKOAuth1();
3786 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3787 } catch (Exception $e) {
3788 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3796 * Returns an OAuth Access Token.
3798 * @return array|string
3799 * @see https://oauth.net/core/1.0/#auth_step3
3801 function api_oauth_access_token()
3803 $oauth1 = new FKOAuth1();
3805 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3806 } catch (Exception $e) {
3807 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3814 /// @TODO move to top of file or somewhere better
3815 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3816 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3820 * @brief delete a complete photoalbum with all containing photos from database through api
3822 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3823 * @return string|array
3825 function api_fr_photoalbum_delete($type)
3827 if (api_user() === false) {
3828 throw new ForbiddenException();
3831 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3833 // we do not allow calls without album string
3835 throw new BadRequestException("no albumname specified");
3837 // check if album is existing
3839 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3843 if (!DBM::is_result($r)) {
3844 throw new BadRequestException("album not available");
3847 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3848 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3849 foreach ($r as $rr) {
3850 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
3851 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
3853 if (!DBM::is_result($photo_item)) {
3854 throw new InternalServerErrorException("problem with deleting items occured");
3856 Item::deleteForUser(['id' => $photo_item['id']], api_user());
3859 // now let's delete all photos from the album
3860 $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
3862 // return success of deletion or error message
3864 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
3865 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
3867 throw new InternalServerErrorException("unknown error - deleting from database failed");
3872 * @brief update the name of the album for all photos of an album
3874 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3875 * @return string|array
3877 function api_fr_photoalbum_update($type)
3879 if (api_user() === false) {
3880 throw new ForbiddenException();
3883 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3884 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3886 // we do not allow calls without album string
3888 throw new BadRequestException("no albumname specified");
3890 if ($album_new == "") {
3891 throw new BadRequestException("no new albumname specified");
3893 // check if album is existing
3894 if (!dba::exists('photo', ['uid' => api_user(), 'album' => $album])) {
3895 throw new BadRequestException("album not available");
3897 // now let's update all photos to the albumname
3898 $result = dba::update('photo', ['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
3900 // return success of updating or error message
3902 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
3903 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
3905 throw new InternalServerErrorException("unknown error - updating in database failed");
3911 * @brief list all photos of the authenticated user
3913 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3914 * @return string|array
3916 function api_fr_photos_list($type)
3918 if (api_user() === false) {
3919 throw new ForbiddenException();
3922 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3923 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3924 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3925 intval(local_user())
3928 'image/jpeg' => 'jpg',
3929 'image/png' => 'png',
3930 'image/gif' => 'gif'
3932 $data = ['photo'=>[]];
3933 if (DBM::is_result($r)) {
3934 foreach ($r as $rr) {
3936 $photo['id'] = $rr['resource-id'];
3937 $photo['album'] = $rr['album'];
3938 $photo['filename'] = $rr['filename'];
3939 $photo['type'] = $rr['type'];
3940 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3941 $photo['created'] = $rr['created'];
3942 $photo['edited'] = $rr['edited'];
3943 $photo['desc'] = $rr['desc'];
3945 if ($type == "xml") {
3946 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3948 $photo['thumb'] = $thumb;
3949 $data['photo'][] = $photo;
3953 return api_format_data("photos", $type, $data);
3957 * @brief upload a new photo or change an existing photo
3959 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3960 * @return string|array
3962 function api_fr_photo_create_update($type)
3964 if (api_user() === false) {
3965 throw new ForbiddenException();
3968 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3969 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3970 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3971 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3972 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3973 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3974 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3975 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3976 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3978 // do several checks on input parameters
3979 // we do not allow calls without album string
3980 if ($album == null) {
3981 throw new BadRequestException("no albumname specified");
3983 // if photo_id == null --> we are uploading a new photo
3984 if ($photo_id == null) {
3987 // error if no media posted in create-mode
3988 if (!x($_FILES, 'media')) {
3990 throw new BadRequestException("no media data submitted");
3993 // album_new will be ignored in create-mode
3998 // check if photo is existing in database
4000 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4005 if (!DBM::is_result($r)) {
4006 throw new BadRequestException("photo not available");
4010 // checks on acl strings provided by clients
4011 $acl_input_error = false;
4012 $acl_input_error |= check_acl_input($allow_cid);
4013 $acl_input_error |= check_acl_input($deny_cid);
4014 $acl_input_error |= check_acl_input($allow_gid);
4015 $acl_input_error |= check_acl_input($deny_gid);
4016 if ($acl_input_error) {
4017 throw new BadRequestException("acl data invalid");
4019 // now let's upload the new media in create-mode
4020 if ($mode == "create") {
4021 $media = $_FILES['media'];
4022 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4024 // return success of updating or error message
4025 if (!is_null($data)) {
4026 return api_format_data("photo_create", $type, $data);
4028 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4032 // now let's do the changes in update-mode
4033 if ($mode == "update") {
4036 if (!is_null($desc)) {
4037 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4040 if (!is_null($album_new)) {
4041 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4044 if (!is_null($allow_cid)) {
4045 $allow_cid = trim($allow_cid);
4046 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4049 if (!is_null($deny_cid)) {
4050 $deny_cid = trim($deny_cid);
4051 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4054 if (!is_null($allow_gid)) {
4055 $allow_gid = trim($allow_gid);
4056 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4059 if (!is_null($deny_gid)) {
4060 $deny_gid = trim($deny_gid);
4061 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4065 if ($sql_extra != "") {
4066 $nothingtodo = false;
4068 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4070 DateTimeFormat::utcNow(), // update edited timestamp
4076 $nothingtodo = true;
4079 if (x($_FILES, 'media')) {
4080 $nothingtodo = false;
4081 $media = $_FILES['media'];
4082 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4083 if (!is_null($data)) {
4084 return api_format_data("photo_update", $type, $data);
4088 // return success of updating or error message
4090 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4091 return api_format_data("photo_update", $type, ['$result' => $answer]);
4094 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4095 return api_format_data("photo_update", $type, ['$result' => $answer]);
4097 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4100 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4104 * @brief delete a single photo from the database through api
4106 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4107 * @return string|array
4109 function api_fr_photo_delete($type)
4111 if (api_user() === false) {
4112 throw new ForbiddenException();
4115 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4117 // do several checks on input parameters
4118 // we do not allow calls without photo id
4119 if ($photo_id == null) {
4120 throw new BadRequestException("no photo_id specified");
4122 // check if photo is existing in database
4124 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4128 if (!DBM::is_result($r)) {
4129 throw new BadRequestException("photo not available");
4131 // now we can perform on the deletion of the photo
4132 $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4134 // return success of deletion or error message
4136 // retrieve the id of the parent element (the photo element)
4137 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4138 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4140 if (!DBM::is_result($photo_item)) {
4141 throw new InternalServerErrorException("problem with deleting items occured");
4143 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4144 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4145 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4147 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4148 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4150 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4156 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4158 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4159 * @return string|array
4161 function api_fr_photo_detail($type)
4163 if (api_user() === false) {
4164 throw new ForbiddenException();
4166 if (!x($_REQUEST, 'photo_id')) {
4167 throw new BadRequestException("No photo id.");
4170 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4171 $photo_id = $_REQUEST['photo_id'];
4173 // prepare json/xml output with data from database for the requested photo
4174 $data = prepare_photo_data($type, $scale, $photo_id);
4176 return api_format_data("photo_detail", $type, $data);
4181 * Updates the user’s profile image.
4183 * @brief updates the profile image for the user (either a specified profile or the default profile)
4185 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4187 * @return string|array
4188 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4190 function api_account_update_profile_image($type)
4192 if (api_user() === false) {
4193 throw new ForbiddenException();
4196 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4198 // error if image data is missing
4199 if (!x($_FILES, 'image')) {
4200 throw new BadRequestException("no media data submitted");
4203 // check if specified profile id is valid
4204 if ($profile_id != 0) {
4205 $profile = dba::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4206 // error message if specified profile id is not in database
4207 if (!DBM::is_result($profile)) {
4208 throw new BadRequestException("profile_id not available");
4210 $is_default_profile = $profile['is-default'];
4212 $is_default_profile = 1;
4215 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4217 if (x($_FILES, 'image')) {
4218 $media = $_FILES['image'];
4219 } elseif (x($_FILES, 'media')) {
4220 $media = $_FILES['media'];
4222 // save new profile image
4223 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4226 if (is_array($media['type'])) {
4227 $filetype = $media['type'][0];
4229 $filetype = $media['type'];
4231 if ($filetype == "image/jpeg") {
4233 } elseif ($filetype == "image/png") {
4236 throw new InternalServerErrorException('Unsupported filetype');
4239 // change specified profile or all profiles to the new resource-id
4240 if ($is_default_profile) {
4241 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4242 dba::update('photo', ['profile' => false], $condition);
4244 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype,
4245 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype];
4246 dba::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4249 Contact::updateSelfFromUserID(api_user(), true);
4251 // Update global directory in background
4252 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4253 if ($url && strlen(Config::get('system', 'directory'))) {
4254 Worker::add(PRIORITY_LOW, "Directory", $url);
4257 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4259 // output for client
4261 return api_account_verify_credentials($type);
4263 // SaveMediaToDatabase failed for some reason
4264 throw new InternalServerErrorException("image upload failed");
4268 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4269 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4270 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4271 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4272 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4273 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4274 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4275 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4276 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4279 * Update user profile
4281 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4283 * @return array|string
4285 function api_account_update_profile($type)
4287 $local_user = api_user();
4288 $api_user = api_get_user(get_app());
4290 if (!empty($_POST['name'])) {
4291 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4292 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4293 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4294 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4297 if (isset($_POST['description'])) {
4298 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4299 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4300 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4303 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4304 // Update global directory in background
4305 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4306 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4309 return api_account_verify_credentials($type);
4312 /// @TODO move to top of file or somewhere better
4313 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4317 * @param string $acl_string
4319 function check_acl_input($acl_string)
4321 if ($acl_string == null || $acl_string == " ") {
4324 $contact_not_found = false;
4326 // split <x><y><z> into array of cid's
4327 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4329 // check for each cid if it is available on server
4330 $cid_array = $array[0];
4331 foreach ($cid_array as $cid) {
4332 $cid = str_replace("<", "", $cid);
4333 $cid = str_replace(">", "", $cid);
4335 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4339 $contact_not_found |= !DBM::is_result($contact);
4341 return $contact_not_found;
4346 * @param string $mediatype
4347 * @param array $media
4348 * @param string $type
4349 * @param string $album
4350 * @param string $allow_cid
4351 * @param string $deny_cid
4352 * @param string $allow_gid
4353 * @param string $deny_gid
4354 * @param string $desc
4355 * @param integer $profile
4356 * @param boolean $visibility
4357 * @param string $photo_id
4359 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)
4367 if (is_array($media)) {
4368 if (is_array($media['tmp_name'])) {
4369 $src = $media['tmp_name'][0];
4371 $src = $media['tmp_name'];
4373 if (is_array($media['name'])) {
4374 $filename = basename($media['name'][0]);
4376 $filename = basename($media['name']);
4378 if (is_array($media['size'])) {
4379 $filesize = intval($media['size'][0]);
4381 $filesize = intval($media['size']);
4383 if (is_array($media['type'])) {
4384 $filetype = $media['type'][0];
4386 $filetype = $media['type'];
4390 if ($filetype == "") {
4391 $filetype=Image::guessType($filename);
4393 $imagedata = getimagesize($src);
4395 $filetype = $imagedata['mime'];
4398 "File upload src: " . $src . " - filename: " . $filename .
4399 " - size: " . $filesize . " - type: " . $filetype,
4403 // check if there was a php upload error
4404 if ($filesize == 0 && $media['error'] == 1) {
4405 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4407 // check against max upload size within Friendica instance
4408 $maximagesize = Config::get('system', 'maximagesize');
4409 if ($maximagesize && ($filesize > $maximagesize)) {
4410 $formattedBytes = formatBytes($maximagesize);
4411 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4414 // create Photo instance with the data of the image
4415 $imagedata = @file_get_contents($src);
4416 $Image = new Image($imagedata, $filetype);
4417 if (! $Image->isValid()) {
4418 throw new InternalServerErrorException("unable to process image data");
4421 // check orientation of image
4422 $Image->orient($src);
4425 // check max length of images on server
4426 $max_length = Config::get('system', 'max_image_length');
4427 if (! $max_length) {
4428 $max_length = MAX_IMAGE_LENGTH;
4430 if ($max_length > 0) {
4431 $Image->scaleDown($max_length);
4432 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4434 $width = $Image->getWidth();
4435 $height = $Image->getHeight();
4437 // create a new resource-id if not already provided
4438 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4440 if ($mediatype == "photo") {
4441 // upload normal image (scales 0, 1, 2)
4442 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4444 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4446 logger("photo upload: image upload with scale 0 (original size) failed");
4448 if ($width > 640 || $height > 640) {
4449 $Image->scaleDown(640);
4450 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4452 logger("photo upload: image upload with scale 1 (640x640) failed");
4456 if ($width > 320 || $height > 320) {
4457 $Image->scaleDown(320);
4458 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4460 logger("photo upload: image upload with scale 2 (320x320) failed");
4463 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4464 } elseif ($mediatype == "profileimage") {
4465 // upload profile image (scales 4, 5, 6)
4466 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4468 if ($width > 175 || $height > 175) {
4469 $Image->scaleDown(175);
4470 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4472 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4476 if ($width > 80 || $height > 80) {
4477 $Image->scaleDown(80);
4478 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4480 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4484 if ($width > 48 || $height > 48) {
4485 $Image->scaleDown(48);
4486 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4488 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4491 $Image->__destruct();
4492 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4495 if (isset($r) && $r) {
4496 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4497 if ($photo_id == null && $mediatype == "photo") {
4498 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4500 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4501 return prepare_photo_data($type, false, $hash);
4503 throw new InternalServerErrorException("image upload failed");
4509 * @param string $hash
4510 * @param string $allow_cid
4511 * @param string $deny_cid
4512 * @param string $allow_gid
4513 * @param string $deny_gid
4514 * @param string $filetype
4515 * @param boolean $visibility
4517 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4519 // get data about the api authenticated user
4520 $uri = Item::newURI(intval(api_user()));
4521 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4524 $arr['guid'] = get_guid(32);
4525 $arr['uid'] = intval(api_user());
4527 $arr['parent-uri'] = $uri;
4528 $arr['type'] = 'photo';
4530 $arr['resource-id'] = $hash;
4531 $arr['contact-id'] = $owner_record[0]['id'];
4532 $arr['owner-name'] = $owner_record[0]['name'];
4533 $arr['owner-link'] = $owner_record[0]['url'];
4534 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4535 $arr['author-name'] = $owner_record[0]['name'];
4536 $arr['author-link'] = $owner_record[0]['url'];
4537 $arr['author-avatar'] = $owner_record[0]['thumb'];
4539 $arr['allow_cid'] = $allow_cid;
4540 $arr['allow_gid'] = $allow_gid;
4541 $arr['deny_cid'] = $deny_cid;
4542 $arr['deny_gid'] = $deny_gid;
4543 $arr['visible'] = $visibility;
4547 'image/jpeg' => 'jpg',
4548 'image/png' => 'png',
4549 'image/gif' => 'gif'
4552 // adds link to the thumbnail scale photo
4553 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4554 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4557 // do the magic for storing the item in the database and trigger the federation to other contacts
4563 * @param string $type
4565 * @param string $photo_id
4569 function prepare_photo_data($type, $scale, $photo_id)
4572 $user_info = api_get_user($a);
4574 if ($user_info === false) {
4575 throw new ForbiddenException();
4578 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4579 $data_sql = ($scale === false ? "" : "data, ");
4581 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4582 // clients needs to convert this in their way for further processing
4584 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4585 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4586 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4587 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4589 intval(local_user()),
4595 'image/jpeg' => 'jpg',
4596 'image/png' => 'png',
4597 'image/gif' => 'gif'
4600 // prepare output data for photo
4601 if (DBM::is_result($r)) {
4602 $data = ['photo' => $r[0]];
4603 $data['photo']['id'] = $data['photo']['resource-id'];
4604 if ($scale !== false) {
4605 $data['photo']['data'] = base64_encode($data['photo']['data']);
4607 unset($data['photo']['datasize']); //needed only with scale param
4609 if ($type == "xml") {
4610 $data['photo']['links'] = [];
4611 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4612 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4614 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4617 $data['photo']['link'] = [];
4618 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4620 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4621 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4625 unset($data['photo']['resource-id']);
4626 unset($data['photo']['minscale']);
4627 unset($data['photo']['maxscale']);
4629 throw new NotFoundException();
4632 // retrieve item element for getting activities (like, dislike etc.) related to photo
4633 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4634 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4636 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4638 // retrieve comments on photo
4639 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4640 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4642 $statuses = Item::selectForUser(api_user(), [], $condition);
4644 // prepare output of comments
4645 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
4647 if ($type == "xml") {
4649 foreach ($commentData as $comment) {
4650 $comments[$k++ . ":comment"] = $comment;
4653 foreach ($commentData as $comment) {
4654 $comments[] = $comment;
4657 $data['photo']['friendica_comments'] = $comments;
4659 // include info if rights on photo and rights on item are mismatching
4660 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4661 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4662 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4663 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4664 $data['photo']['rights_mismatch'] = $rights_mismatch;
4671 * Similar as /mod/redir.php
4672 * redirect to 'url' after dfrn auth
4674 * Why this when there is mod/redir.php already?
4675 * This use api_user() and api_login()
4678 * c_url: url of remote contact to auth to
4679 * url: string, url to redirect after auth
4681 function api_friendica_remoteauth()
4683 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4684 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4686 if ($url === '' || $c_url === '') {
4687 throw new BadRequestException("Wrong parameters.");
4690 $c_url = normalise_link($c_url);
4694 $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4696 if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
4697 throw new BadRequestException("Unknown contact");
4700 $cid = $contact['id'];
4702 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4704 if ($contact['duplex'] && $contact['issued-id']) {
4705 $orig_id = $contact['issued-id'];
4706 $dfrn_id = '1:' . $orig_id;
4708 if ($contact['duplex'] && $contact['dfrn-id']) {
4709 $orig_id = $contact['dfrn-id'];
4710 $dfrn_id = '0:' . $orig_id;
4713 $sec = random_string();
4715 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4716 'sec' => $sec, 'expire' => time() + 45];
4717 dba::insert('profile_check', $fields);
4719 logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
4720 $dest = ($url ? '&destination_url=' . $url : '');
4722 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4723 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4724 . '&type=profile&sec=' . $sec . $dest
4727 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4730 * @brief Return the item shared, if the item contains only the [share] tag
4732 * @param array $item Sharer item
4733 * @return array|false Shared item or false if not a reshare
4735 function api_share_as_retweet(&$item)
4737 $body = trim($item["body"]);
4739 if (Diaspora::isReshare($body, false)===false) {
4743 /// @TODO "$1" should maybe mean '$1' ?
4744 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4746 * Skip if there is no shared message in there
4747 * we already checked this in diaspora::isReshare()
4748 * but better one more than one less...
4750 if ($body == $attributes) {
4755 // build the fake reshared item
4756 $reshared_item = $item;
4759 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4760 if ($matches[1] != "") {
4761 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4764 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4765 if ($matches[1] != "") {
4766 $author = $matches[1];
4770 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4771 if ($matches[1] != "") {
4772 $profile = $matches[1];
4775 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4776 if ($matches[1] != "") {
4777 $profile = $matches[1];
4781 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4782 if ($matches[1] != "") {
4783 $avatar = $matches[1];
4786 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4787 if ($matches[1] != "") {
4788 $avatar = $matches[1];
4792 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4793 if ($matches[1] != "") {
4794 $link = $matches[1];
4797 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4798 if ($matches[1] != "") {
4799 $link = $matches[1];
4803 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4804 if ($matches[1] != "") {
4805 $posted = $matches[1];
4808 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4809 if ($matches[1] != "") {
4810 $posted = $matches[1];
4813 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4815 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4819 $reshared_item["body"] = $shared_body;
4820 $reshared_item["author-name"] = $author;
4821 $reshared_item["author-link"] = $profile;
4822 $reshared_item["author-avatar"] = $avatar;
4823 $reshared_item["plink"] = $link;
4824 $reshared_item["created"] = $posted;
4825 $reshared_item["edited"] = $posted;
4827 return $reshared_item;
4832 * @param string $profile
4834 * @return string|false
4835 * @todo remove trailing junk from profile url
4836 * @todo pump.io check has to check the website
4838 function api_get_nick($profile)
4843 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4844 dbesc(normalise_link($profile))
4847 if (DBM::is_result($r)) {
4848 $nick = $r[0]["nick"];
4853 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4854 dbesc(normalise_link($profile))
4857 if (DBM::is_result($r)) {
4858 $nick = $r[0]["nick"];
4863 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4864 if ($friendica != $profile) {
4870 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4871 if ($diaspora != $profile) {
4877 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4878 if ($twitter != $profile) {
4885 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4886 if ($StatusnetHost != $profile) {
4887 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4888 if ($StatusnetUser != $profile) {
4889 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4890 $user = json_decode($UserData);
4892 $nick = $user->screen_name;
4898 // To-Do: look at the page if its really a pumpio site
4899 //if (!$nick == "") {
4900 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4901 // if ($pumpio != $profile)
4903 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4916 * @param array $item
4920 function api_in_reply_to($item)
4924 $in_reply_to['status_id'] = null;
4925 $in_reply_to['user_id'] = null;
4926 $in_reply_to['status_id_str'] = null;
4927 $in_reply_to['user_id_str'] = null;
4928 $in_reply_to['screen_name'] = null;
4930 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4931 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
4932 if (DBM::is_result($parent)) {
4933 $in_reply_to['status_id'] = intval($parent['id']);
4935 $in_reply_to['status_id'] = intval($item['parent']);
4938 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4940 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
4941 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
4943 if (DBM::is_result($parent)) {
4944 if ($parent['author-nick'] == "") {
4945 $parent['author-nick'] = api_get_nick($parent['author-link']);
4948 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
4949 $in_reply_to['user_id'] = intval($parent['author-id']);
4950 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
4953 // There seems to be situation, where both fields are identical:
4954 // https://github.com/friendica/friendica/issues/1010
4955 // This is a bugfix for that.
4956 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4957 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4958 $in_reply_to['status_id'] = null;
4959 $in_reply_to['user_id'] = null;
4960 $in_reply_to['status_id_str'] = null;
4961 $in_reply_to['user_id_str'] = null;
4962 $in_reply_to['screen_name'] = null;
4966 return $in_reply_to;
4971 * @param string $text
4975 function api_clean_plain_items($text)
4977 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4979 $text = BBCode::cleanPictureLinks($text);
4980 $URLSearchString = "^\[\]";
4982 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4984 if ($include_entities == "true") {
4985 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4988 // Simplify "attachment" element
4989 $text = api_clean_attachments($text);
4995 * @brief Removes most sharing information for API text export
4997 * @param string $body The original body
4999 * @return string Cleaned body
5001 function api_clean_attachments($body)
5003 $data = BBCode::getAttachmentData($body);
5010 if (isset($data["text"])) {
5011 $body = $data["text"];
5013 if (($body == "") && isset($data["title"])) {
5014 $body = $data["title"];
5016 if (isset($data["url"])) {
5017 $body .= "\n".$data["url"];
5019 $body .= $data["after"];
5026 * @param array $contacts
5030 function api_best_nickname(&$contacts)
5034 if (count($contacts) == 0) {
5038 foreach ($contacts as $contact) {
5039 if ($contact["network"] == "") {
5040 $contact["network"] = "dfrn";
5041 $best_contact = [$contact];
5045 if (sizeof($best_contact) == 0) {
5046 foreach ($contacts as $contact) {
5047 if ($contact["network"] == "dfrn") {
5048 $best_contact = [$contact];
5053 if (sizeof($best_contact) == 0) {
5054 foreach ($contacts as $contact) {
5055 if ($contact["network"] == "dspr") {
5056 $best_contact = [$contact];
5061 if (sizeof($best_contact) == 0) {
5062 foreach ($contacts as $contact) {
5063 if ($contact["network"] == "stat") {
5064 $best_contact = [$contact];
5069 if (sizeof($best_contact) == 0) {
5070 foreach ($contacts as $contact) {
5071 if ($contact["network"] == "pump") {
5072 $best_contact = [$contact];
5077 if (sizeof($best_contact) == 0) {
5078 foreach ($contacts as $contact) {
5079 if ($contact["network"] == "twit") {
5080 $best_contact = [$contact];
5085 if (sizeof($best_contact) == 1) {
5086 $contacts = $best_contact;
5088 $contacts = [$contacts[0]];
5093 * Return all or a specified group of the user with the containing contacts.
5095 * @param string $type Return type (atom, rss, xml, json)
5097 * @return array|string
5099 function api_friendica_group_show($type)
5103 if (api_user() === false) {
5104 throw new ForbiddenException();
5108 $user_info = api_get_user($a);
5109 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5110 $uid = $user_info['uid'];
5112 // get data of the specified group id or all groups if not specified
5115 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5119 // error message if specified gid is not in database
5120 if (!DBM::is_result($r)) {
5121 throw new BadRequestException("gid not available");
5125 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5130 // loop through all groups and retrieve all members for adding data in the user array
5132 foreach ($r as $rr) {
5133 $members = Contact::getByGroupId($rr['id']);
5136 if ($type == "xml") {
5137 $user_element = "users";
5139 foreach ($members as $member) {
5140 $user = api_get_user($a, $member['nurl']);
5141 $users[$k++.":user"] = $user;
5144 $user_element = "user";
5145 foreach ($members as $member) {
5146 $user = api_get_user($a, $member['nurl']);
5150 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5152 return api_format_data("groups", $type, ['group' => $grps]);
5154 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5158 * Delete the specified group of the user.
5160 * @param string $type Return type (atom, rss, xml, json)
5162 * @return array|string
5164 function api_friendica_group_delete($type)
5168 if (api_user() === false) {
5169 throw new ForbiddenException();
5173 $user_info = api_get_user($a);
5174 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5175 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5176 $uid = $user_info['uid'];
5178 // error if no gid specified
5179 if ($gid == 0 || $name == "") {
5180 throw new BadRequestException('gid or name not specified');
5183 // get data of the specified group id
5185 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5189 // error message if specified gid is not in database
5190 if (!DBM::is_result($r)) {
5191 throw new BadRequestException('gid not available');
5194 // get data of the specified group id and group name
5196 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5201 // error message if specified gid is not in database
5202 if (!DBM::is_result($rname)) {
5203 throw new BadRequestException('wrong group name');
5207 $ret = Group::removeByName($uid, $name);
5210 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5211 return api_format_data("group_delete", $type, ['result' => $success]);
5213 throw new BadRequestException('other API error');
5216 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5221 * @param string $type Return type (atom, rss, xml, json)
5223 * @return array|string
5224 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5226 function api_lists_destroy($type)
5230 if (api_user() === false) {
5231 throw new ForbiddenException();
5235 $user_info = api_get_user($a);
5236 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5237 $uid = $user_info['uid'];
5239 // error if no gid specified
5241 throw new BadRequestException('gid not specified');
5244 // get data of the specified group id
5245 $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5246 // error message if specified gid is not in database
5248 throw new BadRequestException('gid not available');
5251 if (Group::remove($gid)) {
5253 'name' => $group['name'],
5254 'id' => intval($gid),
5255 'id_str' => (string) $gid,
5256 'user' => $user_info
5259 return api_format_data("lists", $type, ['lists' => $list]);
5262 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5265 * Add a new group to the database.
5267 * @param string $name Group name
5268 * @param int $uid User ID
5269 * @param array $users List of users to add to the group
5273 function group_create($name, $uid, $users = [])
5275 // error if no name specified
5277 throw new BadRequestException('group name not specified');
5280 // get data of the specified group name
5282 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5286 // error message if specified group name already exists
5287 if (DBM::is_result($rname)) {
5288 throw new BadRequestException('group name already exists');
5291 // check if specified group name is a deleted group
5293 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5297 // error message if specified group name already exists
5298 if (DBM::is_result($rname)) {
5299 $reactivate_group = true;
5303 $ret = Group::create($uid, $name);
5305 $gid = Group::getIdByName($uid, $name);
5307 throw new BadRequestException('other API error');
5311 $erroraddinguser = false;
5313 foreach ($users as $user) {
5314 $cid = $user['cid'];
5315 // check if user really exists as contact
5317 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5321 if (count($contact)) {
5322 Group::addMember($gid, $cid);
5324 $erroraddinguser = true;
5325 $errorusers[] = $cid;
5329 // return success message incl. missing users in array
5330 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5332 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5336 * Create the specified group with the posted array of contacts.
5338 * @param string $type Return type (atom, rss, xml, json)
5340 * @return array|string
5342 function api_friendica_group_create($type)
5346 if (api_user() === false) {
5347 throw new ForbiddenException();
5351 $user_info = api_get_user($a);
5352 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5353 $uid = $user_info['uid'];
5354 $json = json_decode($_POST['json'], true);
5355 $users = $json['user'];
5357 $success = group_create($name, $uid, $users);
5359 return api_format_data("group_create", $type, ['result' => $success]);
5361 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5364 * Create a new group.
5366 * @param string $type Return type (atom, rss, xml, json)
5368 * @return array|string
5369 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5371 function api_lists_create($type)
5375 if (api_user() === false) {
5376 throw new ForbiddenException();
5380 $user_info = api_get_user($a);
5381 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5382 $uid = $user_info['uid'];
5384 $success = group_create($name, $uid);
5385 if ($success['success']) {
5387 'name' => $success['name'],
5388 'id' => intval($success['gid']),
5389 'id_str' => (string) $success['gid'],
5390 'user' => $user_info
5393 return api_format_data("lists", $type, ['lists'=>$grp]);
5396 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5399 * Update the specified group with the posted array of contacts.
5401 * @param string $type Return type (atom, rss, xml, json)
5403 * @return array|string
5405 function api_friendica_group_update($type)
5409 if (api_user() === false) {
5410 throw new ForbiddenException();
5414 $user_info = api_get_user($a);
5415 $uid = $user_info['uid'];
5416 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5417 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5418 $json = json_decode($_POST['json'], true);
5419 $users = $json['user'];
5421 // error if no name specified
5423 throw new BadRequestException('group name not specified');
5426 // error if no gid specified
5428 throw new BadRequestException('gid not specified');
5432 $members = Contact::getByGroupId($gid);
5433 foreach ($members as $member) {
5434 $cid = $member['id'];
5435 foreach ($users as $user) {
5436 $found = ($user['cid'] == $cid ? true : false);
5438 if (!isset($found) || !$found) {
5439 Group::removeMemberByName($uid, $name, $cid);
5444 $erroraddinguser = false;
5446 foreach ($users as $user) {
5447 $cid = $user['cid'];
5448 // check if user really exists as contact
5450 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5455 if (count($contact)) {
5456 Group::addMember($gid, $cid);
5458 $erroraddinguser = true;
5459 $errorusers[] = $cid;
5463 // return success message incl. missing users in array
5464 $status = ($erroraddinguser ? "missing user" : "ok");
5465 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5466 return api_format_data("group_update", $type, ['result' => $success]);
5469 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5472 * Update information about a group.
5474 * @param string $type Return type (atom, rss, xml, json)
5476 * @return array|string
5477 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5479 function api_lists_update($type)
5483 if (api_user() === false) {
5484 throw new ForbiddenException();
5488 $user_info = api_get_user($a);
5489 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5490 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5491 $uid = $user_info['uid'];
5493 // error if no gid specified
5495 throw new BadRequestException('gid not specified');
5498 // get data of the specified group id
5499 $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5500 // error message if specified gid is not in database
5502 throw new BadRequestException('gid not available');
5505 if (Group::update($gid, $name)) {
5508 'id' => intval($gid),
5509 'id_str' => (string) $gid,
5510 'user' => $user_info
5513 return api_format_data("lists", $type, ['lists' => $list]);
5517 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5521 * @param string $type Return type (atom, rss, xml, json)
5523 * @return array|string
5525 function api_friendica_activity($type)
5529 if (api_user() === false) {
5530 throw new ForbiddenException();
5532 $verb = strtolower($a->argv[3]);
5533 $verb = preg_replace("|\..*$|", "", $verb);
5535 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5537 $res = Item::performLike($id, $verb);
5540 if ($type == "xml") {
5545 return api_format_data('ok', $type, ['ok' => $ok]);
5547 throw new BadRequestException('Error adding activity');
5551 /// @TODO move to top of file or somewhere better
5552 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5553 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5554 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5555 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5556 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5557 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5558 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5559 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5560 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5561 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5564 * @brief Returns notifications
5566 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5567 * @return string|array
5569 function api_friendica_notification($type)
5573 if (api_user() === false) {
5574 throw new ForbiddenException();
5577 throw new BadRequestException("Invalid argument count");
5579 $nm = new NotificationsManager();
5581 $notes = $nm->getAll([], "+seen -date", 50);
5583 if ($type == "xml") {
5585 foreach ($notes as $note) {
5586 $xmlnotes[] = ["@attributes" => $note];
5592 return api_format_data("notes", $type, ['note' => $notes]);
5596 * POST request with 'id' param as notification id
5598 * @brief Set notification as seen and returns associated item (if possible)
5600 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5601 * @return string|array
5603 function api_friendica_notification_seen($type)
5606 $user_info = api_get_user($a);
5608 if (api_user() === false || $user_info === false) {
5609 throw new ForbiddenException();
5612 throw new BadRequestException("Invalid argument count");
5615 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5617 $nm = new NotificationsManager();
5618 $note = $nm->getByID($id);
5619 if (is_null($note)) {
5620 throw new BadRequestException("Invalid argument");
5623 $nm->setSeen($note);
5624 if ($note['otype']=='item') {
5625 // would be really better with an ItemsManager and $im->getByID() :-P
5626 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5627 if (DBM::is_result($$item)) {
5628 // we found the item, return it to the user
5629 $ret = api_format_items([$item], $user_info, false, $type);
5630 $data = ['status' => $ret];
5631 return api_format_data("status", $type, $data);
5633 // the item can't be found, but we set the note as seen, so we count this as a success
5635 return api_format_data('result', $type, ['result' => "success"]);
5638 /// @TODO move to top of file or somewhere better
5639 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5640 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5643 * @brief update a direct_message to seen state
5645 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5646 * @return string|array (success result=ok, error result=error with error message)
5648 function api_friendica_direct_messages_setseen($type)
5651 if (api_user() === false) {
5652 throw new ForbiddenException();
5656 $user_info = api_get_user($a);
5657 $uid = $user_info['uid'];
5658 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5660 // return error if id is zero
5662 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5663 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5666 // error message if specified id is not in database
5667 if (!dba::exists('mail', ['id' => $id, 'uid' => $uid])) {
5668 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5669 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5672 // update seen indicator
5673 $result = dba::update('mail', ['seen' => true], ['id' => $id]);
5677 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5678 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5680 $answer = ['result' => 'error', 'message' => 'unknown error'];
5681 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5685 /// @TODO move to top of file or somewhere better
5686 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5689 * @brief search for direct_messages containing a searchstring through api
5691 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5692 * @param string $box
5693 * @return string|array (success: success=true if found and search_result contains found messages,
5694 * success=false if nothing was found, search_result='nothing found',
5695 * error: result=error with error message)
5697 function api_friendica_direct_messages_search($type, $box = "")
5701 if (api_user() === false) {
5702 throw new ForbiddenException();
5706 $user_info = api_get_user($a);
5707 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5708 $uid = $user_info['uid'];
5710 // error if no searchstring specified
5711 if ($searchstring == "") {
5712 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5713 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5716 // get data for the specified searchstring
5718 "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",
5720 dbesc('%'.$searchstring.'%')
5723 $profile_url = $user_info["url"];
5725 // message if nothing was found
5726 if (!DBM::is_result($r)) {
5727 $success = ['success' => false, 'search_results' => 'problem with query'];
5728 } elseif (count($r) == 0) {
5729 $success = ['success' => false, 'search_results' => 'nothing found'];
5732 foreach ($r as $item) {
5733 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5734 $recipient = $user_info;
5735 $sender = api_get_user($a, normalise_link($item['contact-url']));
5736 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5737 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5738 $sender = $user_info;
5741 if (isset($recipient) && isset($sender)) {
5742 $ret[] = api_format_messages($item, $recipient, $sender);
5745 $success = ['success' => true, 'search_results' => $ret];
5748 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5751 /// @TODO move to top of file or somewhere better
5752 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5755 * @brief return data of all the profiles a user has to the client
5757 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5758 * @return string|array
5760 function api_friendica_profile_show($type)
5764 if (api_user() === false) {
5765 throw new ForbiddenException();
5769 $profile_id = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5771 // retrieve general information about profiles for user
5772 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5773 $directory = Config::get('system', 'directory');
5775 // get data of the specified profile id or all profiles of the user if not specified
5776 if ($profile_id != 0) {
5778 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5783 // error message if specified gid is not in database
5784 if (!DBM::is_result($r)) {
5785 throw new BadRequestException("profile_id not available");
5789 "SELECT * FROM `profile` WHERE `uid` = %d",
5793 // loop through all returned profiles and retrieve data and users
5796 foreach ($r as $rr) {
5797 $profile = api_format_items_profiles($rr);
5799 // select all users from contact table, loop and prepare standard return for user data
5802 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5804 intval($rr['profile_id'])
5807 foreach ($nurls as $nurl) {
5808 $user = api_get_user($a, $nurl['nurl']);
5809 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5811 $profile['users'] = $users;
5813 // add prepared profile data to array for final return
5814 if ($type == "xml") {
5815 $profiles[$k++ . ":profile"] = $profile;
5817 $profiles[] = $profile;
5821 // return settings, authenticated user and profiles data
5822 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5824 $result = ['multi_profiles' => $multi_profiles ? true : false,
5825 'global_dir' => $directory,
5826 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5827 'profiles' => $profiles];
5828 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5830 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5833 * Returns a list of saved searches.
5835 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5837 * @param string $type Return format: json or xml
5839 * @return string|array
5841 function api_saved_searches_list($type)
5843 $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
5846 while ($term = $terms->fetch()) {
5848 'created_at' => api_date(time()),
5849 'id' => intval($term['id']),
5850 'id_str' => $term['id'],
5851 'name' => $term['term'],
5853 'query' => $term['term']
5859 return api_format_data("terms", $type, ['terms' => $result]);
5862 /// @TODO move to top of file or somewhere better
5863 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5866 @TODO Maybe open to implement?
5868 [pagename] => api/1.1/statuses/lookup.json
5869 [id] => 605138389168451584
5870 [include_cards] => true
5871 [cards_platform] => Android-12
5872 [include_entities] => true
5873 [include_my_retweet] => 1
5875 [include_reply_count] => true
5876 [include_descendent_reply_count] => true
5880 Not implemented by now:
5881 statuses/retweets_of_me
5886 account/update_location
5887 account/update_profile_background_image
5890 friendica/profile/update
5891 friendica/profile/create
5892 friendica/profile/delete
5894 Not implemented in status.net:
5895 statuses/retweeted_to_me
5896 statuses/retweeted_by_me
5897 direct_messages/destroy
5899 account/update_delivery_device
5900 notifications/follow