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 (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
97 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
103 * @brief Format date for API
105 * @param string $str Source date, as UTC
106 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
108 function api_date($str)
110 // Wed May 23 06:01:13 +0000 2007
111 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
115 * Register a function to be the endpoint for defined API path.
117 * @brief Register API endpoint
119 * @param string $path API URL path, relative to System::baseUrl()
120 * @param string $func Function name to call on path request
121 * @param bool $auth API need logged user
122 * @param string $method HTTP method reqiured to call this endpoint.
123 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
124 * Default to API_METHOD_ANY
126 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
136 // Workaround for hotot
137 $path = str_replace("api/", "api/1.1/", $path);
147 * Log in user via OAuth1 or Simple HTTP Auth.
148 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
150 * @brief Login API user
152 * @param object $a App
153 * @hook 'authenticate'
155 * 'username' => username from login form
156 * 'password' => password from login form
157 * 'authenticated' => return status,
158 * 'user_record' => return authenticated user record
160 * array $user logged user record
162 function api_login(App $a)
164 $oauth1 = new FKOAuth1();
167 list($consumer, $token) = $oauth1->verify_request(OAuthRequest::from_request());
168 if (!is_null($token)) {
169 $oauth1->loginUser($token->uid);
170 Addon::callHooks('logged_in', $a->user);
173 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
174 var_dump($consumer, $token);
176 } catch (Exception $e) {
180 // workaround for HTTP-auth in CGI mode
181 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
182 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
183 if (strlen($userpass)) {
184 list($name, $password) = explode(':', $userpass);
185 $_SERVER['PHP_AUTH_USER'] = $name;
186 $_SERVER['PHP_AUTH_PW'] = $password;
190 if (!x($_SERVER, 'PHP_AUTH_USER')) {
191 logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
192 header('WWW-Authenticate: Basic realm="Friendica"');
193 throw new UnauthorizedException("This API requires login");
196 $user = $_SERVER['PHP_AUTH_USER'];
197 $password = $_SERVER['PHP_AUTH_PW'];
199 // allow "user@server" login (but ignore 'server' part)
200 $at = strstr($user, "@", true);
205 // next code from mod/auth.php. needs better solution
209 'username' => trim($user),
210 'password' => trim($password),
211 'authenticated' => 0,
212 'user_record' => null,
216 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
217 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
218 * and later addons should not interfere with an earlier one that succeeded.
220 Addon::callHooks('authenticate', $addon_auth);
222 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
223 $record = $addon_auth['user_record'];
225 $user_id = User::authenticate(trim($user), trim($password));
226 if ($user_id !== false) {
227 $record = dba::selectFirst('user', [], ['uid' => $user_id]);
231 if (!DBM::is_result($record)) {
232 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
233 header('WWW-Authenticate: Basic realm="Friendica"');
234 //header('HTTP/1.0 401 Unauthorized');
235 //die('This api requires login');
236 throw new UnauthorizedException("This API requires login");
239 authenticate_success($record);
241 $_SESSION["allow_api"] = true;
243 Addon::callHooks('logged_in', $a->user);
247 * API endpoints can define which HTTP method to accept when called.
248 * This function check the current HTTP method agains endpoint
251 * @brief Check HTTP method of called API
253 * @param string $method Required methods, uppercase, separated by comma
256 function api_check_method($method)
258 if ($method == "*") {
261 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
265 * Authenticate user, call registered API function, set HTTP headers
267 * @brief Main API entry point
269 * @param object $a App
270 * @return string|array API call result
272 function api_call(App $a)
274 global $API, $called_api;
277 if (strpos($a->query_string, ".xml") > 0) {
280 if (strpos($a->query_string, ".json") > 0) {
283 if (strpos($a->query_string, ".rss") > 0) {
286 if (strpos($a->query_string, ".atom") > 0) {
291 foreach ($API as $p => $info) {
292 if (strpos($a->query_string, $p) === 0) {
293 if (!api_check_method($info['method'])) {
294 throw new MethodNotAllowedException();
297 $called_api = explode("/", $p);
298 //unset($_SERVER['PHP_AUTH_USER']);
300 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
301 if ($info['auth'] === true && api_user() === false) {
305 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
306 logger('API parameters: ' . print_r($_REQUEST, true));
308 $stamp = microtime(true);
309 $return = call_user_func($info['func'], $type);
310 $duration = (float) (microtime(true) - $stamp);
311 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
313 if (Config::get("system", "profiler")) {
314 $duration = microtime(true)-$a->performance["start"];
316 /// @TODO round() really everywhere?
318 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
319 "Database: %s/%s, Cache %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
320 round($a->performance["database"] - $a->performance["database_write"], 3),
321 round($a->performance["database_write"], 3),
322 round($a->performance["cache"], 3),
323 round($a->performance["cache_write"], 3),
324 round($a->performance["network"], 2),
325 round($a->performance["file"], 2),
326 round($duration - ($a->performance["database"]
327 + $a->performance["cache"] + $a->performance["cache_write"]
328 + $a->performance["network"] + $a->performance["file"]), 2),
334 if (Config::get("rendertime", "callstack")) {
335 $o = "Database Read:\n";
336 foreach ($a->callstack["database"] as $func => $time) {
337 $time = round($time, 3);
339 $o .= $func . ": " . $time . "\n";
342 $o .= "\nDatabase Write:\n";
343 foreach ($a->callstack["database_write"] as $func => $time) {
344 $time = round($time, 3);
346 $o .= $func . ": " . $time . "\n";
350 $o = "Cache Read:\n";
351 foreach ($a->callstack["cache"] as $func => $time) {
352 $time = round($time, 3);
354 $o .= $func . ": " . $time . "\n";
357 $o .= "\nCache Write:\n";
358 foreach ($a->callstack["cache_write"] as $func => $time) {
359 $time = round($time, 3);
361 $o .= $func . ": " . $time . "\n";
365 $o .= "\nNetwork:\n";
366 foreach ($a->callstack["network"] as $func => $time) {
367 $time = round($time, 3);
369 $o .= $func . ": " . $time . "\n";
372 logger($o, LOGGER_DEBUG);
376 if (false === $return) {
378 * api function returned false withour throw an
379 * exception. This should not happend, throw a 500
381 throw new InternalServerErrorException();
386 header("Content-Type: text/xml");
389 header("Content-Type: application/json");
390 $json = json_encode(end($return));
391 if (x($_GET, 'callback')) {
392 $json = $_GET['callback'] . "(" . $json . ")";
397 header("Content-Type: application/rss+xml");
398 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
401 header("Content-Type: application/atom+xml");
402 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
409 logger('API call not implemented: ' . $a->query_string);
410 throw new NotImplementedException();
411 } catch (HTTPException $e) {
412 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
413 return api_error($type, $e);
418 * @brief Format API error string
420 * @param string $type Return type (xml, json, rss, as)
421 * @param object $e HTTPException Error object
422 * @return string|array error message formatted as $type
424 function api_error($type, $e)
428 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
429 /// @TODO: https://dev.twitter.com/overview/api/response-codes
431 $error = ["error" => $error,
432 "code" => $e->httpcode . " " . $e->httpdesc,
433 "request" => $a->query_string];
435 $return = api_format_data('status', $type, ['status' => $error]);
439 header("Content-Type: text/xml");
442 header("Content-Type: application/json");
443 $return = json_encode($return);
446 header("Content-Type: application/rss+xml");
449 header("Content-Type: application/atom+xml");
457 * @brief Set values for RSS template
460 * @param array $arr Array to be passed to template
461 * @param array $user_info User info
463 * @todo find proper type-hints
465 function api_rss_extra(App $a, $arr, $user_info)
467 if (is_null($user_info)) {
468 $user_info = api_get_user($a);
471 $arr['$user'] = $user_info;
473 'alternate' => $user_info['url'],
474 'self' => System::baseUrl() . "/" . $a->query_string,
475 'base' => System::baseUrl(),
476 'updated' => api_date(null),
477 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
478 'language' => $user_info['language'],
479 'logo' => System::baseUrl() . "/images/friendica-32.png",
487 * @brief Unique contact to contact url.
489 * @param int $id Contact id
490 * @return bool|string
491 * Contact url or False if contact id is unknown
493 function api_unique_id_to_nurl($id)
495 $r = dba::selectFirst('contact', ['nurl'], ['id' => $id]);
497 if (DBM::is_result($r)) {
505 * @brief Get user info array.
507 * @param object $a App
508 * @param int|string $contact_id Contact ID or URL
510 function api_get_user(App $a, $contact_id = null)
518 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
520 // Searching for contact URL
521 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
522 $user = dbesc(normalise_link($contact_id));
524 $extra_query = "AND `contact`.`nurl` = '%s' ";
525 if (api_user() !== false) {
526 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
530 // Searching for contact id with uid = 0
531 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
532 $user = dbesc(api_unique_id_to_nurl(intval($contact_id)));
535 throw new BadRequestException("User ID ".$contact_id." not found.");
539 $extra_query = "AND `contact`.`nurl` = '%s' ";
540 if (api_user() !== false) {
541 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
545 if (is_null($user) && x($_GET, 'user_id')) {
546 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
549 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
553 $extra_query = "AND `contact`.`nurl` = '%s' ";
554 if (api_user() !== false) {
555 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
558 if (is_null($user) && x($_GET, 'screen_name')) {
559 $user = dbesc($_GET['screen_name']);
560 $extra_query = "AND `contact`.`nick` = '%s' ";
561 if (api_user() !== false) {
562 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
566 if (is_null($user) && x($_GET, 'profileurl')) {
567 $user = dbesc(normalise_link($_GET['profileurl']));
568 $extra_query = "AND `contact`.`nurl` = '%s' ";
569 if (api_user() !== false) {
570 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
574 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
575 $argid = count($called_api);
576 list($user, $null) = explode(".", $a->argv[$argid]);
577 if (is_numeric($user)) {
578 $user = dbesc(api_unique_id_to_nurl(intval($user)));
582 $extra_query = "AND `contact`.`nurl` = '%s' ";
583 if (api_user() !== false) {
584 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
588 $user = dbesc($user);
589 $extra_query = "AND `contact`.`nick` = '%s' ";
590 if (api_user() !== false) {
591 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
596 logger("api_get_user: user ".$user, LOGGER_DEBUG);
599 if (api_user() === false) {
603 $user = $_SESSION['uid'];
604 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
608 logger('api_user: ' . $extra_query . ', user: ' . $user);
612 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
618 // Selecting the id by priority, friendica first
619 if (is_array($uinfo)) {
620 api_best_nickname($uinfo);
623 // if the contact wasn't found, fetch it from the contacts with uid = 0
624 if (!DBM::is_result($uinfo)) {
628 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
631 if (DBM::is_result($r)) {
632 $network_name = ContactSelector::networkToName($r[0]['network'], $r[0]['url']);
634 // If no nick where given, extract it from the address
635 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
636 $r[0]['nick'] = api_get_nick($r[0]["url"]);
641 'id_str' => (string) $r[0]["id"],
642 'name' => $r[0]["name"],
643 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
644 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
645 'description' => $r[0]["about"],
646 'profile_image_url' => $r[0]["micro"],
647 'profile_image_url_https' => $r[0]["micro"],
648 'profile_image_url_profile_size' => $r[0]["thumb"],
649 'profile_image_url_large' => $r[0]["photo"],
650 'url' => $r[0]["url"],
651 'protected' => false,
652 'followers_count' => 0,
653 'friends_count' => 0,
655 'created_at' => api_date($r[0]["created"]),
656 'favourites_count' => 0,
658 'time_zone' => 'UTC',
659 'geo_enabled' => false,
661 'statuses_count' => 0,
663 'contributors_enabled' => false,
664 'is_translator' => false,
665 'is_translation_enabled' => false,
666 'following' => false,
667 'follow_request_sent' => false,
668 'statusnet_blocking' => false,
669 'notifications' => false,
670 'statusnet_profile_url' => $r[0]["url"],
672 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
673 'pid' => Contact::getIdForURL($r[0]["url"], 0, true),
675 'network' => $r[0]["network"],
680 throw new BadRequestException("User ".$url." not found.");
684 if ($uinfo[0]['self']) {
685 if ($uinfo[0]['network'] == "") {
686 $uinfo[0]['network'] = NETWORK_DFRN;
689 $usr = dba::selectFirst('user', ['default-location'], ['uid' => api_user()]);
690 $profile = dba::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
697 // Add a nick if it isn't present there
698 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
699 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
702 $network_name = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
704 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
706 if (!empty($profile['about'])) {
707 $description = $profile['about'];
709 $description = $uinfo[0]["about"];
712 if (!empty($usr['default-location'])) {
713 $location = $usr['default-location'];
714 } elseif (!empty($uinfo[0]["location"])) {
715 $location = $uinfo[0]["location"];
717 $location = $network_name;
721 'id' => intval($pcontact_id),
722 'id_str' => (string) intval($pcontact_id),
723 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
724 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
725 'location' => $location,
726 'description' => $description,
727 'profile_image_url' => $uinfo[0]['micro'],
728 'profile_image_url_https' => $uinfo[0]['micro'],
729 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
730 'profile_image_url_large' => $uinfo[0]["photo"],
731 'url' => $uinfo[0]['url'],
732 'protected' => false,
733 'followers_count' => intval($countfollowers),
734 'friends_count' => intval($countfriends),
736 'created_at' => api_date($uinfo[0]['created']),
737 'favourites_count' => intval($starred),
739 'time_zone' => 'UTC',
740 'geo_enabled' => false,
742 'statuses_count' => intval($countitms),
744 'contributors_enabled' => false,
745 'is_translator' => false,
746 'is_translation_enabled' => false,
747 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
748 'follow_request_sent' => false,
749 'statusnet_blocking' => false,
750 'notifications' => false,
752 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
753 'statusnet_profile_url' => $uinfo[0]['url'],
754 'uid' => intval($uinfo[0]['uid']),
755 'cid' => intval($uinfo[0]['cid']),
756 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
757 'self' => $uinfo[0]['self'],
758 'network' => $uinfo[0]['network'],
761 // If this is a local user and it uses Frio, we can get its color preferences.
763 $theme_info = dba::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
764 if ($theme_info['theme'] === 'frio') {
765 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
766 if ($schema && ($schema != '---')) {
767 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
768 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
769 require_once $schemefile;
772 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
773 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
774 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
780 $link_color = "#6fdbe8";
783 $bgcolor = "#ededed";
786 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
787 $ret['profile_link_color'] = str_replace('#', '', $link_color);
788 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
796 * @brief return api-formatted array for item's author and owner
798 * @param object $a App
799 * @param array $item item from db
800 * @return array(array:author, array:owner)
802 function api_item_get_user(App $a, $item)
804 $status_user = api_get_user($a, $item["author-id"]);
806 $status_user["protected"] = $item["private"];
808 if ($item['thr-parent'] == $item['uri']) {
809 $owner_user = api_get_user($a, $item["owner-id"]);
811 $owner_user = $status_user;
814 return ([$status_user, $owner_user]);
818 * @brief walks recursively through an array with the possibility to change value and key
820 * @param array $array The array to walk through
821 * @param string $callback The callback function
823 * @return array the transformed array
825 function api_walk_recursive(array &$array, callable $callback)
829 foreach ($array as $k => $v) {
831 if ($callback($v, $k)) {
832 $new_array[$k] = api_walk_recursive($v, $callback);
835 if ($callback($v, $k)) {
846 * @brief Callback function to transform the array in an array that can be transformed in a XML file
848 * @param mixed $item Array item value
849 * @param string $key Array key
851 * @return boolean Should the array item be deleted?
853 function api_reformat_xml(&$item, &$key)
855 if (is_bool($item)) {
856 $item = ($item ? "true" : "false");
859 if (substr($key, 0, 10) == "statusnet_") {
860 $key = "statusnet:".substr($key, 10);
861 } elseif (substr($key, 0, 10) == "friendica_") {
862 $key = "friendica:".substr($key, 10);
864 /// @TODO old-lost code?
866 // $key = "default:".$key;
872 * @brief Creates the XML from a JSON style array
874 * @param array $data JSON style array
875 * @param string $root_element Name of the root element
877 * @return string The XML data
879 function api_create_xml(array $data, $root_element)
881 $childname = key($data);
882 $data2 = array_pop($data);
885 $namespaces = ["" => "http://api.twitter.com",
886 "statusnet" => "http://status.net/schema/api/1/",
887 "friendica" => "http://friendi.ca/schema/api/1/",
888 "georss" => "http://www.georss.org/georss"];
890 /// @todo Auto detection of needed namespaces
891 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
895 if (is_array($data2)) {
896 api_walk_recursive($data2, "api_reformat_xml");
903 foreach ($data2 as $item) {
904 $data4[$i++ . ":" . $childname] = $item;
910 $data3 = [$root_element => $data2];
912 $ret = XML::fromArray($data3, $xml, false, $namespaces);
917 * @brief Formats the data according to the data type
919 * @param string $root_element Name of the root element
920 * @param string $type Return type (atom, rss, xml, json)
921 * @param array $data JSON style array
923 * @return (string|array) XML data or JSON data
925 function api_format_data($root_element, $type, $data)
931 $ret = api_create_xml($data, $root_element);
947 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
948 * returns a 401 status code and an error message if not.
949 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
951 * @param string $type Return type (atom, rss, xml, json)
953 function api_account_verify_credentials($type)
958 if (api_user() === false) {
959 throw new ForbiddenException();
962 unset($_REQUEST["user_id"]);
963 unset($_GET["user_id"]);
965 unset($_REQUEST["screen_name"]);
966 unset($_GET["screen_name"]);
968 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
970 $user_info = api_get_user($a);
972 // "verified" isn't used here in the standard
973 unset($user_info["verified"]);
975 // - Adding last status
977 $user_info["status"] = api_status_show("raw");
978 if (!count($user_info["status"])) {
979 unset($user_info["status"]);
981 unset($user_info["status"]["user"]);
985 // "uid" and "self" are only needed for some internal stuff, so remove it from here
986 unset($user_info["uid"]);
987 unset($user_info["self"]);
989 return api_format_data("user", $type, ['user' => $user_info]);
992 /// @TODO move to top of file or somewhere better
993 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
996 * Get data from $_POST or $_GET
1000 function requestdata($k)
1002 if (x($_POST, $k)) {
1012 * Deprecated function to upload media.
1014 * @param string $type Return type (atom, rss, xml, json)
1016 * @return array|string
1018 function api_statuses_mediap($type)
1022 if (api_user() === false) {
1023 logger('api_statuses_update: no user');
1024 throw new ForbiddenException();
1026 $user_info = api_get_user($a);
1028 $_REQUEST['type'] = 'wall';
1029 $_REQUEST['profile_uid'] = api_user();
1030 $_REQUEST['api_source'] = true;
1031 $txt = requestdata('status');
1032 /// @TODO old-lost code?
1033 //$txt = urldecode(requestdata('status'));
1035 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1036 $txt = html2bb_video($txt);
1037 $config = HTMLPurifier_Config::createDefault();
1038 $config->set('Cache.DefinitionImpl', null);
1039 $purifier = new HTMLPurifier($config);
1040 $txt = $purifier->purify($txt);
1042 $txt = HTML::toBBCode($txt);
1044 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1046 $picture = wall_upload_post($a, false);
1048 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1049 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1052 // this should output the last post (the one we just posted).
1053 return api_status_show($type);
1056 /// @TODO move this to top of file or somewhere better!
1057 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1060 * Updates the user’s current status.
1062 * @param string $type Return type (atom, rss, xml, json)
1064 * @return array|string
1065 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1067 function api_statuses_update($type)
1072 if (api_user() === false) {
1073 logger('api_statuses_update: no user');
1074 throw new ForbiddenException();
1079 // convert $_POST array items to the form we use for web posts.
1080 if (requestdata('htmlstatus')) {
1081 $txt = requestdata('htmlstatus');
1082 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1083 $txt = html2bb_video($txt);
1085 $config = HTMLPurifier_Config::createDefault();
1086 $config->set('Cache.DefinitionImpl', null);
1088 $purifier = new HTMLPurifier($config);
1089 $txt = $purifier->purify($txt);
1091 $_REQUEST['body'] = HTML::toBBCode($txt);
1094 $_REQUEST['body'] = requestdata('status');
1097 $_REQUEST['title'] = requestdata('title');
1099 $parent = requestdata('in_reply_to_status_id');
1101 // Twidere sends "-1" if it is no reply ...
1102 if ($parent == -1) {
1106 if (ctype_digit($parent)) {
1107 $_REQUEST['parent'] = $parent;
1109 $_REQUEST['parent_uri'] = $parent;
1112 if (requestdata('lat') && requestdata('long')) {
1113 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1115 $_REQUEST['profile_uid'] = api_user();
1118 $_REQUEST['type'] = 'net-comment';
1120 // Check for throttling (maximum posts per day, week and month)
1121 $throttle_day = Config::get('system', 'throttle_limit_day');
1122 if ($throttle_day > 0) {
1123 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1125 $condition = ["`uid` = ? AND `wall` AND `created` > ? AND `id` = `parent`", api_user(), $datefrom];
1126 $posts_day = dba::count('item', $condition);
1128 if ($posts_day > $throttle_day) {
1129 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1130 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1131 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));
1135 $throttle_week = Config::get('system', 'throttle_limit_week');
1136 if ($throttle_week > 0) {
1137 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1139 $condition = ["`uid` = ? AND `wall` AND `created` > ? AND `id` = `parent`", api_user(), $datefrom];
1140 $posts_week = dba::count('item', $condition);
1142 if ($posts_week > $throttle_week) {
1143 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1144 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1145 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));
1149 $throttle_month = Config::get('system', 'throttle_limit_month');
1150 if ($throttle_month > 0) {
1151 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1153 $condition = ["`uid` = ? AND `wall` AND `created` > ? AND `id` = `parent`", api_user(), $datefrom];
1154 $posts_month = dba::count('item', $condition);
1156 if ($posts_month > $throttle_month) {
1157 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1158 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1159 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));
1163 $_REQUEST['type'] = 'wall';
1166 if (x($_FILES, 'media')) {
1167 // upload the image if we have one
1168 $picture = wall_upload_post($a, false);
1169 if (is_array($picture)) {
1170 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1174 // To-Do: Multiple IDs
1175 if (requestdata('media_ids')) {
1177 "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",
1178 intval(requestdata('media_ids')),
1181 if (DBM::is_result($r)) {
1182 $phototypes = Image::supportedTypes();
1183 $ext = $phototypes[$r[0]['type']];
1184 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1185 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1189 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1191 $_REQUEST['api_source'] = true;
1193 if (!x($_REQUEST, "source")) {
1194 $_REQUEST["source"] = api_source();
1197 // call out normal post function
1200 // this should output the last post (the one we just posted).
1201 return api_status_show($type);
1204 /// @TODO move to top of file or somewhere better
1205 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1206 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1209 * Uploads an image to Friendica.
1212 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1214 function api_media_upload()
1218 if (api_user() === false) {
1220 throw new ForbiddenException();
1225 if (!x($_FILES, 'media')) {
1227 throw new BadRequestException("No media.");
1230 $media = wall_upload_post($a, false);
1233 throw new InternalServerErrorException();
1237 $returndata["media_id"] = $media["id"];
1238 $returndata["media_id_string"] = (string)$media["id"];
1239 $returndata["size"] = $media["size"];
1240 $returndata["image"] = ["w" => $media["width"],
1241 "h" => $media["height"],
1242 "image_type" => $media["type"]];
1244 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1246 return ["media" => $returndata];
1249 /// @TODO move to top of file or somewhere better
1250 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1254 * @param string $type Return type (atom, rss, xml, json)
1256 * @return array|string
1258 function api_status_show($type)
1262 $user_info = api_get_user($a);
1264 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1266 if ($type == "raw") {
1267 $privacy_sql = "AND NOT `private`";
1272 // get last public wall message
1273 $condition = ["`owner-id` = ? AND `uid` = ? AND `type` != 'activity' ".$privacy_sql,
1274 $user_info['pid'], api_user()];
1275 $lastwall = dba::selectFirst('item', [], $condition, ['order' => ['id' => true]]);
1277 if (DBM::is_result($lastwall)) {
1278 $in_reply_to = api_in_reply_to($lastwall);
1280 $converted = api_convert_item($lastwall);
1282 if ($type == "xml") {
1283 $geo = "georss:point";
1289 'created_at' => api_date($lastwall['created']),
1290 'id' => intval($lastwall['id']),
1291 'id_str' => (string) $lastwall['id'],
1292 'text' => $converted["text"],
1293 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1294 'truncated' => false,
1295 'in_reply_to_status_id' => $in_reply_to['status_id'],
1296 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1297 'in_reply_to_user_id' => $in_reply_to['user_id'],
1298 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1299 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1300 'user' => $user_info,
1302 'coordinates' => "",
1304 'contributors' => "",
1305 'is_quote_status' => false,
1306 'retweet_count' => 0,
1307 'favorite_count' => 0,
1308 'favorited' => $lastwall['starred'] ? true : false,
1309 'retweeted' => false,
1310 'possibly_sensitive' => false,
1312 'statusnet_html' => $converted["html"],
1313 'statusnet_conversation_id' => $lastwall['parent'],
1314 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1317 if (count($converted["attachments"]) > 0) {
1318 $status_info["attachments"] = $converted["attachments"];
1321 if (count($converted["entities"]) > 0) {
1322 $status_info["entities"] = $converted["entities"];
1325 if ($status_info["source"] == 'web') {
1326 $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $user_info['url']);
1327 } elseif (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $status_info["source"]) {
1328 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $user_info['url']).')');
1331 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1332 unset($status_info["user"]["uid"]);
1333 unset($status_info["user"]["self"]);
1335 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1337 if ($type == "raw") {
1338 return $status_info;
1341 return api_format_data("statuses", $type, ['status' => $status_info]);
1346 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1347 * The author's most recent status will be returned inline.
1349 * @param string $type Return type (atom, rss, xml, json)
1350 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1352 function api_users_show($type)
1356 $user_info = api_get_user($a);
1358 $condition = ["`owner-id` = ? AND `uid` = ? AND `verb` = ? AND `type` != 'activity' AND NOT `private`",
1359 $user_info['pid'], api_user(), ACTIVITY_POST];
1360 $lastwall = dba::selectFirst('item', [], $condition, ['order' => ['id' => true]]);
1362 if (DBM::is_result($lastwall)) {
1363 $in_reply_to = api_in_reply_to($lastwall);
1365 $converted = api_convert_item($lastwall);
1367 if ($type == "xml") {
1368 $geo = "georss:point";
1373 $user_info['status'] = [
1374 'text' => $converted["text"],
1375 'truncated' => false,
1376 'created_at' => api_date($lastwall['created']),
1377 'in_reply_to_status_id' => $in_reply_to['status_id'],
1378 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1379 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1380 'id' => intval($lastwall['contact-id']),
1381 'id_str' => (string) $lastwall['contact-id'],
1382 'in_reply_to_user_id' => $in_reply_to['user_id'],
1383 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1384 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1386 'favorited' => $lastwall['starred'] ? true : false,
1387 'statusnet_html' => $converted["html"],
1388 'statusnet_conversation_id' => $lastwall['parent'],
1389 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1392 if (count($converted["attachments"]) > 0) {
1393 $user_info["status"]["attachments"] = $converted["attachments"];
1396 if (count($converted["entities"]) > 0) {
1397 $user_info["status"]["entities"] = $converted["entities"];
1400 if ($user_info["status"]["source"] == 'web') {
1401 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $user_info['url']);
1404 if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
1405 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $user_info['url']) . ')');
1409 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1410 unset($user_info["uid"]);
1411 unset($user_info["self"]);
1413 return api_format_data("user", $type, ['user' => $user_info]);
1416 /// @TODO move to top of file or somewhere better
1417 api_register_func('api/users/show', 'api_users_show');
1418 api_register_func('api/externalprofile/show', 'api_users_show');
1421 * Search a public user account.
1423 * @param string $type Return type (atom, rss, xml, json)
1425 * @return array|string
1426 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1428 function api_users_search($type)
1434 if (x($_GET, 'q')) {
1435 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1437 if (!DBM::is_result($r)) {
1438 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1441 if (DBM::is_result($r)) {
1443 foreach ($r as $user) {
1444 $user_info = api_get_user($a, $user["id"]);
1446 if ($type == "xml") {
1447 $userlist[$k++.":user"] = $user_info;
1449 $userlist[] = $user_info;
1452 $userlist = ["users" => $userlist];
1454 throw new BadRequestException("User ".$_GET["q"]." not found.");
1457 throw new BadRequestException("No user specified.");
1460 return api_format_data("users", $type, $userlist);
1463 /// @TODO move to top of file or somewhere better
1464 api_register_func('api/users/search', 'api_users_search');
1467 * Return user objects
1469 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1471 * @param string $type Return format: json or xml
1473 * @return array|string
1474 * @throws NotFoundException if the results are empty.
1476 function api_users_lookup($type)
1480 if (x($_REQUEST['user_id'])) {
1481 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1483 $users[] = api_get_user(get_app(), $id);
1488 if (empty($users)) {
1489 throw new NotFoundException;
1492 return api_format_data("users", $type, ['users' => $users]);
1495 /// @TODO move to top of file or somewhere better
1496 api_register_func('api/users/lookup', 'api_users_lookup', true);
1499 * Returns statuses that match a specified query.
1501 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1503 * @param string $type Return format: json, xml, atom, rss
1505 * @return array|string
1506 * @throws BadRequestException if the "q" parameter is missing.
1508 function api_search($type)
1511 $user_info = api_get_user($a);
1513 if (api_user() === false || $user_info === false) {
1514 throw new ForbiddenException();
1519 if (!x($_REQUEST, 'q')) {
1520 throw new BadRequestException("q parameter is required.");
1523 if (x($_REQUEST, 'rpp')) {
1524 $count = $_REQUEST['rpp'];
1525 } elseif (x($_REQUEST, 'count')) {
1526 $count = $_REQUEST['count'];
1531 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1532 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1533 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1535 $start = $page * $count;
1537 $condition = ["`verb` = ? AND `item`.`id` > ?
1538 AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1539 AND `item`.`body` LIKE CONCAT('%',?,'%')",
1540 ACTIVITY_POST, $since_id, api_user(), $_REQUEST['q']];
1543 $condition[0] .= " AND `item`.`id` <= ?";
1544 $condition[] = $max_id;
1547 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1548 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1550 $data['status'] = api_format_items(dba::inArray($statuses), $user_info);
1552 return api_format_data("statuses", $type, $data);
1555 /// @TODO move to top of file or somewhere better
1556 api_register_func('api/search/tweets', 'api_search', true);
1557 api_register_func('api/search', 'api_search', true);
1560 * Returns the most recent statuses posted by the user and the users they follow.
1562 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1564 * @param string $type Return type (atom, rss, xml, json)
1566 * @todo Optional parameters
1567 * @todo Add reply info
1569 function api_statuses_home_timeline($type)
1572 $user_info = api_get_user($a);
1574 if (api_user() === false || $user_info === false) {
1575 throw new ForbiddenException();
1578 unset($_REQUEST["user_id"]);
1579 unset($_GET["user_id"]);
1581 unset($_REQUEST["screen_name"]);
1582 unset($_GET["screen_name"]);
1584 // get last network messages
1587 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1588 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1592 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1593 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1594 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1595 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1596 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1598 $start = $page * $count;
1600 $condition = ["`uid` = ? AND `verb` = ? AND `item`.`id` > ?", api_user(), ACTIVITY_POST, $since_id];
1603 $condition[0] .= " AND `item`.`id` <= ?";
1604 $condition[] = $max_id;
1606 if ($exclude_replies > 0) {
1607 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1609 if ($conversation_id > 0) {
1610 $condition[0] .= " AND `item`.`parent` = ?";
1611 $condition[] = $conversation_id;
1614 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1615 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1617 $items = dba::inArray($statuses);
1619 $ret = api_format_items($items, $user_info, false, $type);
1621 // Set all posts from the query above to seen
1623 foreach ($items as $item) {
1624 $idarray[] = intval($item["id"]);
1627 if (!empty($idarray)) {
1628 $unseen = dba::exists('item', ['unseen' => true, 'id' => $idarray]);
1630 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1634 $data = ['status' => $ret];
1638 $data = api_rss_extra($a, $data, $user_info);
1642 return api_format_data("statuses", $type, $data);
1645 /// @TODO move to top of file or somewhere better
1646 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1647 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1650 * Returns the most recent statuses from public users.
1652 * @param string $type Return type (atom, rss, xml, json)
1654 * @return array|string
1656 function api_statuses_public_timeline($type)
1659 $user_info = api_get_user($a);
1661 if (api_user() === false || $user_info === false) {
1662 throw new ForbiddenException();
1665 // get last network messages
1668 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1669 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1673 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1674 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1675 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1676 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1677 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1679 $start = $page * $count;
1682 if ($exclude_replies && !$conversation_id) {
1683 $condition = ["`verb` = ? AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall`",
1684 ACTIVITY_POST, $since_id];
1687 $condition[0] .= " AND `thread`.`iid` <= ?";
1688 $condition[] = $max_id;
1691 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1692 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1694 $r = dba::inArray($statuses);
1696 $condition = ["`verb` = ? AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin`",
1697 ACTIVITY_POST, $since_id];
1700 $condition[0] .= " AND `item`.`id` <= ?";
1701 $condition[] = $max_id;
1703 if ($conversation_id > 0) {
1704 $condition[0] .= " AND `item`.`parent` = ?";
1705 $condition[] = $conversation_id;
1708 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1709 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1711 $r = dba::inArray($statuses);
1714 $ret = api_format_items($r, $user_info, false, $type);
1716 $data = ['status' => $ret];
1720 $data = api_rss_extra($a, $data, $user_info);
1724 return api_format_data("statuses", $type, $data);
1727 /// @TODO move to top of file or somewhere better
1728 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1731 * Returns the most recent statuses posted by users this node knows about.
1733 * @brief Returns the list of public federated posts this node knows about
1735 * @param string $type Return format: json, xml, atom, rss
1736 * @return array|string
1737 * @throws ForbiddenException
1739 function api_statuses_networkpublic_timeline($type)
1742 $user_info = api_get_user($a);
1744 if (api_user() === false || $user_info === false) {
1745 throw new ForbiddenException();
1748 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1749 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1752 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1753 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1757 $start = ($page - 1) * $count;
1759 $condition = ["`uid` = 0 AND `verb` = ? AND `thread`.`iid` > ? AND NOT `private`",
1760 ACTIVITY_POST, $since_id];
1763 $condition[0] .= " AND `thread`.`iid` <= ?";
1764 $condition[] = $max_id;
1767 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1768 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1770 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
1772 $data = ['status' => $ret];
1776 $data = api_rss_extra($a, $data, $user_info);
1780 return api_format_data("statuses", $type, $data);
1783 /// @TODO move to top of file or somewhere better
1784 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1787 * Returns a single status.
1789 * @param string $type Return type (atom, rss, xml, json)
1791 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1793 function api_statuses_show($type)
1796 $user_info = api_get_user($a);
1798 if (api_user() === false || $user_info === false) {
1799 throw new ForbiddenException();
1803 $id = intval($a->argv[3]);
1806 $id = intval($_REQUEST["id"]);
1811 $id = intval($a->argv[4]);
1814 logger('API: api_statuses_show: ' . $id);
1816 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1818 // try to fetch the item for the local user - or the public item, if there is no local one
1819 $uri_item = dba::selectFirst('item', ['uri'], ['id' => $id]);
1820 if (!DBM::is_result($uri_item)) {
1821 throw new BadRequestException("There is no status with this id.");
1824 $item = dba::selectFirst('item', ['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1825 if (!DBM::is_result($item)) {
1826 throw new BadRequestException("There is no status with this id.");
1831 if ($conversation) {
1832 $condition = ['parent' => $id, 'verb' => ACTIVITY_POST];
1833 $params = ['order' => ['id' => true]];
1835 $condition = ['id' => $id, 'verb' => ACTIVITY_POST];
1839 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1841 /// @TODO How about copying this to above methods which don't check $r ?
1842 if (!DBM::is_result($statuses)) {
1843 throw new BadRequestException("There is no status with this id.");
1846 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
1848 if ($conversation) {
1849 $data = ['status' => $ret];
1850 return api_format_data("statuses", $type, $data);
1852 $data = ['status' => $ret[0]];
1853 return api_format_data("status", $type, $data);
1857 /// @TODO move to top of file or somewhere better
1858 api_register_func('api/statuses/show', 'api_statuses_show', true);
1862 * @param string $type Return type (atom, rss, xml, json)
1864 * @todo nothing to say?
1866 function api_conversation_show($type)
1869 $user_info = api_get_user($a);
1871 if (api_user() === false || $user_info === false) {
1872 throw new ForbiddenException();
1876 $id = intval($a->argv[3]);
1877 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1878 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1882 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1883 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1885 $start = $page*$count;
1888 $id = intval($_REQUEST["id"]);
1893 $id = intval($a->argv[4]);
1896 logger('API: api_conversation_show: '.$id);
1898 // try to fetch the item for the local user - or the public item, if there is no local one
1899 $item = dba::selectFirst('item', ['parent-uri'], ['id' => $id]);
1900 if (!DBM::is_result($item)) {
1901 throw new BadRequestException("There is no status with this id.");
1904 $parent = dba::selectFirst('item', ['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1905 if (!DBM::is_result($parent)) {
1906 throw new BadRequestException("There is no status with this id.");
1909 $id = $parent['id'];
1911 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `verb` = ? AND `item`.`id` > ?",
1912 $id, api_user(), ACTIVITY_POST, $since_id];
1915 $condition[0] .= " AND `item`.`id` <= ?";
1916 $condition[] = $max_id;
1919 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1920 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1922 if (!DBM::is_result($statuses)) {
1923 throw new BadRequestException("There is no status with id $id.");
1926 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
1928 $data = ['status' => $ret];
1929 return api_format_data("statuses", $type, $data);
1932 /// @TODO move to top of file or somewhere better
1933 api_register_func('api/conversation/show', 'api_conversation_show', true);
1934 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1939 * @param string $type Return type (atom, rss, xml, json)
1941 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1943 function api_statuses_repeat($type)
1949 if (api_user() === false) {
1950 throw new ForbiddenException();
1956 $id = intval($a->argv[3]);
1959 $id = intval($_REQUEST["id"]);
1964 $id = intval($a->argv[4]);
1967 logger('API: api_statuses_repeat: '.$id);
1969 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1970 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
1972 if (DBM::is_result($item) && $item['body'] != "") {
1973 if (strpos($item['body'], "[/share]") !== false) {
1974 $pos = strpos($item['body'], "[share");
1975 $post = substr($item['body'], $pos);
1977 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
1979 $post .= $item['body'];
1980 $post .= "[/share]";
1982 $_REQUEST['body'] = $post;
1983 $_REQUEST['profile_uid'] = api_user();
1984 $_REQUEST['type'] = 'wall';
1985 $_REQUEST['api_source'] = true;
1987 if (!x($_REQUEST, "source")) {
1988 $_REQUEST["source"] = api_source();
1993 throw new ForbiddenException();
1996 // this should output the last post (the one we just posted).
1998 return api_status_show($type);
2001 /// @TODO move to top of file or somewhere better
2002 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2005 * Destroys a specific status.
2007 * @param string $type Return type (atom, rss, xml, json)
2009 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2011 function api_statuses_destroy($type)
2015 if (api_user() === false) {
2016 throw new ForbiddenException();
2022 $id = intval($a->argv[3]);
2025 $id = intval($_REQUEST["id"]);
2030 $id = intval($a->argv[4]);
2033 logger('API: api_statuses_destroy: '.$id);
2035 $ret = api_statuses_show($type);
2037 Item::deleteForUser(['id' => $id], api_user());
2042 /// @TODO move to top of file or somewhere better
2043 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2046 * Returns the most recent mentions.
2048 * @param string $type Return type (atom, rss, xml, json)
2050 * @see http://developer.twitter.com/doc/get/statuses/mentions
2052 function api_statuses_mentions($type)
2055 $user_info = api_get_user($a);
2057 if (api_user() === false || $user_info === false) {
2058 throw new ForbiddenException();
2061 unset($_REQUEST["user_id"]);
2062 unset($_GET["user_id"]);
2064 unset($_REQUEST["screen_name"]);
2065 unset($_GET["screen_name"]);
2067 // get last network messages
2070 $since_id = defaults($_REQUEST, 'since_id', 0);
2071 $max_id = defaults($_REQUEST, 'max_id' , 0);
2072 $count = defaults($_REQUEST, 'count' , 20);
2073 $page = defaults($_REQUEST, 'page' , 1);
2078 $start = ($page - 1) * $count;
2080 $condition = ["`uid` = ? AND `verb` = ? AND `item`.`id` > ? AND `author-id` != ?
2081 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = ? AND `mention` AND NOT `ignored`)",
2082 api_user(), ACTIVITY_POST, $since_id, $user_info['pid'], api_user()];
2085 $condition[0] .= " AND `item`.`id` <= ?";
2086 $condition[] = $max_id;
2089 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2090 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2092 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
2094 $data = ['status' => $ret];
2098 $data = api_rss_extra($a, $data, $user_info);
2102 return api_format_data("statuses", $type, $data);
2105 /// @TODO move to top of file or somewhere better
2106 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2107 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2110 * Returns the most recent statuses posted by the user.
2112 * @brief Returns a user's public timeline
2114 * @param string $type Either "json" or "xml"
2115 * @return string|array
2116 * @throws ForbiddenException
2117 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2119 function api_statuses_user_timeline($type)
2122 $user_info = api_get_user($a);
2124 if (api_user() === false || $user_info === false) {
2125 throw new ForbiddenException();
2129 "api_statuses_user_timeline: api_user: ". api_user() .
2130 "\nuser_info: ".print_r($user_info, true) .
2131 "\n_REQUEST: ".print_r($_REQUEST, true),
2135 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2136 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2137 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2138 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2141 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2142 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2146 $start = ($page - 1) * $count;
2148 $condition = ["`uid` = ? AND `verb` = ? AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2149 api_user(), ACTIVITY_POST, $since_id, $user_info['cid']];
2151 if ($user_info['self'] == 1) {
2152 $condition[0] .= ' AND `item`.`wall` ';
2155 if ($exclude_replies > 0) {
2156 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2159 if ($conversation_id > 0) {
2160 $condition[0] .= " AND `item`.`parent` = ?";
2161 $condition[] = $conversation_id;
2165 $condition[0] .= " AND `item`.`id` <= ?";
2166 $condition[] = $max_id;
2169 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2170 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2172 $ret = api_format_items(dba::inArray($statuses), $user_info, true, $type);
2174 $data = ['status' => $ret];
2178 $data = api_rss_extra($a, $data, $user_info);
2182 return api_format_data("statuses", $type, $data);
2185 /// @TODO move to top of file or somewhere better
2186 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2189 * Star/unstar an item.
2190 * param: id : id of the item
2192 * @param string $type Return type (atom, rss, xml, json)
2194 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2196 function api_favorites_create_destroy($type)
2200 if (api_user() === false) {
2201 throw new ForbiddenException();
2204 // for versioned api.
2205 /// @TODO We need a better global soluton
2206 $action_argv_id = 2;
2207 if ($a->argv[1] == "1.1") {
2208 $action_argv_id = 3;
2211 if ($a->argc <= $action_argv_id) {
2212 throw new BadRequestException("Invalid request.");
2214 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2215 if ($a->argc == $action_argv_id + 2) {
2216 $itemid = intval($a->argv[$action_argv_id + 1]);
2218 /// @TODO use x() to check if _REQUEST contains 'id'
2219 $itemid = intval($_REQUEST['id']);
2222 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2224 if (!DBM::is_result($item)) {
2225 throw new BadRequestException("Invalid item.");
2230 $item['starred'] = 1;
2233 $item['starred'] = 0;
2236 throw new BadRequestException("Invalid action ".$action);
2239 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2242 throw new InternalServerErrorException("DB error");
2246 $user_info = api_get_user($a);
2247 $rets = api_format_items([$item], $user_info, false, $type);
2250 $data = ['status' => $ret];
2254 $data = api_rss_extra($a, $data, $user_info);
2257 return api_format_data("status", $type, $data);
2260 /// @TODO move to top of file or somewhere better
2261 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2262 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2265 * Returns the most recent favorite statuses.
2267 * @param string $type Return type (atom, rss, xml, json)
2269 * @return string|array
2271 function api_favorites($type)
2276 $user_info = api_get_user($a);
2278 if (api_user() === false || $user_info === false) {
2279 throw new ForbiddenException();
2284 // in friendica starred item are private
2285 // return favorites only for self
2286 logger('api_favorites: self:' . $user_info['self']);
2288 if ($user_info['self'] == 0) {
2292 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2293 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2294 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2295 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2300 $start = $page*$count;
2302 $condition = ["`uid` = ? AND `verb` = ? AND `id` > ? AND `starred`",
2303 api_user(), ACTIVITY_POST, $since_id];
2305 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2308 $condition[0] .= " AND `item`.`id` <= ?";
2309 $condition[] = $max_id;
2312 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2314 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
2317 $data = ['status' => $ret];
2321 $data = api_rss_extra($a, $data, $user_info);
2324 return api_format_data("statuses", $type, $data);
2327 /// @TODO move to top of file or somewhere better
2328 api_register_func('api/favorites', 'api_favorites', true);
2332 * @param array $item
2333 * @param array $recipient
2334 * @param array $sender
2338 function api_format_messages($item, $recipient, $sender)
2340 // standard meta information
2342 'id' => $item['id'],
2343 'sender_id' => $sender['id'] ,
2345 'recipient_id' => $recipient['id'],
2346 'created_at' => api_date($item['created']),
2347 'sender_screen_name' => $sender['screen_name'],
2348 'recipient_screen_name' => $recipient['screen_name'],
2349 'sender' => $sender,
2350 'recipient' => $recipient,
2352 'friendica_seen' => $item['seen'],
2353 'friendica_parent_uri' => $item['parent-uri'],
2356 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2357 unset($ret["sender"]["uid"]);
2358 unset($ret["sender"]["self"]);
2359 unset($ret["recipient"]["uid"]);
2360 unset($ret["recipient"]["self"]);
2362 //don't send title to regular StatusNET requests to avoid confusing these apps
2363 if (x($_GET, 'getText')) {
2364 $ret['title'] = $item['title'];
2365 if ($_GET['getText'] == 'html') {
2366 $ret['text'] = BBCode::convert($item['body'], false);
2367 } elseif ($_GET['getText'] == 'plain') {
2368 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2371 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2373 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2374 unset($ret['sender']);
2375 unset($ret['recipient']);
2383 * @param array $item
2387 function api_convert_item($item)
2389 $body = $item['body'];
2390 $attachments = api_get_attachments($body);
2392 // Workaround for ostatus messages where the title is identically to the body
2393 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2394 $statusbody = trim(HTML::toPlaintext($html, 0));
2396 // handle data: images
2397 $statusbody = api_format_items_embeded_images($item, $statusbody);
2399 $statustitle = trim($item['title']);
2401 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2402 $statustext = trim($statusbody);
2404 $statustext = trim($statustitle."\n\n".$statusbody);
2407 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2408 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2411 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2413 // Workaround for clients with limited HTML parser functionality
2414 $search = ["<br>", "<blockquote>", "</blockquote>",
2415 "<h1>", "</h1>", "<h2>", "</h2>",
2416 "<h3>", "</h3>", "<h4>", "</h4>",
2417 "<h5>", "</h5>", "<h6>", "</h6>"];
2418 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2419 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2420 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2421 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2422 $statushtml = str_replace($search, $replace, $statushtml);
2424 if ($item['title'] != "") {
2425 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2429 $oldtext = $statushtml;
2430 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2431 } while ($oldtext != $statushtml);
2433 if (substr($statushtml, 0, 4) == '<br>') {
2434 $statushtml = substr($statushtml, 4);
2437 if (substr($statushtml, 0, -4) == '<br>') {
2438 $statushtml = substr($statushtml, -4);
2441 // feeds without body should contain the link
2442 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2443 $statushtml .= BBCode::convert($item['plink']);
2446 $entities = api_get_entitities($statustext, $body);
2449 "text" => $statustext,
2450 "html" => $statushtml,
2451 "attachments" => $attachments,
2452 "entities" => $entities
2458 * @param string $body
2462 function api_get_attachments(&$body)
2465 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2467 $URLSearchString = "^\[\]";
2468 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2476 foreach ($images[1] as $image) {
2477 $imagedata = Image::getInfoFromURL($image);
2480 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2484 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2485 foreach ($images[0] as $orig) {
2486 $body = str_replace($orig, "", $body);
2490 return $attachments;
2495 * @param string $text
2496 * @param string $bbcode
2499 * @todo Links at the first character of the post
2501 function api_get_entitities(&$text, $bbcode)
2503 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2505 if ($include_entities != "true") {
2506 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2508 foreach ($images[1] as $image) {
2509 $replace = proxy_url($image);
2510 $text = str_replace($image, $replace, $text);
2515 $bbcode = BBCode::cleanPictureLinks($bbcode);
2517 // Change pure links in text to bbcode uris
2518 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2521 $entities["hashtags"] = [];
2522 $entities["symbols"] = [];
2523 $entities["urls"] = [];
2524 $entities["user_mentions"] = [];
2526 $URLSearchString = "^\[\]";
2528 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2530 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2531 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2532 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2534 $bbcode = preg_replace(
2535 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2536 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2539 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2541 $bbcode = preg_replace(
2542 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2543 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2546 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2548 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2550 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2551 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2554 foreach ($urls[1] as $id => $url) {
2555 //$start = strpos($text, $url, $offset);
2556 $start = iconv_strpos($text, $url, 0, "UTF-8");
2557 if (!($start === false)) {
2558 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2562 ksort($ordered_urls);
2565 //foreach ($urls[1] AS $id=>$url) {
2566 foreach ($ordered_urls as $url) {
2567 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2568 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2570 $display_url = $url["title"];
2572 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2573 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2575 if (strlen($display_url) > 26) {
2576 $display_url = substr($display_url, 0, 25)."…";
2580 //$start = strpos($text, $url, $offset);
2581 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2582 if (!($start === false)) {
2583 $entities["urls"][] = ["url" => $url["url"],
2584 "expanded_url" => $url["url"],
2585 "display_url" => $display_url,
2586 "indices" => [$start, $start+strlen($url["url"])]];
2587 $offset = $start + 1;
2591 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2592 $ordered_images = [];
2593 foreach ($images[1] as $image) {
2594 //$start = strpos($text, $url, $offset);
2595 $start = iconv_strpos($text, $image, 0, "UTF-8");
2596 if (!($start === false)) {
2597 $ordered_images[$start] = $image;
2600 //$entities["media"] = array();
2603 foreach ($ordered_images as $url) {
2604 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2605 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2607 if (strlen($display_url) > 26) {
2608 $display_url = substr($display_url, 0, 25)."…";
2611 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2612 if (!($start === false)) {
2613 $image = Image::getInfoFromURL($url);
2615 // If image cache is activated, then use the following sizes:
2616 // thumb (150), small (340), medium (600) and large (1024)
2617 if (!Config::get("system", "proxy_disabled")) {
2618 $media_url = proxy_url($url);
2621 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2622 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2624 if (($image[0] > 150) || ($image[1] > 150)) {
2625 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2626 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2629 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2630 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2632 if (($image[0] > 600) || ($image[1] > 600)) {
2633 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2634 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2638 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2641 $entities["media"][] = [
2643 "id_str" => (string)$start+1,
2644 "indices" => [$start, $start+strlen($url)],
2645 "media_url" => normalise_link($media_url),
2646 "media_url_https" => $media_url,
2648 "display_url" => $display_url,
2649 "expanded_url" => $url,
2653 $offset = $start + 1;
2662 * @param array $item
2663 * @param string $text
2667 function api_format_items_embeded_images($item, $text)
2669 $text = preg_replace_callback(
2670 '|data:image/([^;]+)[^=]+=*|m',
2671 function () use ($item) {
2672 return System::baseUrl() . '/display/' . $item['guid'];
2680 * @brief return <a href='url'>name</a> as array
2682 * @param string $txt text
2687 function api_contactlink_to_array($txt)
2690 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2691 if ($r && count($match)==3) {
2693 'name' => $match[2],
2707 * @brief return likes, dislikes and attend status for item
2709 * @param array $item array
2710 * @param string $type Return type (atom, rss, xml, json)
2713 * likes => int count,
2714 * dislikes => int count
2716 function api_format_items_activities(&$item, $type = "json")
2725 'attendmaybe' => [],
2728 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2729 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2731 while ($i = dba::fetch($ret)) {
2732 // not used as result should be structured like other user data
2733 //builtin_activity_puller($i, $activities);
2735 // get user data and add it to the array of the activity
2736 $user = api_get_user($a, $i['author-id']);
2737 switch ($i['verb']) {
2739 $activities['like'][] = $user;
2741 case ACTIVITY_DISLIKE:
2742 $activities['dislike'][] = $user;
2744 case ACTIVITY_ATTEND:
2745 $activities['attendyes'][] = $user;
2747 case ACTIVITY_ATTENDNO:
2748 $activities['attendno'][] = $user;
2750 case ACTIVITY_ATTENDMAYBE:
2751 $activities['attendmaybe'][] = $user;
2760 if ($type == "xml") {
2761 $xml_activities = [];
2762 foreach ($activities as $k => $v) {
2763 // change xml element from "like" to "friendica:like"
2764 $xml_activities["friendica:".$k] = $v;
2765 // add user data into xml output
2767 foreach ($v as $user) {
2768 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2771 $activities = $xml_activities;
2779 * @brief return data from profiles
2781 * @param array $profile_row array containing data from db table 'profile'
2784 function api_format_items_profiles($profile_row)
2787 'profile_id' => $profile_row['id'],
2788 'profile_name' => $profile_row['profile-name'],
2789 'is_default' => $profile_row['is-default'] ? true : false,
2790 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2791 'profile_photo' => $profile_row['photo'],
2792 'profile_thumb' => $profile_row['thumb'],
2793 'publish' => $profile_row['publish'] ? true : false,
2794 'net_publish' => $profile_row['net-publish'] ? true : false,
2795 'description' => $profile_row['pdesc'],
2796 'date_of_birth' => $profile_row['dob'],
2797 'address' => $profile_row['address'],
2798 'city' => $profile_row['locality'],
2799 'region' => $profile_row['region'],
2800 'postal_code' => $profile_row['postal-code'],
2801 'country' => $profile_row['country-name'],
2802 'hometown' => $profile_row['hometown'],
2803 'gender' => $profile_row['gender'],
2804 'marital' => $profile_row['marital'],
2805 'marital_with' => $profile_row['with'],
2806 'marital_since' => $profile_row['howlong'],
2807 'sexual' => $profile_row['sexual'],
2808 'politic' => $profile_row['politic'],
2809 'religion' => $profile_row['religion'],
2810 'public_keywords' => $profile_row['pub_keywords'],
2811 'private_keywords' => $profile_row['prv_keywords'],
2812 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2813 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2814 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2815 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2816 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2817 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2818 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2819 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2820 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2821 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2822 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2823 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2824 'homepage' => $profile_row['homepage'],
2831 * @brief format items to be returned by api
2833 * @param array $r array of items
2834 * @param array $user_info
2835 * @param bool $filter_user filter items by $user_info
2836 * @param string $type Return type (atom, rss, xml, json)
2838 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2844 foreach ($r as $item) {
2845 localize_item($item);
2846 list($status_user, $owner_user) = api_item_get_user($a, $item);
2848 // Look if the posts are matching if they should be filtered by user id
2849 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2853 $in_reply_to = api_in_reply_to($item);
2855 $converted = api_convert_item($item);
2857 if ($type == "xml") {
2858 $geo = "georss:point";
2864 'text' => $converted["text"],
2865 'truncated' => false,
2866 'created_at'=> api_date($item['created']),
2867 'in_reply_to_status_id' => $in_reply_to['status_id'],
2868 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2869 'source' => (($item['app']) ? $item['app'] : 'web'),
2870 'id' => intval($item['id']),
2871 'id_str' => (string) intval($item['id']),
2872 'in_reply_to_user_id' => $in_reply_to['user_id'],
2873 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2874 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2876 'favorited' => $item['starred'] ? true : false,
2877 'user' => $status_user ,
2878 'friendica_owner' => $owner_user,
2879 //'entities' => NULL,
2880 'statusnet_html' => $converted["html"],
2881 'statusnet_conversation_id' => $item['parent'],
2882 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2883 'friendica_activities' => api_format_items_activities($item, $type),
2886 if (count($converted["attachments"]) > 0) {
2887 $status["attachments"] = $converted["attachments"];
2890 if (count($converted["entities"]) > 0) {
2891 $status["entities"] = $converted["entities"];
2894 if ($status["source"] == 'web') {
2895 $status["source"] = ContactSelector::networkToName($item['network'], $user_info['url']);
2896 } elseif (ContactSelector::networkToName($item['network'], $user_info['url']) != $status["source"]) {
2897 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $user_info['url']).')');
2900 if ($item["id"] == $item["parent"]) {
2901 $retweeted_item = api_share_as_retweet($item);
2902 if ($retweeted_item !== false) {
2903 $retweeted_status = $status;
2905 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
2906 } catch (BadRequestException $e) {
2907 // user not found. should be found?
2908 /// @todo check if the user should be always found
2909 $retweeted_status["user"] = [];
2912 $rt_converted = api_convert_item($retweeted_item);
2914 $retweeted_status['text'] = $rt_converted["text"];
2915 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2916 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2917 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2918 $status['retweeted_status'] = $retweeted_status;
2922 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2923 unset($status["user"]["uid"]);
2924 unset($status["user"]["self"]);
2926 if ($item["coord"] != "") {
2927 $coords = explode(' ', $item["coord"]);
2928 if (count($coords) == 2) {
2929 if ($type == "json") {
2930 $status["geo"] = ['type' => 'Point',
2931 'coordinates' => [(float) $coords[0],
2932 (float) $coords[1]]];
2933 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2934 $status["georss:point"] = $item["coord"];
2944 * Returns the remaining number of API requests available to the user before the API limit is reached.
2946 * @param string $type Return type (atom, rss, xml, json)
2948 * @return array|string
2950 function api_account_rate_limit_status($type)
2952 if ($type == "xml") {
2954 'remaining-hits' => '150',
2955 '@attributes' => ["type" => "integer"],
2956 'hourly-limit' => '150',
2957 '@attributes2' => ["type" => "integer"],
2958 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
2959 '@attributes3' => ["type" => "datetime"],
2960 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2961 '@attributes4' => ["type" => "integer"],
2965 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2966 'remaining_hits' => '150',
2967 'hourly_limit' => '150',
2968 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
2972 return api_format_data('hash', $type, ['hash' => $hash]);
2975 /// @TODO move to top of file or somewhere better
2976 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
2979 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
2981 * @param string $type Return type (atom, rss, xml, json)
2983 * @return array|string
2985 function api_help_test($type)
2987 if ($type == 'xml') {
2993 return api_format_data('ok', $type, ["ok" => $ok]);
2996 /// @TODO move to top of file or somewhere better
2997 api_register_func('api/help/test', 'api_help_test', false);
3000 * Returns all lists the user subscribes to.
3002 * @param string $type Return type (atom, rss, xml, json)
3004 * @return array|string
3005 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3007 function api_lists_list($type)
3010 /// @TODO $ret is not filled here?
3011 return api_format_data('lists', $type, ["lists_list" => $ret]);
3014 /// @TODO move to top of file or somewhere better
3015 api_register_func('api/lists/list', 'api_lists_list', true);
3016 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3019 * Returns all groups the user owns.
3021 * @param string $type Return type (atom, rss, xml, json)
3023 * @return array|string
3024 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3026 function api_lists_ownerships($type)
3030 if (api_user() === false) {
3031 throw new ForbiddenException();
3035 $user_info = api_get_user($a);
3036 $uid = $user_info['uid'];
3038 $groups = dba::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3040 // loop through all groups
3042 foreach ($groups as $group) {
3043 if ($group['visible']) {
3049 'name' => $group['name'],
3050 'id' => intval($group['id']),
3051 'id_str' => (string) $group['id'],
3052 'user' => $user_info,
3056 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3059 /// @TODO move to top of file or somewhere better
3060 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3063 * Returns recent statuses from users in the specified group.
3065 * @param string $type Return type (atom, rss, xml, json)
3067 * @return array|string
3068 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3070 function api_lists_statuses($type)
3074 $user_info = api_get_user($a);
3075 if (api_user() === false || $user_info === false) {
3076 throw new ForbiddenException();
3079 unset($_REQUEST["user_id"]);
3080 unset($_GET["user_id"]);
3082 unset($_REQUEST["screen_name"]);
3083 unset($_GET["screen_name"]);
3085 if (empty($_REQUEST['list_id'])) {
3086 throw new BadRequestException('list_id not specified');
3090 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
3091 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
3095 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3096 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3097 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
3098 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
3100 $start = $page * $count;
3102 $condition = ["`uid` = ? AND `verb` = ? AND `id` > ? AND `group_member`.`gid` = ?",
3103 api_user(), ACTIVITY_POST, $since_id, $_REQUEST['list_id']];
3106 $condition[0] .= " AND `item`.`id` <= ?";
3107 $condition[] = $max_id;
3109 if ($exclude_replies > 0) {
3110 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3112 if ($conversation_id > 0) {
3113 $condition[0] .= " AND `item`.`parent` = ?";
3114 $condition[] = $conversation_id;
3117 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3118 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3120 $items = api_format_items(dba::inArray($statuses), $user_info, false, $type);
3122 $data = ['status' => $items];
3126 $data = api_rss_extra($a, $data, $user_info);
3130 return api_format_data("statuses", $type, $data);
3133 /// @TODO move to top of file or somewhere better
3134 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3137 * Considers friends and followers lists to be private and won't return
3138 * anything if any user_id parameter is passed.
3140 * @brief Returns either the friends of the follower list
3142 * @param string $qtype Either "friends" or "followers"
3143 * @return boolean|array
3144 * @throws ForbiddenException
3146 function api_statuses_f($qtype)
3150 if (api_user() === false) {
3151 throw new ForbiddenException();
3155 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3156 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3160 $start = ($page - 1) * $count;
3162 $user_info = api_get_user($a);
3164 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3165 /* this is to stop Hotot to load friends multiple times
3166 * I'm not sure if I'm missing return something or
3167 * is a bug in hotot. Workaround, meantime
3171 return array('$users' => $ret);*/
3176 if ($qtype == 'friends') {
3177 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3178 } elseif ($qtype == 'followers') {
3179 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3182 // friends and followers only for self
3183 if ($user_info['self'] == 0) {
3184 $sql_extra = " AND false ";
3187 if ($qtype == 'blocks') {
3188 $sql_filter = 'AND `blocked` AND NOT `pending`';
3189 } elseif ($qtype == 'incoming') {
3190 $sql_filter = 'AND `pending`';
3192 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3210 foreach ($r as $cid) {
3211 $user = api_get_user($a, $cid['nurl']);
3212 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3213 unset($user["uid"]);
3214 unset($user["self"]);
3221 return ['user' => $ret];
3226 * Returns the user's friends.
3228 * @brief Returns the list of friends of the provided user
3230 * @deprecated By Twitter API in favor of friends/list
3232 * @param string $type Either "json" or "xml"
3233 * @return boolean|string|array
3235 function api_statuses_friends($type)
3237 $data = api_statuses_f("friends");
3238 if ($data === false) {
3241 return api_format_data("users", $type, $data);
3245 * Returns the user's followers.
3247 * @brief Returns the list of followers of the provided user
3249 * @deprecated By Twitter API in favor of friends/list
3251 * @param string $type Either "json" or "xml"
3252 * @return boolean|string|array
3254 function api_statuses_followers($type)
3256 $data = api_statuses_f("followers");
3257 if ($data === false) {
3260 return api_format_data("users", $type, $data);
3263 /// @TODO move to top of file or somewhere better
3264 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3265 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3268 * Returns the list of blocked users
3270 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3272 * @param string $type Either "json" or "xml"
3274 * @return boolean|string|array
3276 function api_blocks_list($type)
3278 $data = api_statuses_f('blocks');
3279 if ($data === false) {
3282 return api_format_data("users", $type, $data);
3285 /// @TODO move to top of file or somewhere better
3286 api_register_func('api/blocks/list', 'api_blocks_list', true);
3289 * Returns the list of pending users IDs
3291 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3293 * @param string $type Either "json" or "xml"
3295 * @return boolean|string|array
3297 function api_friendships_incoming($type)
3299 $data = api_statuses_f('incoming');
3300 if ($data === false) {
3305 foreach ($data['user'] as $user) {
3306 $ids[] = $user['id'];
3309 return api_format_data("ids", $type, ['id' => $ids]);
3312 /// @TODO move to top of file or somewhere better
3313 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3316 * Returns the instance's configuration information.
3318 * @param string $type Return type (atom, rss, xml, json)
3320 * @return array|string
3322 function api_statusnet_config($type)
3326 $name = $a->config['sitename'];
3327 $server = $a->get_hostname();
3328 $logo = System::baseUrl() . '/images/friendica-64.png';
3329 $email = $a->config['admin_email'];
3330 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3331 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3332 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3333 if ($a->config['api_import_size']) {
3334 $textlimit = (string) $a->config['api_import_size'];
3336 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3337 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3340 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3341 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3342 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3343 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3344 'shorturllength' => '30',
3346 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3347 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3348 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3349 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3354 return api_format_data('config', $type, ['config' => $config]);
3357 /// @TODO move to top of file or somewhere better
3358 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3359 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3363 * @param string $type Return type (atom, rss, xml, json)
3365 * @return array|string
3367 function api_statusnet_version($type)
3370 $fake_statusnet_version = "0.9.7";
3372 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3375 /// @TODO move to top of file or somewhere better
3376 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3377 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3381 * @param string $type Return type (atom, rss, xml, json)
3383 * @todo use api_format_data() to return data
3385 function api_ff_ids($type)
3388 throw new ForbiddenException();
3395 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3398 "SELECT `pcontact`.`id` FROM `contact`
3399 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3400 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3403 if (!DBM::is_result($r)) {
3408 foreach ($r as $rr) {
3409 if ($stringify_ids) {
3412 $ids[] = intval($rr['id']);
3416 return api_format_data("ids", $type, ['id' => $ids]);
3420 * Returns the ID of every user the user is following.
3422 * @param string $type Return type (atom, rss, xml, json)
3424 * @return array|string
3425 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3427 function api_friends_ids($type)
3429 return api_ff_ids($type);
3433 * Returns the ID of every user following the user.
3435 * @param string $type Return type (atom, rss, xml, json)
3437 * @return array|string
3438 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3440 function api_followers_ids($type)
3442 return api_ff_ids($type);
3445 /// @TODO move to top of file or somewhere better
3446 api_register_func('api/friends/ids', 'api_friends_ids', true);
3447 api_register_func('api/followers/ids', 'api_followers_ids', true);
3450 * Sends a new direct message.
3452 * @param string $type Return type (atom, rss, xml, json)
3454 * @return array|string
3455 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3457 function api_direct_messages_new($type)
3462 if (api_user() === false) {
3463 throw new ForbiddenException();
3466 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3470 $sender = api_get_user($a);
3472 if ($_POST['screen_name']) {
3474 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3476 dbesc($_POST['screen_name'])
3479 // Selecting the id by priority, friendica first
3480 api_best_nickname($r);
3482 $recipient = api_get_user($a, $r[0]['nurl']);
3484 $recipient = api_get_user($a, $_POST['user_id']);
3489 if (x($_REQUEST, 'replyto')) {
3491 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3493 intval($_REQUEST['replyto'])
3495 $replyto = $r[0]['parent-uri'];
3496 $sub = $r[0]['title'];
3498 if (x($_REQUEST, 'title')) {
3499 $sub = $_REQUEST['title'];
3501 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3505 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3508 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3509 $ret = api_format_messages($r[0], $recipient, $sender);
3511 $ret = ["error"=>$id];
3514 $data = ['direct_message'=>$ret];
3519 $data = api_rss_extra($a, $data, $sender);
3522 return api_format_data("direct-messages", $type, $data);
3525 /// @TODO move to top of file or somewhere better
3526 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3529 * Destroys a direct message.
3531 * @brief delete a direct_message from mail table through api
3533 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3534 * @return string|array
3535 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3537 function api_direct_messages_destroy($type)
3541 if (api_user() === false) {
3542 throw new ForbiddenException();
3546 $user_info = api_get_user($a);
3548 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3550 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3551 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3552 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3554 $uid = $user_info['uid'];
3555 // error if no id or parenturi specified (for clients posting parent-uri as well)
3556 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3557 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3558 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3561 // BadRequestException if no id specified (for clients using Twitter API)
3563 throw new BadRequestException('Message id not specified');
3566 // add parent-uri to sql command if specified by calling app
3567 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3569 // get data of the specified message id
3571 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3576 // error message if specified id is not in database
3577 if (!DBM::is_result($r)) {
3578 if ($verbose == "true") {
3579 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3580 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3582 /// @todo BadRequestException ok for Twitter API clients?
3583 throw new BadRequestException('message id not in database');
3588 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3593 if ($verbose == "true") {
3596 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3597 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3599 $answer = ['result' => 'error', 'message' => 'unknown error'];
3600 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3603 /// @todo return JSON data like Twitter API not yet implemented
3606 /// @TODO move to top of file or somewhere better
3607 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3611 * @param string $type Return type (atom, rss, xml, json)
3612 * @param string $box
3613 * @param string $verbose
3615 * @return array|string
3617 function api_direct_messages_box($type, $box, $verbose)
3620 $user_info = api_get_user($a);
3622 if (api_user() === false || $user_info === false) {
3623 throw new ForbiddenException();
3627 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3628 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3633 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3634 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3636 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3637 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3640 unset($_REQUEST["user_id"]);
3641 unset($_GET["user_id"]);
3643 unset($_REQUEST["screen_name"]);
3644 unset($_GET["screen_name"]);
3646 $profile_url = $user_info["url"];
3649 $start = $page * $count;
3654 if ($box=="sentbox") {
3655 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3656 } elseif ($box == "conversation") {
3657 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3658 } elseif ($box == "all") {
3659 $sql_extra = "true";
3660 } elseif ($box == "inbox") {
3661 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3665 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3668 if ($user_id != "") {
3669 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3670 } elseif ($screen_name !="") {
3671 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3675 "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",
3681 if ($verbose == "true" && !DBM::is_result($r)) {
3682 $answer = ['result' => 'error', 'message' => 'no mails available'];
3683 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3687 foreach ($r as $item) {
3688 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3689 $recipient = $user_info;
3690 $sender = api_get_user($a, normalise_link($item['contact-url']));
3691 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3692 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3693 $sender = $user_info;
3696 if (isset($recipient) && isset($sender)) {
3697 $ret[] = api_format_messages($item, $recipient, $sender);
3702 $data = ['direct_message' => $ret];
3706 $data = api_rss_extra($a, $data, $user_info);
3709 return api_format_data("direct-messages", $type, $data);
3713 * Returns the most recent direct messages sent by the user.
3715 * @param string $type Return type (atom, rss, xml, json)
3717 * @return array|string
3718 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3720 function api_direct_messages_sentbox($type)
3722 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3723 return api_direct_messages_box($type, "sentbox", $verbose);
3727 * Returns the most recent direct messages sent to the user.
3729 * @param string $type Return type (atom, rss, xml, json)
3731 * @return array|string
3732 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3734 function api_direct_messages_inbox($type)
3736 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3737 return api_direct_messages_box($type, "inbox", $verbose);
3742 * @param string $type Return type (atom, rss, xml, json)
3744 * @return array|string
3746 function api_direct_messages_all($type)
3748 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3749 return api_direct_messages_box($type, "all", $verbose);
3754 * @param string $type Return type (atom, rss, xml, json)
3756 * @return array|string
3758 function api_direct_messages_conversation($type)
3760 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3761 return api_direct_messages_box($type, "conversation", $verbose);
3764 /// @TODO move to top of file or somewhere better
3765 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3766 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3767 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3768 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3771 * Returns an OAuth Request Token.
3773 * @see https://oauth.net/core/1.0/#auth_step1
3775 function api_oauth_request_token()
3777 $oauth1 = new FKOAuth1();
3779 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3780 } catch (Exception $e) {
3781 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3789 * Returns an OAuth Access Token.
3791 * @return array|string
3792 * @see https://oauth.net/core/1.0/#auth_step3
3794 function api_oauth_access_token()
3796 $oauth1 = new FKOAuth1();
3798 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3799 } catch (Exception $e) {
3800 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3807 /// @TODO move to top of file or somewhere better
3808 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3809 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3813 * @brief delete a complete photoalbum with all containing photos from database through api
3815 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3816 * @return string|array
3818 function api_fr_photoalbum_delete($type)
3820 if (api_user() === false) {
3821 throw new ForbiddenException();
3824 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3826 // we do not allow calls without album string
3828 throw new BadRequestException("no albumname specified");
3830 // check if album is existing
3832 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3836 if (!DBM::is_result($r)) {
3837 throw new BadRequestException("album not available");
3840 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3841 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3842 foreach ($r as $rr) {
3843 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
3844 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
3846 if (!DBM::is_result($photo_item)) {
3847 throw new InternalServerErrorException("problem with deleting items occured");
3849 Item::deleteForUser(['id' => $photo_item['id']], api_user());
3852 // now let's delete all photos from the album
3853 $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
3855 // return success of deletion or error message
3857 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
3858 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
3860 throw new InternalServerErrorException("unknown error - deleting from database failed");
3865 * @brief update the name of the album for all photos of an album
3867 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3868 * @return string|array
3870 function api_fr_photoalbum_update($type)
3872 if (api_user() === false) {
3873 throw new ForbiddenException();
3876 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3877 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3879 // we do not allow calls without album string
3881 throw new BadRequestException("no albumname specified");
3883 if ($album_new == "") {
3884 throw new BadRequestException("no new albumname specified");
3886 // check if album is existing
3887 if (!dba::exists('photo', ['uid' => api_user(), 'album' => $album])) {
3888 throw new BadRequestException("album not available");
3890 // now let's update all photos to the albumname
3891 $result = dba::update('photo', ['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
3893 // return success of updating or error message
3895 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
3896 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
3898 throw new InternalServerErrorException("unknown error - updating in database failed");
3904 * @brief list all photos of the authenticated user
3906 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3907 * @return string|array
3909 function api_fr_photos_list($type)
3911 if (api_user() === false) {
3912 throw new ForbiddenException();
3915 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3916 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3917 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3918 intval(local_user())
3921 'image/jpeg' => 'jpg',
3922 'image/png' => 'png',
3923 'image/gif' => 'gif'
3925 $data = ['photo'=>[]];
3926 if (DBM::is_result($r)) {
3927 foreach ($r as $rr) {
3929 $photo['id'] = $rr['resource-id'];
3930 $photo['album'] = $rr['album'];
3931 $photo['filename'] = $rr['filename'];
3932 $photo['type'] = $rr['type'];
3933 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3934 $photo['created'] = $rr['created'];
3935 $photo['edited'] = $rr['edited'];
3936 $photo['desc'] = $rr['desc'];
3938 if ($type == "xml") {
3939 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3941 $photo['thumb'] = $thumb;
3942 $data['photo'][] = $photo;
3946 return api_format_data("photos", $type, $data);
3950 * @brief upload a new photo or change an existing photo
3952 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3953 * @return string|array
3955 function api_fr_photo_create_update($type)
3957 if (api_user() === false) {
3958 throw new ForbiddenException();
3961 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3962 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3963 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3964 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3965 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3966 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3967 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3968 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3969 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3971 // do several checks on input parameters
3972 // we do not allow calls without album string
3973 if ($album == null) {
3974 throw new BadRequestException("no albumname specified");
3976 // if photo_id == null --> we are uploading a new photo
3977 if ($photo_id == null) {
3980 // error if no media posted in create-mode
3981 if (!x($_FILES, 'media')) {
3983 throw new BadRequestException("no media data submitted");
3986 // album_new will be ignored in create-mode
3991 // check if photo is existing in database
3993 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3998 if (!DBM::is_result($r)) {
3999 throw new BadRequestException("photo not available");
4003 // checks on acl strings provided by clients
4004 $acl_input_error = false;
4005 $acl_input_error |= check_acl_input($allow_cid);
4006 $acl_input_error |= check_acl_input($deny_cid);
4007 $acl_input_error |= check_acl_input($allow_gid);
4008 $acl_input_error |= check_acl_input($deny_gid);
4009 if ($acl_input_error) {
4010 throw new BadRequestException("acl data invalid");
4012 // now let's upload the new media in create-mode
4013 if ($mode == "create") {
4014 $media = $_FILES['media'];
4015 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4017 // return success of updating or error message
4018 if (!is_null($data)) {
4019 return api_format_data("photo_create", $type, $data);
4021 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4025 // now let's do the changes in update-mode
4026 if ($mode == "update") {
4029 if (!is_null($desc)) {
4030 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4033 if (!is_null($album_new)) {
4034 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4037 if (!is_null($allow_cid)) {
4038 $allow_cid = trim($allow_cid);
4039 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4042 if (!is_null($deny_cid)) {
4043 $deny_cid = trim($deny_cid);
4044 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4047 if (!is_null($allow_gid)) {
4048 $allow_gid = trim($allow_gid);
4049 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4052 if (!is_null($deny_gid)) {
4053 $deny_gid = trim($deny_gid);
4054 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4058 if ($sql_extra != "") {
4059 $nothingtodo = false;
4061 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4063 DateTimeFormat::utcNow(), // update edited timestamp
4069 $nothingtodo = true;
4072 if (x($_FILES, 'media')) {
4073 $nothingtodo = false;
4074 $media = $_FILES['media'];
4075 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4076 if (!is_null($data)) {
4077 return api_format_data("photo_update", $type, $data);
4081 // return success of updating or error message
4083 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4084 return api_format_data("photo_update", $type, ['$result' => $answer]);
4087 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4088 return api_format_data("photo_update", $type, ['$result' => $answer]);
4090 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4093 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4097 * @brief delete a single photo from the database through api
4099 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4100 * @return string|array
4102 function api_fr_photo_delete($type)
4104 if (api_user() === false) {
4105 throw new ForbiddenException();
4108 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4110 // do several checks on input parameters
4111 // we do not allow calls without photo id
4112 if ($photo_id == null) {
4113 throw new BadRequestException("no photo_id specified");
4115 // check if photo is existing in database
4117 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4121 if (!DBM::is_result($r)) {
4122 throw new BadRequestException("photo not available");
4124 // now we can perform on the deletion of the photo
4125 $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4127 // return success of deletion or error message
4129 // retrieve the id of the parent element (the photo element)
4130 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4131 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4133 if (!DBM::is_result($photo_item)) {
4134 throw new InternalServerErrorException("problem with deleting items occured");
4136 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4137 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4138 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4140 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4141 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4143 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4149 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4151 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4152 * @return string|array
4154 function api_fr_photo_detail($type)
4156 if (api_user() === false) {
4157 throw new ForbiddenException();
4159 if (!x($_REQUEST, 'photo_id')) {
4160 throw new BadRequestException("No photo id.");
4163 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4164 $photo_id = $_REQUEST['photo_id'];
4166 // prepare json/xml output with data from database for the requested photo
4167 $data = prepare_photo_data($type, $scale, $photo_id);
4169 return api_format_data("photo_detail", $type, $data);
4174 * Updates the user’s profile image.
4176 * @brief updates the profile image for the user (either a specified profile or the default profile)
4178 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4180 * @return string|array
4181 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4183 function api_account_update_profile_image($type)
4185 if (api_user() === false) {
4186 throw new ForbiddenException();
4189 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4191 // error if image data is missing
4192 if (!x($_FILES, 'image')) {
4193 throw new BadRequestException("no media data submitted");
4196 // check if specified profile id is valid
4197 if ($profile_id != 0) {
4198 $profile = dba::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4199 // error message if specified profile id is not in database
4200 if (!DBM::is_result($profile)) {
4201 throw new BadRequestException("profile_id not available");
4203 $is_default_profile = $profile['is-default'];
4205 $is_default_profile = 1;
4208 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4210 if (x($_FILES, 'image')) {
4211 $media = $_FILES['image'];
4212 } elseif (x($_FILES, 'media')) {
4213 $media = $_FILES['media'];
4215 // save new profile image
4216 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4219 if (is_array($media['type'])) {
4220 $filetype = $media['type'][0];
4222 $filetype = $media['type'];
4224 if ($filetype == "image/jpeg") {
4226 } elseif ($filetype == "image/png") {
4229 throw new InternalServerErrorException('Unsupported filetype');
4232 // change specified profile or all profiles to the new resource-id
4233 if ($is_default_profile) {
4234 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4235 dba::update('photo', ['profile' => false], $condition);
4237 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype,
4238 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype];
4239 dba::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4242 Contact::updateSelfFromUserID(api_user(), true);
4244 // Update global directory in background
4245 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4246 if ($url && strlen(Config::get('system', 'directory'))) {
4247 Worker::add(PRIORITY_LOW, "Directory", $url);
4250 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4252 // output for client
4254 return api_account_verify_credentials($type);
4256 // SaveMediaToDatabase failed for some reason
4257 throw new InternalServerErrorException("image upload failed");
4261 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4262 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4263 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4264 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4265 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4266 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4267 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4268 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4269 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4272 * Update user profile
4274 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4276 * @return array|string
4278 function api_account_update_profile($type)
4280 $local_user = api_user();
4281 $api_user = api_get_user(get_app());
4283 if (!empty($_POST['name'])) {
4284 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4285 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4286 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4287 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4290 if (isset($_POST['description'])) {
4291 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4292 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4293 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4296 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4297 // Update global directory in background
4298 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4299 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4302 return api_account_verify_credentials($type);
4305 /// @TODO move to top of file or somewhere better
4306 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4310 * @param string $acl_string
4312 function check_acl_input($acl_string)
4314 if ($acl_string == null || $acl_string == " ") {
4317 $contact_not_found = false;
4319 // split <x><y><z> into array of cid's
4320 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4322 // check for each cid if it is available on server
4323 $cid_array = $array[0];
4324 foreach ($cid_array as $cid) {
4325 $cid = str_replace("<", "", $cid);
4326 $cid = str_replace(">", "", $cid);
4328 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4332 $contact_not_found |= !DBM::is_result($contact);
4334 return $contact_not_found;
4339 * @param string $mediatype
4340 * @param array $media
4341 * @param string $type
4342 * @param string $album
4343 * @param string $allow_cid
4344 * @param string $deny_cid
4345 * @param string $allow_gid
4346 * @param string $deny_gid
4347 * @param string $desc
4348 * @param integer $profile
4349 * @param boolean $visibility
4350 * @param string $photo_id
4352 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)
4360 if (is_array($media)) {
4361 if (is_array($media['tmp_name'])) {
4362 $src = $media['tmp_name'][0];
4364 $src = $media['tmp_name'];
4366 if (is_array($media['name'])) {
4367 $filename = basename($media['name'][0]);
4369 $filename = basename($media['name']);
4371 if (is_array($media['size'])) {
4372 $filesize = intval($media['size'][0]);
4374 $filesize = intval($media['size']);
4376 if (is_array($media['type'])) {
4377 $filetype = $media['type'][0];
4379 $filetype = $media['type'];
4383 if ($filetype == "") {
4384 $filetype=Image::guessType($filename);
4386 $imagedata = getimagesize($src);
4388 $filetype = $imagedata['mime'];
4391 "File upload src: " . $src . " - filename: " . $filename .
4392 " - size: " . $filesize . " - type: " . $filetype,
4396 // check if there was a php upload error
4397 if ($filesize == 0 && $media['error'] == 1) {
4398 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4400 // check against max upload size within Friendica instance
4401 $maximagesize = Config::get('system', 'maximagesize');
4402 if ($maximagesize && ($filesize > $maximagesize)) {
4403 $formattedBytes = formatBytes($maximagesize);
4404 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4407 // create Photo instance with the data of the image
4408 $imagedata = @file_get_contents($src);
4409 $Image = new Image($imagedata, $filetype);
4410 if (! $Image->isValid()) {
4411 throw new InternalServerErrorException("unable to process image data");
4414 // check orientation of image
4415 $Image->orient($src);
4418 // check max length of images on server
4419 $max_length = Config::get('system', 'max_image_length');
4420 if (! $max_length) {
4421 $max_length = MAX_IMAGE_LENGTH;
4423 if ($max_length > 0) {
4424 $Image->scaleDown($max_length);
4425 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4427 $width = $Image->getWidth();
4428 $height = $Image->getHeight();
4430 // create a new resource-id if not already provided
4431 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4433 if ($mediatype == "photo") {
4434 // upload normal image (scales 0, 1, 2)
4435 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4437 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4439 logger("photo upload: image upload with scale 0 (original size) failed");
4441 if ($width > 640 || $height > 640) {
4442 $Image->scaleDown(640);
4443 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4445 logger("photo upload: image upload with scale 1 (640x640) failed");
4449 if ($width > 320 || $height > 320) {
4450 $Image->scaleDown(320);
4451 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4453 logger("photo upload: image upload with scale 2 (320x320) failed");
4456 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4457 } elseif ($mediatype == "profileimage") {
4458 // upload profile image (scales 4, 5, 6)
4459 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4461 if ($width > 175 || $height > 175) {
4462 $Image->scaleDown(175);
4463 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4465 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4469 if ($width > 80 || $height > 80) {
4470 $Image->scaleDown(80);
4471 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4473 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4477 if ($width > 48 || $height > 48) {
4478 $Image->scaleDown(48);
4479 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4481 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4484 $Image->__destruct();
4485 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4488 if (isset($r) && $r) {
4489 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4490 if ($photo_id == null && $mediatype == "photo") {
4491 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4493 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4494 return prepare_photo_data($type, false, $hash);
4496 throw new InternalServerErrorException("image upload failed");
4502 * @param string $hash
4503 * @param string $allow_cid
4504 * @param string $deny_cid
4505 * @param string $allow_gid
4506 * @param string $deny_gid
4507 * @param string $filetype
4508 * @param boolean $visibility
4510 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4512 // get data about the api authenticated user
4513 $uri = Item::newURI(intval(api_user()));
4514 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4517 $arr['guid'] = get_guid(32);
4518 $arr['uid'] = intval(api_user());
4520 $arr['parent-uri'] = $uri;
4521 $arr['type'] = 'photo';
4523 $arr['resource-id'] = $hash;
4524 $arr['contact-id'] = $owner_record[0]['id'];
4525 $arr['owner-name'] = $owner_record[0]['name'];
4526 $arr['owner-link'] = $owner_record[0]['url'];
4527 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4528 $arr['author-name'] = $owner_record[0]['name'];
4529 $arr['author-link'] = $owner_record[0]['url'];
4530 $arr['author-avatar'] = $owner_record[0]['thumb'];
4532 $arr['allow_cid'] = $allow_cid;
4533 $arr['allow_gid'] = $allow_gid;
4534 $arr['deny_cid'] = $deny_cid;
4535 $arr['deny_gid'] = $deny_gid;
4536 $arr['visible'] = $visibility;
4540 'image/jpeg' => 'jpg',
4541 'image/png' => 'png',
4542 'image/gif' => 'gif'
4545 // adds link to the thumbnail scale photo
4546 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4547 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4550 // do the magic for storing the item in the database and trigger the federation to other contacts
4556 * @param string $type
4558 * @param string $photo_id
4562 function prepare_photo_data($type, $scale, $photo_id)
4565 $user_info = api_get_user($a);
4567 if ($user_info === false) {
4568 throw new ForbiddenException();
4571 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4572 $data_sql = ($scale === false ? "" : "data, ");
4574 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4575 // clients needs to convert this in their way for further processing
4577 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4578 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4579 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4580 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4582 intval(local_user()),
4588 'image/jpeg' => 'jpg',
4589 'image/png' => 'png',
4590 'image/gif' => 'gif'
4593 // prepare output data for photo
4594 if (DBM::is_result($r)) {
4595 $data = ['photo' => $r[0]];
4596 $data['photo']['id'] = $data['photo']['resource-id'];
4597 if ($scale !== false) {
4598 $data['photo']['data'] = base64_encode($data['photo']['data']);
4600 unset($data['photo']['datasize']); //needed only with scale param
4602 if ($type == "xml") {
4603 $data['photo']['links'] = [];
4604 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4605 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4607 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4610 $data['photo']['link'] = [];
4611 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4613 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4614 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4618 unset($data['photo']['resource-id']);
4619 unset($data['photo']['minscale']);
4620 unset($data['photo']['maxscale']);
4622 throw new NotFoundException();
4625 // retrieve item element for getting activities (like, dislike etc.) related to photo
4626 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4627 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4629 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4631 // retrieve comments on photo
4632 $condition = ["`parent` = ? AND `uid` = ? AND (`verb` = ? OR `type`='photo')",
4633 $item[0]['parent'], api_user(), ACTIVITY_POST];
4635 $statuses = Item::selectForUser(api_user(), [], $condition);
4637 // prepare output of comments
4638 $commentData = api_format_items(dba::inArray($statuses), $user_info, false, $type);
4640 if ($type == "xml") {
4642 foreach ($commentData as $comment) {
4643 $comments[$k++ . ":comment"] = $comment;
4646 foreach ($commentData as $comment) {
4647 $comments[] = $comment;
4650 $data['photo']['friendica_comments'] = $comments;
4652 // include info if rights on photo and rights on item are mismatching
4653 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4654 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4655 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4656 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4657 $data['photo']['rights_mismatch'] = $rights_mismatch;
4664 * Similar as /mod/redir.php
4665 * redirect to 'url' after dfrn auth
4667 * Why this when there is mod/redir.php already?
4668 * This use api_user() and api_login()
4671 * c_url: url of remote contact to auth to
4672 * url: string, url to redirect after auth
4674 function api_friendica_remoteauth()
4676 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4677 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4679 if ($url === '' || $c_url === '') {
4680 throw new BadRequestException("Wrong parameters.");
4683 $c_url = normalise_link($c_url);
4687 $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4689 if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
4690 throw new BadRequestException("Unknown contact");
4693 $cid = $contact['id'];
4695 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4697 if ($contact['duplex'] && $contact['issued-id']) {
4698 $orig_id = $contact['issued-id'];
4699 $dfrn_id = '1:' . $orig_id;
4701 if ($contact['duplex'] && $contact['dfrn-id']) {
4702 $orig_id = $contact['dfrn-id'];
4703 $dfrn_id = '0:' . $orig_id;
4706 $sec = random_string();
4708 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4709 'sec' => $sec, 'expire' => time() + 45];
4710 dba::insert('profile_check', $fields);
4712 logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
4713 $dest = ($url ? '&destination_url=' . $url : '');
4715 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4716 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4717 . '&type=profile&sec=' . $sec . $dest
4720 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4723 * @brief Return the item shared, if the item contains only the [share] tag
4725 * @param array $item Sharer item
4726 * @return array|false Shared item or false if not a reshare
4728 function api_share_as_retweet(&$item)
4730 $body = trim($item["body"]);
4732 if (Diaspora::isReshare($body, false)===false) {
4736 /// @TODO "$1" should maybe mean '$1' ?
4737 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4739 * Skip if there is no shared message in there
4740 * we already checked this in diaspora::isReshare()
4741 * but better one more than one less...
4743 if ($body == $attributes) {
4748 // build the fake reshared item
4749 $reshared_item = $item;
4752 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4753 if ($matches[1] != "") {
4754 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4757 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4758 if ($matches[1] != "") {
4759 $author = $matches[1];
4763 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4764 if ($matches[1] != "") {
4765 $profile = $matches[1];
4768 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4769 if ($matches[1] != "") {
4770 $profile = $matches[1];
4774 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4775 if ($matches[1] != "") {
4776 $avatar = $matches[1];
4779 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4780 if ($matches[1] != "") {
4781 $avatar = $matches[1];
4785 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4786 if ($matches[1] != "") {
4787 $link = $matches[1];
4790 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4791 if ($matches[1] != "") {
4792 $link = $matches[1];
4796 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4797 if ($matches[1] != "") {
4798 $posted = $matches[1];
4801 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4802 if ($matches[1] != "") {
4803 $posted = $matches[1];
4806 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4808 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4812 $reshared_item["body"] = $shared_body;
4813 $reshared_item["author-name"] = $author;
4814 $reshared_item["author-link"] = $profile;
4815 $reshared_item["author-avatar"] = $avatar;
4816 $reshared_item["plink"] = $link;
4817 $reshared_item["created"] = $posted;
4818 $reshared_item["edited"] = $posted;
4820 return $reshared_item;
4825 * @param string $profile
4827 * @return string|false
4828 * @todo remove trailing junk from profile url
4829 * @todo pump.io check has to check the website
4831 function api_get_nick($profile)
4836 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4837 dbesc(normalise_link($profile))
4840 if (DBM::is_result($r)) {
4841 $nick = $r[0]["nick"];
4846 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4847 dbesc(normalise_link($profile))
4850 if (DBM::is_result($r)) {
4851 $nick = $r[0]["nick"];
4856 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4857 if ($friendica != $profile) {
4863 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4864 if ($diaspora != $profile) {
4870 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4871 if ($twitter != $profile) {
4878 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4879 if ($StatusnetHost != $profile) {
4880 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4881 if ($StatusnetUser != $profile) {
4882 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4883 $user = json_decode($UserData);
4885 $nick = $user->screen_name;
4891 // To-Do: look at the page if its really a pumpio site
4892 //if (!$nick == "") {
4893 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4894 // if ($pumpio != $profile)
4896 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4909 * @param array $item
4913 function api_in_reply_to($item)
4917 $in_reply_to['status_id'] = null;
4918 $in_reply_to['user_id'] = null;
4919 $in_reply_to['status_id_str'] = null;
4920 $in_reply_to['user_id_str'] = null;
4921 $in_reply_to['screen_name'] = null;
4923 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4924 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
4925 if (DBM::is_result($parent)) {
4926 $in_reply_to['status_id'] = intval($parent['id']);
4928 $in_reply_to['status_id'] = intval($item['parent']);
4931 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4933 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
4934 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
4936 if (DBM::is_result($parent)) {
4937 if ($parent['author-nick'] == "") {
4938 $parent['author-nick'] = api_get_nick($parent['author-link']);
4941 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
4942 $in_reply_to['user_id'] = intval($parent['author-id']);
4943 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
4946 // There seems to be situation, where both fields are identical:
4947 // https://github.com/friendica/friendica/issues/1010
4948 // This is a bugfix for that.
4949 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4950 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4951 $in_reply_to['status_id'] = null;
4952 $in_reply_to['user_id'] = null;
4953 $in_reply_to['status_id_str'] = null;
4954 $in_reply_to['user_id_str'] = null;
4955 $in_reply_to['screen_name'] = null;
4959 return $in_reply_to;
4964 * @param string $text
4968 function api_clean_plain_items($text)
4970 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4972 $text = BBCode::cleanPictureLinks($text);
4973 $URLSearchString = "^\[\]";
4975 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4977 if ($include_entities == "true") {
4978 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4981 // Simplify "attachment" element
4982 $text = api_clean_attachments($text);
4988 * @brief Removes most sharing information for API text export
4990 * @param string $body The original body
4992 * @return string Cleaned body
4994 function api_clean_attachments($body)
4996 $data = BBCode::getAttachmentData($body);
5003 if (isset($data["text"])) {
5004 $body = $data["text"];
5006 if (($body == "") && isset($data["title"])) {
5007 $body = $data["title"];
5009 if (isset($data["url"])) {
5010 $body .= "\n".$data["url"];
5012 $body .= $data["after"];
5019 * @param array $contacts
5023 function api_best_nickname(&$contacts)
5027 if (count($contacts) == 0) {
5031 foreach ($contacts as $contact) {
5032 if ($contact["network"] == "") {
5033 $contact["network"] = "dfrn";
5034 $best_contact = [$contact];
5038 if (sizeof($best_contact) == 0) {
5039 foreach ($contacts as $contact) {
5040 if ($contact["network"] == "dfrn") {
5041 $best_contact = [$contact];
5046 if (sizeof($best_contact) == 0) {
5047 foreach ($contacts as $contact) {
5048 if ($contact["network"] == "dspr") {
5049 $best_contact = [$contact];
5054 if (sizeof($best_contact) == 0) {
5055 foreach ($contacts as $contact) {
5056 if ($contact["network"] == "stat") {
5057 $best_contact = [$contact];
5062 if (sizeof($best_contact) == 0) {
5063 foreach ($contacts as $contact) {
5064 if ($contact["network"] == "pump") {
5065 $best_contact = [$contact];
5070 if (sizeof($best_contact) == 0) {
5071 foreach ($contacts as $contact) {
5072 if ($contact["network"] == "twit") {
5073 $best_contact = [$contact];
5078 if (sizeof($best_contact) == 1) {
5079 $contacts = $best_contact;
5081 $contacts = [$contacts[0]];
5086 * Return all or a specified group of the user with the containing contacts.
5088 * @param string $type Return type (atom, rss, xml, json)
5090 * @return array|string
5092 function api_friendica_group_show($type)
5096 if (api_user() === false) {
5097 throw new ForbiddenException();
5101 $user_info = api_get_user($a);
5102 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5103 $uid = $user_info['uid'];
5105 // get data of the specified group id or all groups if not specified
5108 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5112 // error message if specified gid is not in database
5113 if (!DBM::is_result($r)) {
5114 throw new BadRequestException("gid not available");
5118 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5123 // loop through all groups and retrieve all members for adding data in the user array
5125 foreach ($r as $rr) {
5126 $members = Contact::getByGroupId($rr['id']);
5129 if ($type == "xml") {
5130 $user_element = "users";
5132 foreach ($members as $member) {
5133 $user = api_get_user($a, $member['nurl']);
5134 $users[$k++.":user"] = $user;
5137 $user_element = "user";
5138 foreach ($members as $member) {
5139 $user = api_get_user($a, $member['nurl']);
5143 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5145 return api_format_data("groups", $type, ['group' => $grps]);
5147 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5151 * Delete the specified group of the user.
5153 * @param string $type Return type (atom, rss, xml, json)
5155 * @return array|string
5157 function api_friendica_group_delete($type)
5161 if (api_user() === false) {
5162 throw new ForbiddenException();
5166 $user_info = api_get_user($a);
5167 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5168 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5169 $uid = $user_info['uid'];
5171 // error if no gid specified
5172 if ($gid == 0 || $name == "") {
5173 throw new BadRequestException('gid or name not specified');
5176 // get data of the specified group id
5178 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5182 // error message if specified gid is not in database
5183 if (!DBM::is_result($r)) {
5184 throw new BadRequestException('gid not available');
5187 // get data of the specified group id and group name
5189 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5194 // error message if specified gid is not in database
5195 if (!DBM::is_result($rname)) {
5196 throw new BadRequestException('wrong group name');
5200 $ret = Group::removeByName($uid, $name);
5203 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5204 return api_format_data("group_delete", $type, ['result' => $success]);
5206 throw new BadRequestException('other API error');
5209 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5214 * @param string $type Return type (atom, rss, xml, json)
5216 * @return array|string
5217 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5219 function api_lists_destroy($type)
5223 if (api_user() === false) {
5224 throw new ForbiddenException();
5228 $user_info = api_get_user($a);
5229 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5230 $uid = $user_info['uid'];
5232 // error if no gid specified
5234 throw new BadRequestException('gid not specified');
5237 // get data of the specified group id
5238 $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5239 // error message if specified gid is not in database
5241 throw new BadRequestException('gid not available');
5244 if (Group::remove($gid)) {
5246 'name' => $group['name'],
5247 'id' => intval($gid),
5248 'id_str' => (string) $gid,
5249 'user' => $user_info
5252 return api_format_data("lists", $type, ['lists' => $list]);
5255 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5258 * Add a new group to the database.
5260 * @param string $name Group name
5261 * @param int $uid User ID
5262 * @param array $users List of users to add to the group
5266 function group_create($name, $uid, $users = [])
5268 // error if no name specified
5270 throw new BadRequestException('group name not specified');
5273 // get data of the specified group name
5275 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5279 // error message if specified group name already exists
5280 if (DBM::is_result($rname)) {
5281 throw new BadRequestException('group name already exists');
5284 // check if specified group name is a deleted group
5286 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5290 // error message if specified group name already exists
5291 if (DBM::is_result($rname)) {
5292 $reactivate_group = true;
5296 $ret = Group::create($uid, $name);
5298 $gid = Group::getIdByName($uid, $name);
5300 throw new BadRequestException('other API error');
5304 $erroraddinguser = false;
5306 foreach ($users as $user) {
5307 $cid = $user['cid'];
5308 // check if user really exists as contact
5310 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5314 if (count($contact)) {
5315 Group::addMember($gid, $cid);
5317 $erroraddinguser = true;
5318 $errorusers[] = $cid;
5322 // return success message incl. missing users in array
5323 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5325 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5329 * Create the specified group with the posted array of contacts.
5331 * @param string $type Return type (atom, rss, xml, json)
5333 * @return array|string
5335 function api_friendica_group_create($type)
5339 if (api_user() === false) {
5340 throw new ForbiddenException();
5344 $user_info = api_get_user($a);
5345 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5346 $uid = $user_info['uid'];
5347 $json = json_decode($_POST['json'], true);
5348 $users = $json['user'];
5350 $success = group_create($name, $uid, $users);
5352 return api_format_data("group_create", $type, ['result' => $success]);
5354 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5357 * Create a new group.
5359 * @param string $type Return type (atom, rss, xml, json)
5361 * @return array|string
5362 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5364 function api_lists_create($type)
5368 if (api_user() === false) {
5369 throw new ForbiddenException();
5373 $user_info = api_get_user($a);
5374 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5375 $uid = $user_info['uid'];
5377 $success = group_create($name, $uid);
5378 if ($success['success']) {
5380 'name' => $success['name'],
5381 'id' => intval($success['gid']),
5382 'id_str' => (string) $success['gid'],
5383 'user' => $user_info
5386 return api_format_data("lists", $type, ['lists'=>$grp]);
5389 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5392 * Update the specified group with the posted array of contacts.
5394 * @param string $type Return type (atom, rss, xml, json)
5396 * @return array|string
5398 function api_friendica_group_update($type)
5402 if (api_user() === false) {
5403 throw new ForbiddenException();
5407 $user_info = api_get_user($a);
5408 $uid = $user_info['uid'];
5409 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5410 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5411 $json = json_decode($_POST['json'], true);
5412 $users = $json['user'];
5414 // error if no name specified
5416 throw new BadRequestException('group name not specified');
5419 // error if no gid specified
5421 throw new BadRequestException('gid not specified');
5425 $members = Contact::getByGroupId($gid);
5426 foreach ($members as $member) {
5427 $cid = $member['id'];
5428 foreach ($users as $user) {
5429 $found = ($user['cid'] == $cid ? true : false);
5431 if (!isset($found) || !$found) {
5432 Group::removeMemberByName($uid, $name, $cid);
5437 $erroraddinguser = false;
5439 foreach ($users as $user) {
5440 $cid = $user['cid'];
5441 // check if user really exists as contact
5443 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5448 if (count($contact)) {
5449 Group::addMember($gid, $cid);
5451 $erroraddinguser = true;
5452 $errorusers[] = $cid;
5456 // return success message incl. missing users in array
5457 $status = ($erroraddinguser ? "missing user" : "ok");
5458 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5459 return api_format_data("group_update", $type, ['result' => $success]);
5462 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5465 * Update information about a group.
5467 * @param string $type Return type (atom, rss, xml, json)
5469 * @return array|string
5470 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5472 function api_lists_update($type)
5476 if (api_user() === false) {
5477 throw new ForbiddenException();
5481 $user_info = api_get_user($a);
5482 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5483 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5484 $uid = $user_info['uid'];
5486 // error if no gid specified
5488 throw new BadRequestException('gid not specified');
5491 // get data of the specified group id
5492 $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5493 // error message if specified gid is not in database
5495 throw new BadRequestException('gid not available');
5498 if (Group::update($gid, $name)) {
5501 'id' => intval($gid),
5502 'id_str' => (string) $gid,
5503 'user' => $user_info
5506 return api_format_data("lists", $type, ['lists' => $list]);
5510 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5514 * @param string $type Return type (atom, rss, xml, json)
5516 * @return array|string
5518 function api_friendica_activity($type)
5522 if (api_user() === false) {
5523 throw new ForbiddenException();
5525 $verb = strtolower($a->argv[3]);
5526 $verb = preg_replace("|\..*$|", "", $verb);
5528 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5530 $res = Item::performLike($id, $verb);
5533 if ($type == "xml") {
5538 return api_format_data('ok', $type, ['ok' => $ok]);
5540 throw new BadRequestException('Error adding activity');
5544 /// @TODO move to top of file or somewhere better
5545 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5546 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5547 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5548 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5549 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5550 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5551 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5552 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5553 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5554 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5557 * @brief Returns notifications
5559 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5560 * @return string|array
5562 function api_friendica_notification($type)
5566 if (api_user() === false) {
5567 throw new ForbiddenException();
5570 throw new BadRequestException("Invalid argument count");
5572 $nm = new NotificationsManager();
5574 $notes = $nm->getAll([], "+seen -date", 50);
5576 if ($type == "xml") {
5578 foreach ($notes as $note) {
5579 $xmlnotes[] = ["@attributes" => $note];
5585 return api_format_data("notes", $type, ['note' => $notes]);
5589 * POST request with 'id' param as notification id
5591 * @brief Set notification as seen and returns associated item (if possible)
5593 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5594 * @return string|array
5596 function api_friendica_notification_seen($type)
5599 $user_info = api_get_user($a);
5601 if (api_user() === false || $user_info === false) {
5602 throw new ForbiddenException();
5605 throw new BadRequestException("Invalid argument count");
5608 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5610 $nm = new NotificationsManager();
5611 $note = $nm->getByID($id);
5612 if (is_null($note)) {
5613 throw new BadRequestException("Invalid argument");
5616 $nm->setSeen($note);
5617 if ($note['otype']=='item') {
5618 // would be really better with an ItemsManager and $im->getByID() :-P
5619 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5620 if (DBM::is_result($$item)) {
5621 // we found the item, return it to the user
5622 $ret = api_format_items([$item], $user_info, false, $type);
5623 $data = ['status' => $ret];
5624 return api_format_data("status", $type, $data);
5626 // the item can't be found, but we set the note as seen, so we count this as a success
5628 return api_format_data('result', $type, ['result' => "success"]);
5631 /// @TODO move to top of file or somewhere better
5632 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5633 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5636 * @brief update a direct_message to seen state
5638 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5639 * @return string|array (success result=ok, error result=error with error message)
5641 function api_friendica_direct_messages_setseen($type)
5644 if (api_user() === false) {
5645 throw new ForbiddenException();
5649 $user_info = api_get_user($a);
5650 $uid = $user_info['uid'];
5651 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5653 // return error if id is zero
5655 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5656 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5659 // error message if specified id is not in database
5660 if (!dba::exists('mail', ['id' => $id, 'uid' => $uid])) {
5661 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5662 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5665 // update seen indicator
5666 $result = dba::update('mail', ['seen' => true], ['id' => $id]);
5670 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5671 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5673 $answer = ['result' => 'error', 'message' => 'unknown error'];
5674 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5678 /// @TODO move to top of file or somewhere better
5679 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5682 * @brief search for direct_messages containing a searchstring through api
5684 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5685 * @param string $box
5686 * @return string|array (success: success=true if found and search_result contains found messages,
5687 * success=false if nothing was found, search_result='nothing found',
5688 * error: result=error with error message)
5690 function api_friendica_direct_messages_search($type, $box = "")
5694 if (api_user() === false) {
5695 throw new ForbiddenException();
5699 $user_info = api_get_user($a);
5700 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5701 $uid = $user_info['uid'];
5703 // error if no searchstring specified
5704 if ($searchstring == "") {
5705 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5706 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5709 // get data for the specified searchstring
5711 "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",
5713 dbesc('%'.$searchstring.'%')
5716 $profile_url = $user_info["url"];
5718 // message if nothing was found
5719 if (!DBM::is_result($r)) {
5720 $success = ['success' => false, 'search_results' => 'problem with query'];
5721 } elseif (count($r) == 0) {
5722 $success = ['success' => false, 'search_results' => 'nothing found'];
5725 foreach ($r as $item) {
5726 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5727 $recipient = $user_info;
5728 $sender = api_get_user($a, normalise_link($item['contact-url']));
5729 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5730 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5731 $sender = $user_info;
5734 if (isset($recipient) && isset($sender)) {
5735 $ret[] = api_format_messages($item, $recipient, $sender);
5738 $success = ['success' => true, 'search_results' => $ret];
5741 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5744 /// @TODO move to top of file or somewhere better
5745 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5748 * @brief return data of all the profiles a user has to the client
5750 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5751 * @return string|array
5753 function api_friendica_profile_show($type)
5757 if (api_user() === false) {
5758 throw new ForbiddenException();
5762 $profile_id = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5764 // retrieve general information about profiles for user
5765 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5766 $directory = Config::get('system', 'directory');
5768 // get data of the specified profile id or all profiles of the user if not specified
5769 if ($profile_id != 0) {
5771 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5776 // error message if specified gid is not in database
5777 if (!DBM::is_result($r)) {
5778 throw new BadRequestException("profile_id not available");
5782 "SELECT * FROM `profile` WHERE `uid` = %d",
5786 // loop through all returned profiles and retrieve data and users
5789 foreach ($r as $rr) {
5790 $profile = api_format_items_profiles($rr);
5792 // select all users from contact table, loop and prepare standard return for user data
5795 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5797 intval($rr['profile_id'])
5800 foreach ($nurls as $nurl) {
5801 $user = api_get_user($a, $nurl['nurl']);
5802 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5804 $profile['users'] = $users;
5806 // add prepared profile data to array for final return
5807 if ($type == "xml") {
5808 $profiles[$k++ . ":profile"] = $profile;
5810 $profiles[] = $profile;
5814 // return settings, authenticated user and profiles data
5815 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5817 $result = ['multi_profiles' => $multi_profiles ? true : false,
5818 'global_dir' => $directory,
5819 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5820 'profiles' => $profiles];
5821 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5823 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5826 * Returns a list of saved searches.
5828 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5830 * @param string $type Return format: json or xml
5832 * @return string|array
5834 function api_saved_searches_list($type)
5836 $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
5839 while ($term = $terms->fetch()) {
5841 'created_at' => api_date(time()),
5842 'id' => intval($term['id']),
5843 'id_str' => $term['id'],
5844 'name' => $term['term'],
5846 'query' => $term['term']
5852 return api_format_data("terms", $type, ['terms' => $result]);
5855 /// @TODO move to top of file or somewhere better
5856 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5859 @TODO Maybe open to implement?
5861 [pagename] => api/1.1/statuses/lookup.json
5862 [id] => 605138389168451584
5863 [include_cards] => true
5864 [cards_platform] => Android-12
5865 [include_entities] => true
5866 [include_my_retweet] => 1
5868 [include_reply_count] => true
5869 [include_descendent_reply_count] => true
5873 Not implemented by now:
5874 statuses/retweets_of_me
5879 account/update_location
5880 account/update_profile_background_image
5883 friendica/profile/update
5884 friendica/profile/create
5885 friendica/profile/delete
5887 Not implemented in status.net:
5888 statuses/retweeted_to_me
5889 statuses/retweeted_by_me
5890 direct_messages/destroy
5892 account/update_delivery_device
5893 notifications/follow