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);
1126 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1127 AND `created` > '%s' AND `id` = `parent`",
1132 if (DBM::is_result($r)) {
1133 $posts_day = $r[0]["posts_day"];
1138 if ($posts_day > $throttle_day) {
1139 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1140 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1141 throw new TooManyRequestsException(L10n::tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1145 $throttle_week = Config::get('system', 'throttle_limit_week');
1146 if ($throttle_week > 0) {
1147 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1150 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1151 AND `created` > '%s' AND `id` = `parent`",
1156 if (DBM::is_result($r)) {
1157 $posts_week = $r[0]["posts_week"];
1162 if ($posts_week > $throttle_week) {
1163 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1164 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1165 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));
1169 $throttle_month = Config::get('system', 'throttle_limit_month');
1170 if ($throttle_month > 0) {
1171 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1174 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1175 AND `created` > '%s' AND `id` = `parent`",
1180 if (DBM::is_result($r)) {
1181 $posts_month = $r[0]["posts_month"];
1186 if ($posts_month > $throttle_month) {
1187 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1188 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1189 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));
1193 $_REQUEST['type'] = 'wall';
1196 if (x($_FILES, 'media')) {
1197 // upload the image if we have one
1198 $picture = wall_upload_post($a, false);
1199 if (is_array($picture)) {
1200 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1204 // To-Do: Multiple IDs
1205 if (requestdata('media_ids')) {
1207 "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",
1208 intval(requestdata('media_ids')),
1211 if (DBM::is_result($r)) {
1212 $phototypes = Image::supportedTypes();
1213 $ext = $phototypes[$r[0]['type']];
1214 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1215 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1219 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1221 $_REQUEST['api_source'] = true;
1223 if (!x($_REQUEST, "source")) {
1224 $_REQUEST["source"] = api_source();
1227 // call out normal post function
1230 // this should output the last post (the one we just posted).
1231 return api_status_show($type);
1234 /// @TODO move to top of file or somewhere better
1235 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1236 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1239 * Uploads an image to Friendica.
1242 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1244 function api_media_upload()
1248 if (api_user() === false) {
1250 throw new ForbiddenException();
1255 if (!x($_FILES, 'media')) {
1257 throw new BadRequestException("No media.");
1260 $media = wall_upload_post($a, false);
1263 throw new InternalServerErrorException();
1267 $returndata["media_id"] = $media["id"];
1268 $returndata["media_id_string"] = (string)$media["id"];
1269 $returndata["size"] = $media["size"];
1270 $returndata["image"] = ["w" => $media["width"],
1271 "h" => $media["height"],
1272 "image_type" => $media["type"]];
1274 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1276 return ["media" => $returndata];
1279 /// @TODO move to top of file or somewhere better
1280 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1284 * @param string $type Return type (atom, rss, xml, json)
1286 * @return array|string
1288 function api_status_show($type)
1292 $user_info = api_get_user($a);
1294 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1296 if ($type == "raw") {
1297 $privacy_sql = "AND NOT `private`";
1302 // get last public wall message
1303 $condition = ["`owner-id` = ? AND `uid` = ? AND `type` != 'activity' ".$privacy_sql,
1304 $user_info['pid'], api_user()];
1305 $lastwall = dba::selectFirst('item', [], $condition, ['order' => ['id' => true]]);
1307 if (DBM::is_result($lastwall)) {
1308 $in_reply_to = api_in_reply_to($lastwall);
1310 $converted = api_convert_item($lastwall);
1312 if ($type == "xml") {
1313 $geo = "georss:point";
1319 'created_at' => api_date($lastwall['created']),
1320 'id' => intval($lastwall['id']),
1321 'id_str' => (string) $lastwall['id'],
1322 'text' => $converted["text"],
1323 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1324 'truncated' => false,
1325 'in_reply_to_status_id' => $in_reply_to['status_id'],
1326 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1327 'in_reply_to_user_id' => $in_reply_to['user_id'],
1328 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1329 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1330 'user' => $user_info,
1332 'coordinates' => "",
1334 'contributors' => "",
1335 'is_quote_status' => false,
1336 'retweet_count' => 0,
1337 'favorite_count' => 0,
1338 'favorited' => $lastwall['starred'] ? true : false,
1339 'retweeted' => false,
1340 'possibly_sensitive' => false,
1342 'statusnet_html' => $converted["html"],
1343 'statusnet_conversation_id' => $lastwall['parent'],
1344 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1347 if (count($converted["attachments"]) > 0) {
1348 $status_info["attachments"] = $converted["attachments"];
1351 if (count($converted["entities"]) > 0) {
1352 $status_info["entities"] = $converted["entities"];
1355 if ($status_info["source"] == 'web') {
1356 $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $user_info['url']);
1357 } elseif (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $status_info["source"]) {
1358 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $user_info['url']).')');
1361 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1362 unset($status_info["user"]["uid"]);
1363 unset($status_info["user"]["self"]);
1365 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1367 if ($type == "raw") {
1368 return $status_info;
1371 return api_format_data("statuses", $type, ['status' => $status_info]);
1376 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1377 * The author's most recent status will be returned inline.
1379 * @param string $type Return type (atom, rss, xml, json)
1380 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1382 function api_users_show($type)
1386 $user_info = api_get_user($a);
1388 $condition = ["`owner-id` = ? AND `uid` = ? AND `verb` = ? AND `type` != 'activity' AND NOT `private`",
1389 $user_info['pid'], api_user(), ACTIVITY_POST];
1390 $lastwall = dba::selectFirst('item', [], $condition, ['order' => ['id' => true]]);
1392 if (DBM::is_result($lastwall)) {
1393 $in_reply_to = api_in_reply_to($lastwall);
1395 $converted = api_convert_item($lastwall);
1397 if ($type == "xml") {
1398 $geo = "georss:point";
1403 $user_info['status'] = [
1404 'text' => $converted["text"],
1405 'truncated' => false,
1406 'created_at' => api_date($lastwall['created']),
1407 'in_reply_to_status_id' => $in_reply_to['status_id'],
1408 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1409 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1410 'id' => intval($lastwall['contact-id']),
1411 'id_str' => (string) $lastwall['contact-id'],
1412 'in_reply_to_user_id' => $in_reply_to['user_id'],
1413 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1414 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1416 'favorited' => $lastwall['starred'] ? true : false,
1417 'statusnet_html' => $converted["html"],
1418 'statusnet_conversation_id' => $lastwall['parent'],
1419 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1422 if (count($converted["attachments"]) > 0) {
1423 $user_info["status"]["attachments"] = $converted["attachments"];
1426 if (count($converted["entities"]) > 0) {
1427 $user_info["status"]["entities"] = $converted["entities"];
1430 if ($user_info["status"]["source"] == 'web') {
1431 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $user_info['url']);
1434 if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
1435 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $user_info['url']) . ')');
1439 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1440 unset($user_info["uid"]);
1441 unset($user_info["self"]);
1443 return api_format_data("user", $type, ['user' => $user_info]);
1446 /// @TODO move to top of file or somewhere better
1447 api_register_func('api/users/show', 'api_users_show');
1448 api_register_func('api/externalprofile/show', 'api_users_show');
1451 * Search a public user account.
1453 * @param string $type Return type (atom, rss, xml, json)
1455 * @return array|string
1456 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1458 function api_users_search($type)
1464 if (x($_GET, 'q')) {
1465 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1467 if (!DBM::is_result($r)) {
1468 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1471 if (DBM::is_result($r)) {
1473 foreach ($r as $user) {
1474 $user_info = api_get_user($a, $user["id"]);
1476 if ($type == "xml") {
1477 $userlist[$k++.":user"] = $user_info;
1479 $userlist[] = $user_info;
1482 $userlist = ["users" => $userlist];
1484 throw new BadRequestException("User ".$_GET["q"]." not found.");
1487 throw new BadRequestException("No user specified.");
1490 return api_format_data("users", $type, $userlist);
1493 /// @TODO move to top of file or somewhere better
1494 api_register_func('api/users/search', 'api_users_search');
1497 * Return user objects
1499 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1501 * @param string $type Return format: json or xml
1503 * @return array|string
1504 * @throws NotFoundException if the results are empty.
1506 function api_users_lookup($type)
1510 if (x($_REQUEST['user_id'])) {
1511 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1513 $users[] = api_get_user(get_app(), $id);
1518 if (empty($users)) {
1519 throw new NotFoundException;
1522 return api_format_data("users", $type, ['users' => $users]);
1525 /// @TODO move to top of file or somewhere better
1526 api_register_func('api/users/lookup', 'api_users_lookup', true);
1529 * Returns statuses that match a specified query.
1531 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1533 * @param string $type Return format: json, xml, atom, rss
1535 * @return array|string
1536 * @throws BadRequestException if the "q" parameter is missing.
1538 function api_search($type)
1541 $user_info = api_get_user($a);
1543 if (api_user() === false || $user_info === false) {
1544 throw new ForbiddenException();
1549 if (!x($_REQUEST, 'q')) {
1550 throw new BadRequestException("q parameter is required.");
1553 if (x($_REQUEST, 'rpp')) {
1554 $count = $_REQUEST['rpp'];
1555 } elseif (x($_REQUEST, 'count')) {
1556 $count = $_REQUEST['count'];
1561 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1562 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1563 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1565 $start = $page * $count;
1567 $condition = ["`verb` = ? AND `item`.`id` > ?
1568 AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1569 AND `item`.`body` LIKE CONCAT('%',?,'%')",
1570 ACTIVITY_POST, $since_id, api_user(), $_REQUEST['q']];
1573 $condition[0] .= " AND `item`.`id` <= ?";
1574 $condition[] = $max_id;
1577 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1578 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1580 $data['status'] = api_format_items(dba::inArray($statuses), $user_info);
1582 return api_format_data("statuses", $type, $data);
1585 /// @TODO move to top of file or somewhere better
1586 api_register_func('api/search/tweets', 'api_search', true);
1587 api_register_func('api/search', 'api_search', true);
1590 * Returns the most recent statuses posted by the user and the users they follow.
1592 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1594 * @param string $type Return type (atom, rss, xml, json)
1596 * @todo Optional parameters
1597 * @todo Add reply info
1599 function api_statuses_home_timeline($type)
1602 $user_info = api_get_user($a);
1604 if (api_user() === false || $user_info === false) {
1605 throw new ForbiddenException();
1608 unset($_REQUEST["user_id"]);
1609 unset($_GET["user_id"]);
1611 unset($_REQUEST["screen_name"]);
1612 unset($_GET["screen_name"]);
1614 // get last network messages
1617 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1618 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1622 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1623 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1624 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1625 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1626 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1628 $start = $page * $count;
1630 $condition = ["`uid` = ? AND `verb` = ? AND `item`.`id` > ?", api_user(), ACTIVITY_POST, $since_id];
1633 $condition[0] .= " AND `item`.`id` <= ?";
1634 $condition[] = $max_id;
1636 if ($exclude_replies > 0) {
1637 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1639 if ($conversation_id > 0) {
1640 $condition[0] .= " AND `item`.`parent` = ?";
1641 $condition[] = $conversation_id;
1644 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1645 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1647 $items = dba::inArray($statuses);
1649 $ret = api_format_items($items, $user_info, false, $type);
1651 // Set all posts from the query above to seen
1653 foreach ($items as $item) {
1654 $idarray[] = intval($item["id"]);
1657 if (!empty($idarray)) {
1658 $unseen = dba::exists('item', ['unseen' => true, 'id' => $idarray]);
1660 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1664 $data = ['status' => $ret];
1668 $data = api_rss_extra($a, $data, $user_info);
1672 return api_format_data("statuses", $type, $data);
1675 /// @TODO move to top of file or somewhere better
1676 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1677 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1680 * Returns the most recent statuses from public users.
1682 * @param string $type Return type (atom, rss, xml, json)
1684 * @return array|string
1686 function api_statuses_public_timeline($type)
1689 $user_info = api_get_user($a);
1691 if (api_user() === false || $user_info === false) {
1692 throw new ForbiddenException();
1695 // get last network messages
1698 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1699 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1703 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1704 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1705 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1706 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1707 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1709 $start = $page * $count;
1712 if ($exclude_replies && !$conversation_id) {
1713 $condition = ["`verb` = ? AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall`",
1714 ACTIVITY_POST, $since_id];
1717 $condition[0] .= " AND `thread`.`iid` <= ?";
1718 $condition[] = $max_id;
1721 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1722 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1724 $r = dba::inArray($statuses);
1726 $condition = ["`verb` = ? AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin`",
1727 ACTIVITY_POST, $since_id];
1730 $condition[0] .= " AND `item`.`id` <= ?";
1731 $condition[] = $max_id;
1733 if ($conversation_id > 0) {
1734 $condition[0] .= " AND `item`.`parent` = ?";
1735 $condition[] = $conversation_id;
1738 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1739 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1741 $r = dba::inArray($statuses);
1744 $ret = api_format_items($r, $user_info, false, $type);
1746 $data = ['status' => $ret];
1750 $data = api_rss_extra($a, $data, $user_info);
1754 return api_format_data("statuses", $type, $data);
1757 /// @TODO move to top of file or somewhere better
1758 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1761 * Returns the most recent statuses posted by users this node knows about.
1763 * @brief Returns the list of public federated posts this node knows about
1765 * @param string $type Return format: json, xml, atom, rss
1766 * @return array|string
1767 * @throws ForbiddenException
1769 function api_statuses_networkpublic_timeline($type)
1772 $user_info = api_get_user($a);
1774 if (api_user() === false || $user_info === false) {
1775 throw new ForbiddenException();
1778 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1779 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1782 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1783 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1787 $start = ($page - 1) * $count;
1789 $condition = ["`uid` = 0 AND `verb` = ? AND `thread`.`iid` > ? AND NOT `private`",
1790 ACTIVITY_POST, $since_id];
1793 $condition[0] .= " AND `thread`.`iid` <= ?";
1794 $condition[] = $max_id;
1797 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1798 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1800 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
1802 $data = ['status' => $ret];
1806 $data = api_rss_extra($a, $data, $user_info);
1810 return api_format_data("statuses", $type, $data);
1813 /// @TODO move to top of file or somewhere better
1814 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1817 * Returns a single status.
1819 * @param string $type Return type (atom, rss, xml, json)
1821 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1823 function api_statuses_show($type)
1826 $user_info = api_get_user($a);
1828 if (api_user() === false || $user_info === false) {
1829 throw new ForbiddenException();
1833 $id = intval($a->argv[3]);
1836 $id = intval($_REQUEST["id"]);
1841 $id = intval($a->argv[4]);
1844 logger('API: api_statuses_show: ' . $id);
1846 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1848 // try to fetch the item for the local user - or the public item, if there is no local one
1849 $uri_item = dba::selectFirst('item', ['uri'], ['id' => $id]);
1850 if (!DBM::is_result($uri_item)) {
1851 throw new BadRequestException("There is no status with this id.");
1854 $item = dba::selectFirst('item', ['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1855 if (!DBM::is_result($item)) {
1856 throw new BadRequestException("There is no status with this id.");
1861 if ($conversation) {
1862 $condition = ['parent' => $id, 'verb' => ACTIVITY_POST];
1863 $params = ['order' => ['id' => true]];
1865 $condition = ['id' => $id, 'verb' => ACTIVITY_POST];
1869 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1871 /// @TODO How about copying this to above methods which don't check $r ?
1872 if (!DBM::is_result($statuses)) {
1873 throw new BadRequestException("There is no status with this id.");
1876 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
1878 if ($conversation) {
1879 $data = ['status' => $ret];
1880 return api_format_data("statuses", $type, $data);
1882 $data = ['status' => $ret[0]];
1883 return api_format_data("status", $type, $data);
1887 /// @TODO move to top of file or somewhere better
1888 api_register_func('api/statuses/show', 'api_statuses_show', true);
1892 * @param string $type Return type (atom, rss, xml, json)
1894 * @todo nothing to say?
1896 function api_conversation_show($type)
1899 $user_info = api_get_user($a);
1901 if (api_user() === false || $user_info === false) {
1902 throw new ForbiddenException();
1906 $id = intval($a->argv[3]);
1907 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1908 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1912 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1913 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1915 $start = $page*$count;
1918 $id = intval($_REQUEST["id"]);
1923 $id = intval($a->argv[4]);
1926 logger('API: api_conversation_show: '.$id);
1928 // try to fetch the item for the local user - or the public item, if there is no local one
1929 $item = dba::selectFirst('item', ['parent-uri'], ['id' => $id]);
1930 if (!DBM::is_result($item)) {
1931 throw new BadRequestException("There is no status with this id.");
1934 $parent = dba::selectFirst('item', ['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1935 if (!DBM::is_result($parent)) {
1936 throw new BadRequestException("There is no status with this id.");
1939 $id = $parent['id'];
1941 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `verb` = ? AND `item`.`id` > ?",
1942 $id, api_user(), ACTIVITY_POST, $since_id];
1945 $condition[0] .= " AND `item`.`id` <= ?";
1946 $condition[] = $max_id;
1949 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1950 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1952 if (!DBM::is_result($statuses)) {
1953 throw new BadRequestException("There is no status with id $id.");
1956 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
1958 $data = ['status' => $ret];
1959 return api_format_data("statuses", $type, $data);
1962 /// @TODO move to top of file or somewhere better
1963 api_register_func('api/conversation/show', 'api_conversation_show', true);
1964 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1969 * @param string $type Return type (atom, rss, xml, json)
1971 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1973 function api_statuses_repeat($type)
1979 if (api_user() === false) {
1980 throw new ForbiddenException();
1986 $id = intval($a->argv[3]);
1989 $id = intval($_REQUEST["id"]);
1994 $id = intval($a->argv[4]);
1997 logger('API: api_statuses_repeat: '.$id);
1999 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2000 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2002 if (DBM::is_result($item) && $item['body'] != "") {
2003 if (strpos($item['body'], "[/share]") !== false) {
2004 $pos = strpos($item['body'], "[share");
2005 $post = substr($item['body'], $pos);
2007 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2009 $post .= $item['body'];
2010 $post .= "[/share]";
2012 $_REQUEST['body'] = $post;
2013 $_REQUEST['profile_uid'] = api_user();
2014 $_REQUEST['type'] = 'wall';
2015 $_REQUEST['api_source'] = true;
2017 if (!x($_REQUEST, "source")) {
2018 $_REQUEST["source"] = api_source();
2023 throw new ForbiddenException();
2026 // this should output the last post (the one we just posted).
2028 return api_status_show($type);
2031 /// @TODO move to top of file or somewhere better
2032 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2035 * Destroys a specific status.
2037 * @param string $type Return type (atom, rss, xml, json)
2039 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2041 function api_statuses_destroy($type)
2045 if (api_user() === false) {
2046 throw new ForbiddenException();
2052 $id = intval($a->argv[3]);
2055 $id = intval($_REQUEST["id"]);
2060 $id = intval($a->argv[4]);
2063 logger('API: api_statuses_destroy: '.$id);
2065 $ret = api_statuses_show($type);
2067 Item::deleteForUser(['id' => $id], api_user());
2072 /// @TODO move to top of file or somewhere better
2073 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2076 * Returns the most recent mentions.
2078 * @param string $type Return type (atom, rss, xml, json)
2080 * @see http://developer.twitter.com/doc/get/statuses/mentions
2082 function api_statuses_mentions($type)
2085 $user_info = api_get_user($a);
2087 if (api_user() === false || $user_info === false) {
2088 throw new ForbiddenException();
2091 unset($_REQUEST["user_id"]);
2092 unset($_GET["user_id"]);
2094 unset($_REQUEST["screen_name"]);
2095 unset($_GET["screen_name"]);
2097 // get last network messages
2100 $since_id = defaults($_REQUEST, 'since_id', 0);
2101 $max_id = defaults($_REQUEST, 'max_id' , 0);
2102 $count = defaults($_REQUEST, 'count' , 20);
2103 $page = defaults($_REQUEST, 'page' , 1);
2108 $start = ($page - 1) * $count;
2110 $condition = ["`uid` = ? AND `verb` = ? AND `item`.`id` > ? AND `author-id` != ?
2111 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = ? AND `mention` AND NOT `ignored`)",
2112 api_user(), ACTIVITY_POST, $since_id, $user_info['pid'], api_user()];
2115 $condition[0] .= " AND `item`.`id` <= ?";
2116 $condition[] = $max_id;
2119 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2120 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2122 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
2124 $data = ['status' => $ret];
2128 $data = api_rss_extra($a, $data, $user_info);
2132 return api_format_data("statuses", $type, $data);
2135 /// @TODO move to top of file or somewhere better
2136 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2137 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2140 * Returns the most recent statuses posted by the user.
2142 * @brief Returns a user's public timeline
2144 * @param string $type Either "json" or "xml"
2145 * @return string|array
2146 * @throws ForbiddenException
2147 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2149 function api_statuses_user_timeline($type)
2152 $user_info = api_get_user($a);
2154 if (api_user() === false || $user_info === false) {
2155 throw new ForbiddenException();
2159 "api_statuses_user_timeline: api_user: ". api_user() .
2160 "\nuser_info: ".print_r($user_info, true) .
2161 "\n_REQUEST: ".print_r($_REQUEST, true),
2165 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2166 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2167 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2168 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2171 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2172 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2176 $start = ($page - 1) * $count;
2178 $condition = ["`uid` = ? AND `verb` = ? AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2179 api_user(), ACTIVITY_POST, $since_id, $user_info['cid']];
2181 if ($user_info['self'] == 1) {
2182 $condition[0] .= ' AND `item`.`wall` ';
2185 if ($exclude_replies > 0) {
2186 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2189 if ($conversation_id > 0) {
2190 $condition[0] .= " AND `item`.`parent` = ?";
2191 $condition[] = $conversation_id;
2195 $condition[0] .= " AND `item`.`id` <= ?";
2196 $condition[] = $max_id;
2199 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2200 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2202 $ret = api_format_items(dba::inArray($statuses), $user_info, true, $type);
2204 $data = ['status' => $ret];
2208 $data = api_rss_extra($a, $data, $user_info);
2212 return api_format_data("statuses", $type, $data);
2215 /// @TODO move to top of file or somewhere better
2216 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2219 * Star/unstar an item.
2220 * param: id : id of the item
2222 * @param string $type Return type (atom, rss, xml, json)
2224 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2226 function api_favorites_create_destroy($type)
2230 if (api_user() === false) {
2231 throw new ForbiddenException();
2234 // for versioned api.
2235 /// @TODO We need a better global soluton
2236 $action_argv_id = 2;
2237 if ($a->argv[1] == "1.1") {
2238 $action_argv_id = 3;
2241 if ($a->argc <= $action_argv_id) {
2242 throw new BadRequestException("Invalid request.");
2244 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2245 if ($a->argc == $action_argv_id + 2) {
2246 $itemid = intval($a->argv[$action_argv_id + 1]);
2248 /// @TODO use x() to check if _REQUEST contains 'id'
2249 $itemid = intval($_REQUEST['id']);
2252 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2254 if (!DBM::is_result($item)) {
2255 throw new BadRequestException("Invalid item.");
2260 $item['starred'] = 1;
2263 $item['starred'] = 0;
2266 throw new BadRequestException("Invalid action ".$action);
2269 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2272 throw new InternalServerErrorException("DB error");
2276 $user_info = api_get_user($a);
2277 $rets = api_format_items([$item], $user_info, false, $type);
2280 $data = ['status' => $ret];
2284 $data = api_rss_extra($a, $data, $user_info);
2287 return api_format_data("status", $type, $data);
2290 /// @TODO move to top of file or somewhere better
2291 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2292 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2295 * Returns the most recent favorite statuses.
2297 * @param string $type Return type (atom, rss, xml, json)
2299 * @return string|array
2301 function api_favorites($type)
2306 $user_info = api_get_user($a);
2308 if (api_user() === false || $user_info === false) {
2309 throw new ForbiddenException();
2314 // in friendica starred item are private
2315 // return favorites only for self
2316 logger('api_favorites: self:' . $user_info['self']);
2318 if ($user_info['self'] == 0) {
2322 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2323 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2324 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2325 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2330 $start = $page*$count;
2332 $condition = ["`uid` = ? AND `verb` = ? AND `id` > ? AND `starred`",
2333 api_user(), ACTIVITY_POST, $since_id];
2335 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2338 $condition[0] .= " AND `item`.`id` <= ?";
2339 $condition[] = $max_id;
2342 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2344 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
2347 $data = ['status' => $ret];
2351 $data = api_rss_extra($a, $data, $user_info);
2354 return api_format_data("statuses", $type, $data);
2357 /// @TODO move to top of file or somewhere better
2358 api_register_func('api/favorites', 'api_favorites', true);
2362 * @param array $item
2363 * @param array $recipient
2364 * @param array $sender
2368 function api_format_messages($item, $recipient, $sender)
2370 // standard meta information
2372 'id' => $item['id'],
2373 'sender_id' => $sender['id'] ,
2375 'recipient_id' => $recipient['id'],
2376 'created_at' => api_date($item['created']),
2377 'sender_screen_name' => $sender['screen_name'],
2378 'recipient_screen_name' => $recipient['screen_name'],
2379 'sender' => $sender,
2380 'recipient' => $recipient,
2382 'friendica_seen' => $item['seen'],
2383 'friendica_parent_uri' => $item['parent-uri'],
2386 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2387 unset($ret["sender"]["uid"]);
2388 unset($ret["sender"]["self"]);
2389 unset($ret["recipient"]["uid"]);
2390 unset($ret["recipient"]["self"]);
2392 //don't send title to regular StatusNET requests to avoid confusing these apps
2393 if (x($_GET, 'getText')) {
2394 $ret['title'] = $item['title'];
2395 if ($_GET['getText'] == 'html') {
2396 $ret['text'] = BBCode::convert($item['body'], false);
2397 } elseif ($_GET['getText'] == 'plain') {
2398 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2401 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2403 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2404 unset($ret['sender']);
2405 unset($ret['recipient']);
2413 * @param array $item
2417 function api_convert_item($item)
2419 $body = $item['body'];
2420 $attachments = api_get_attachments($body);
2422 // Workaround for ostatus messages where the title is identically to the body
2423 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2424 $statusbody = trim(HTML::toPlaintext($html, 0));
2426 // handle data: images
2427 $statusbody = api_format_items_embeded_images($item, $statusbody);
2429 $statustitle = trim($item['title']);
2431 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2432 $statustext = trim($statusbody);
2434 $statustext = trim($statustitle."\n\n".$statusbody);
2437 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2438 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2441 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2443 // Workaround for clients with limited HTML parser functionality
2444 $search = ["<br>", "<blockquote>", "</blockquote>",
2445 "<h1>", "</h1>", "<h2>", "</h2>",
2446 "<h3>", "</h3>", "<h4>", "</h4>",
2447 "<h5>", "</h5>", "<h6>", "</h6>"];
2448 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2449 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2450 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2451 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2452 $statushtml = str_replace($search, $replace, $statushtml);
2454 if ($item['title'] != "") {
2455 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2459 $oldtext = $statushtml;
2460 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2461 } while ($oldtext != $statushtml);
2463 if (substr($statushtml, 0, 4) == '<br>') {
2464 $statushtml = substr($statushtml, 4);
2467 if (substr($statushtml, 0, -4) == '<br>') {
2468 $statushtml = substr($statushtml, -4);
2471 // feeds without body should contain the link
2472 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2473 $statushtml .= BBCode::convert($item['plink']);
2476 $entities = api_get_entitities($statustext, $body);
2479 "text" => $statustext,
2480 "html" => $statushtml,
2481 "attachments" => $attachments,
2482 "entities" => $entities
2488 * @param string $body
2492 function api_get_attachments(&$body)
2495 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2497 $URLSearchString = "^\[\]";
2498 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2506 foreach ($images[1] as $image) {
2507 $imagedata = Image::getInfoFromURL($image);
2510 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2514 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2515 foreach ($images[0] as $orig) {
2516 $body = str_replace($orig, "", $body);
2520 return $attachments;
2525 * @param string $text
2526 * @param string $bbcode
2529 * @todo Links at the first character of the post
2531 function api_get_entitities(&$text, $bbcode)
2533 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2535 if ($include_entities != "true") {
2536 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2538 foreach ($images[1] as $image) {
2539 $replace = proxy_url($image);
2540 $text = str_replace($image, $replace, $text);
2545 $bbcode = BBCode::cleanPictureLinks($bbcode);
2547 // Change pure links in text to bbcode uris
2548 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2551 $entities["hashtags"] = [];
2552 $entities["symbols"] = [];
2553 $entities["urls"] = [];
2554 $entities["user_mentions"] = [];
2556 $URLSearchString = "^\[\]";
2558 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2560 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2561 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2562 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2564 $bbcode = preg_replace(
2565 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2566 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2569 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2571 $bbcode = preg_replace(
2572 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2573 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2576 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2578 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2580 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2581 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2584 foreach ($urls[1] as $id => $url) {
2585 //$start = strpos($text, $url, $offset);
2586 $start = iconv_strpos($text, $url, 0, "UTF-8");
2587 if (!($start === false)) {
2588 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2592 ksort($ordered_urls);
2595 //foreach ($urls[1] AS $id=>$url) {
2596 foreach ($ordered_urls as $url) {
2597 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2598 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2600 $display_url = $url["title"];
2602 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2603 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2605 if (strlen($display_url) > 26) {
2606 $display_url = substr($display_url, 0, 25)."…";
2610 //$start = strpos($text, $url, $offset);
2611 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2612 if (!($start === false)) {
2613 $entities["urls"][] = ["url" => $url["url"],
2614 "expanded_url" => $url["url"],
2615 "display_url" => $display_url,
2616 "indices" => [$start, $start+strlen($url["url"])]];
2617 $offset = $start + 1;
2621 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2622 $ordered_images = [];
2623 foreach ($images[1] as $image) {
2624 //$start = strpos($text, $url, $offset);
2625 $start = iconv_strpos($text, $image, 0, "UTF-8");
2626 if (!($start === false)) {
2627 $ordered_images[$start] = $image;
2630 //$entities["media"] = array();
2633 foreach ($ordered_images as $url) {
2634 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2635 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2637 if (strlen($display_url) > 26) {
2638 $display_url = substr($display_url, 0, 25)."…";
2641 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2642 if (!($start === false)) {
2643 $image = Image::getInfoFromURL($url);
2645 // If image cache is activated, then use the following sizes:
2646 // thumb (150), small (340), medium (600) and large (1024)
2647 if (!Config::get("system", "proxy_disabled")) {
2648 $media_url = proxy_url($url);
2651 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2652 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2654 if (($image[0] > 150) || ($image[1] > 150)) {
2655 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2656 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2659 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2660 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2662 if (($image[0] > 600) || ($image[1] > 600)) {
2663 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2664 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2668 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2671 $entities["media"][] = [
2673 "id_str" => (string)$start+1,
2674 "indices" => [$start, $start+strlen($url)],
2675 "media_url" => normalise_link($media_url),
2676 "media_url_https" => $media_url,
2678 "display_url" => $display_url,
2679 "expanded_url" => $url,
2683 $offset = $start + 1;
2692 * @param array $item
2693 * @param string $text
2697 function api_format_items_embeded_images($item, $text)
2699 $text = preg_replace_callback(
2700 '|data:image/([^;]+)[^=]+=*|m',
2701 function () use ($item) {
2702 return System::baseUrl() . '/display/' . $item['guid'];
2710 * @brief return <a href='url'>name</a> as array
2712 * @param string $txt text
2717 function api_contactlink_to_array($txt)
2720 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2721 if ($r && count($match)==3) {
2723 'name' => $match[2],
2737 * @brief return likes, dislikes and attend status for item
2739 * @param array $item array
2740 * @param string $type Return type (atom, rss, xml, json)
2743 * likes => int count,
2744 * dislikes => int count
2746 function api_format_items_activities(&$item, $type = "json")
2755 'attendmaybe' => [],
2759 'SELECT * FROM `item`
2760 WHERE `uid` = %d AND `thr-parent` = "%s" AND `visible` AND NOT `deleted`',
2761 intval($item['uid']),
2765 foreach ($items as $i) {
2766 // not used as result should be structured like other user data
2767 //builtin_activity_puller($i, $activities);
2769 // get user data and add it to the array of the activity
2770 $user = api_get_user($a, $i['author-id']);
2771 switch ($i['verb']) {
2773 $activities['like'][] = $user;
2775 case ACTIVITY_DISLIKE:
2776 $activities['dislike'][] = $user;
2778 case ACTIVITY_ATTEND:
2779 $activities['attendyes'][] = $user;
2781 case ACTIVITY_ATTENDNO:
2782 $activities['attendno'][] = $user;
2784 case ACTIVITY_ATTENDMAYBE:
2785 $activities['attendmaybe'][] = $user;
2792 if ($type == "xml") {
2793 $xml_activities = [];
2794 foreach ($activities as $k => $v) {
2795 // change xml element from "like" to "friendica:like"
2796 $xml_activities["friendica:".$k] = $v;
2797 // add user data into xml output
2799 foreach ($v as $user) {
2800 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2803 $activities = $xml_activities;
2811 * @brief return data from profiles
2813 * @param array $profile_row array containing data from db table 'profile'
2816 function api_format_items_profiles($profile_row)
2819 'profile_id' => $profile_row['id'],
2820 'profile_name' => $profile_row['profile-name'],
2821 'is_default' => $profile_row['is-default'] ? true : false,
2822 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2823 'profile_photo' => $profile_row['photo'],
2824 'profile_thumb' => $profile_row['thumb'],
2825 'publish' => $profile_row['publish'] ? true : false,
2826 'net_publish' => $profile_row['net-publish'] ? true : false,
2827 'description' => $profile_row['pdesc'],
2828 'date_of_birth' => $profile_row['dob'],
2829 'address' => $profile_row['address'],
2830 'city' => $profile_row['locality'],
2831 'region' => $profile_row['region'],
2832 'postal_code' => $profile_row['postal-code'],
2833 'country' => $profile_row['country-name'],
2834 'hometown' => $profile_row['hometown'],
2835 'gender' => $profile_row['gender'],
2836 'marital' => $profile_row['marital'],
2837 'marital_with' => $profile_row['with'],
2838 'marital_since' => $profile_row['howlong'],
2839 'sexual' => $profile_row['sexual'],
2840 'politic' => $profile_row['politic'],
2841 'religion' => $profile_row['religion'],
2842 'public_keywords' => $profile_row['pub_keywords'],
2843 'private_keywords' => $profile_row['prv_keywords'],
2844 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2845 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2846 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2847 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2848 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2849 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2850 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2851 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2852 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2853 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2854 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2855 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2856 'homepage' => $profile_row['homepage'],
2863 * @brief format items to be returned by api
2865 * @param array $r array of items
2866 * @param array $user_info
2867 * @param bool $filter_user filter items by $user_info
2868 * @param string $type Return type (atom, rss, xml, json)
2870 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2876 foreach ($r as $item) {
2877 localize_item($item);
2878 list($status_user, $owner_user) = api_item_get_user($a, $item);
2880 // Look if the posts are matching if they should be filtered by user id
2881 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2885 $in_reply_to = api_in_reply_to($item);
2887 $converted = api_convert_item($item);
2889 if ($type == "xml") {
2890 $geo = "georss:point";
2896 'text' => $converted["text"],
2897 'truncated' => false,
2898 'created_at'=> api_date($item['created']),
2899 'in_reply_to_status_id' => $in_reply_to['status_id'],
2900 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2901 'source' => (($item['app']) ? $item['app'] : 'web'),
2902 'id' => intval($item['id']),
2903 'id_str' => (string) intval($item['id']),
2904 'in_reply_to_user_id' => $in_reply_to['user_id'],
2905 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2906 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2908 'favorited' => $item['starred'] ? true : false,
2909 'user' => $status_user ,
2910 'friendica_owner' => $owner_user,
2911 //'entities' => NULL,
2912 'statusnet_html' => $converted["html"],
2913 'statusnet_conversation_id' => $item['parent'],
2914 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2915 'friendica_activities' => api_format_items_activities($item, $type),
2918 if (count($converted["attachments"]) > 0) {
2919 $status["attachments"] = $converted["attachments"];
2922 if (count($converted["entities"]) > 0) {
2923 $status["entities"] = $converted["entities"];
2926 if ($status["source"] == 'web') {
2927 $status["source"] = ContactSelector::networkToName($item['network'], $user_info['url']);
2928 } elseif (ContactSelector::networkToName($item['network'], $user_info['url']) != $status["source"]) {
2929 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $user_info['url']).')');
2932 if ($item["id"] == $item["parent"]) {
2933 $retweeted_item = api_share_as_retweet($item);
2934 if ($retweeted_item !== false) {
2935 $retweeted_status = $status;
2937 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
2938 } catch (BadRequestException $e) {
2939 // user not found. should be found?
2940 /// @todo check if the user should be always found
2941 $retweeted_status["user"] = [];
2944 $rt_converted = api_convert_item($retweeted_item);
2946 $retweeted_status['text'] = $rt_converted["text"];
2947 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2948 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2949 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2950 $status['retweeted_status'] = $retweeted_status;
2954 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2955 unset($status["user"]["uid"]);
2956 unset($status["user"]["self"]);
2958 if ($item["coord"] != "") {
2959 $coords = explode(' ', $item["coord"]);
2960 if (count($coords) == 2) {
2961 if ($type == "json") {
2962 $status["geo"] = ['type' => 'Point',
2963 'coordinates' => [(float) $coords[0],
2964 (float) $coords[1]]];
2965 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2966 $status["georss:point"] = $item["coord"];
2976 * Returns the remaining number of API requests available to the user before the API limit is reached.
2978 * @param string $type Return type (atom, rss, xml, json)
2980 * @return array|string
2982 function api_account_rate_limit_status($type)
2984 if ($type == "xml") {
2986 'remaining-hits' => '150',
2987 '@attributes' => ["type" => "integer"],
2988 'hourly-limit' => '150',
2989 '@attributes2' => ["type" => "integer"],
2990 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
2991 '@attributes3' => ["type" => "datetime"],
2992 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2993 '@attributes4' => ["type" => "integer"],
2997 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2998 'remaining_hits' => '150',
2999 'hourly_limit' => '150',
3000 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3004 return api_format_data('hash', $type, ['hash' => $hash]);
3007 /// @TODO move to top of file or somewhere better
3008 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3011 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3013 * @param string $type Return type (atom, rss, xml, json)
3015 * @return array|string
3017 function api_help_test($type)
3019 if ($type == 'xml') {
3025 return api_format_data('ok', $type, ["ok" => $ok]);
3028 /// @TODO move to top of file or somewhere better
3029 api_register_func('api/help/test', 'api_help_test', false);
3032 * Returns all lists the user subscribes to.
3034 * @param string $type Return type (atom, rss, xml, json)
3036 * @return array|string
3037 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3039 function api_lists_list($type)
3042 /// @TODO $ret is not filled here?
3043 return api_format_data('lists', $type, ["lists_list" => $ret]);
3046 /// @TODO move to top of file or somewhere better
3047 api_register_func('api/lists/list', 'api_lists_list', true);
3048 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3051 * Returns all groups the user owns.
3053 * @param string $type Return type (atom, rss, xml, json)
3055 * @return array|string
3056 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3058 function api_lists_ownerships($type)
3062 if (api_user() === false) {
3063 throw new ForbiddenException();
3067 $user_info = api_get_user($a);
3068 $uid = $user_info['uid'];
3070 $groups = dba::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3072 // loop through all groups
3074 foreach ($groups as $group) {
3075 if ($group['visible']) {
3081 'name' => $group['name'],
3082 'id' => intval($group['id']),
3083 'id_str' => (string) $group['id'],
3084 'user' => $user_info,
3088 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3091 /// @TODO move to top of file or somewhere better
3092 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3095 * Returns recent statuses from users in the specified group.
3097 * @param string $type Return type (atom, rss, xml, json)
3099 * @return array|string
3100 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3102 function api_lists_statuses($type)
3106 $user_info = api_get_user($a);
3107 if (api_user() === false || $user_info === false) {
3108 throw new ForbiddenException();
3111 unset($_REQUEST["user_id"]);
3112 unset($_GET["user_id"]);
3114 unset($_REQUEST["screen_name"]);
3115 unset($_GET["screen_name"]);
3117 if (empty($_REQUEST['list_id'])) {
3118 throw new BadRequestException('list_id not specified');
3122 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
3123 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
3127 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3128 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3129 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
3130 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
3132 $start = $page * $count;
3134 $condition = ["`uid` = ? AND `verb` = ? AND `id` > ? AND `group_member`.`gid` = ?",
3135 api_user(), ACTIVITY_POST, $since_id, $_REQUEST['list_id']];
3138 $condition[0] .= " AND `item`.`id` <= ?";
3139 $condition[] = $max_id;
3141 if ($exclude_replies > 0) {
3142 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3144 if ($conversation_id > 0) {
3145 $condition[0] .= " AND `item`.`parent` = ?";
3146 $condition[] = $conversation_id;
3149 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3150 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3152 $items = api_format_items(dba::inArray($statuses), $user_info, false, $type);
3154 $data = ['status' => $items];
3158 $data = api_rss_extra($a, $data, $user_info);
3162 return api_format_data("statuses", $type, $data);
3165 /// @TODO move to top of file or somewhere better
3166 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3169 * Considers friends and followers lists to be private and won't return
3170 * anything if any user_id parameter is passed.
3172 * @brief Returns either the friends of the follower list
3174 * @param string $qtype Either "friends" or "followers"
3175 * @return boolean|array
3176 * @throws ForbiddenException
3178 function api_statuses_f($qtype)
3182 if (api_user() === false) {
3183 throw new ForbiddenException();
3187 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3188 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3192 $start = ($page - 1) * $count;
3194 $user_info = api_get_user($a);
3196 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3197 /* this is to stop Hotot to load friends multiple times
3198 * I'm not sure if I'm missing return something or
3199 * is a bug in hotot. Workaround, meantime
3203 return array('$users' => $ret);*/
3208 if ($qtype == 'friends') {
3209 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3210 } elseif ($qtype == 'followers') {
3211 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3214 // friends and followers only for self
3215 if ($user_info['self'] == 0) {
3216 $sql_extra = " AND false ";
3219 if ($qtype == 'blocks') {
3220 $sql_filter = 'AND `blocked` AND NOT `pending`';
3221 } elseif ($qtype == 'incoming') {
3222 $sql_filter = 'AND `pending`';
3224 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3242 foreach ($r as $cid) {
3243 $user = api_get_user($a, $cid['nurl']);
3244 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3245 unset($user["uid"]);
3246 unset($user["self"]);
3253 return ['user' => $ret];
3258 * Returns the user's friends.
3260 * @brief Returns the list of friends of the provided user
3262 * @deprecated By Twitter API in favor of friends/list
3264 * @param string $type Either "json" or "xml"
3265 * @return boolean|string|array
3267 function api_statuses_friends($type)
3269 $data = api_statuses_f("friends");
3270 if ($data === false) {
3273 return api_format_data("users", $type, $data);
3277 * Returns the user's followers.
3279 * @brief Returns the list of followers of the provided user
3281 * @deprecated By Twitter API in favor of friends/list
3283 * @param string $type Either "json" or "xml"
3284 * @return boolean|string|array
3286 function api_statuses_followers($type)
3288 $data = api_statuses_f("followers");
3289 if ($data === false) {
3292 return api_format_data("users", $type, $data);
3295 /// @TODO move to top of file or somewhere better
3296 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3297 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3300 * Returns the list of blocked users
3302 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3304 * @param string $type Either "json" or "xml"
3306 * @return boolean|string|array
3308 function api_blocks_list($type)
3310 $data = api_statuses_f('blocks');
3311 if ($data === false) {
3314 return api_format_data("users", $type, $data);
3317 /// @TODO move to top of file or somewhere better
3318 api_register_func('api/blocks/list', 'api_blocks_list', true);
3321 * Returns the list of pending users IDs
3323 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3325 * @param string $type Either "json" or "xml"
3327 * @return boolean|string|array
3329 function api_friendships_incoming($type)
3331 $data = api_statuses_f('incoming');
3332 if ($data === false) {
3337 foreach ($data['user'] as $user) {
3338 $ids[] = $user['id'];
3341 return api_format_data("ids", $type, ['id' => $ids]);
3344 /// @TODO move to top of file or somewhere better
3345 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3348 * Returns the instance's configuration information.
3350 * @param string $type Return type (atom, rss, xml, json)
3352 * @return array|string
3354 function api_statusnet_config($type)
3358 $name = $a->config['sitename'];
3359 $server = $a->get_hostname();
3360 $logo = System::baseUrl() . '/images/friendica-64.png';
3361 $email = $a->config['admin_email'];
3362 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3363 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3364 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3365 if ($a->config['api_import_size']) {
3366 $textlimit = (string) $a->config['api_import_size'];
3368 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3369 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3372 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3373 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3374 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3375 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3376 'shorturllength' => '30',
3378 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3379 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3380 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3381 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3386 return api_format_data('config', $type, ['config' => $config]);
3389 /// @TODO move to top of file or somewhere better
3390 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3391 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3395 * @param string $type Return type (atom, rss, xml, json)
3397 * @return array|string
3399 function api_statusnet_version($type)
3402 $fake_statusnet_version = "0.9.7";
3404 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3407 /// @TODO move to top of file or somewhere better
3408 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3409 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3413 * @param string $type Return type (atom, rss, xml, json)
3415 * @todo use api_format_data() to return data
3417 function api_ff_ids($type)
3420 throw new ForbiddenException();
3427 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3430 "SELECT `pcontact`.`id` FROM `contact`
3431 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3432 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3435 if (!DBM::is_result($r)) {
3440 foreach ($r as $rr) {
3441 if ($stringify_ids) {
3444 $ids[] = intval($rr['id']);
3448 return api_format_data("ids", $type, ['id' => $ids]);
3452 * Returns the ID of every user the user is following.
3454 * @param string $type Return type (atom, rss, xml, json)
3456 * @return array|string
3457 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3459 function api_friends_ids($type)
3461 return api_ff_ids($type);
3465 * Returns the ID of every user following the user.
3467 * @param string $type Return type (atom, rss, xml, json)
3469 * @return array|string
3470 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3472 function api_followers_ids($type)
3474 return api_ff_ids($type);
3477 /// @TODO move to top of file or somewhere better
3478 api_register_func('api/friends/ids', 'api_friends_ids', true);
3479 api_register_func('api/followers/ids', 'api_followers_ids', true);
3482 * Sends a new direct message.
3484 * @param string $type Return type (atom, rss, xml, json)
3486 * @return array|string
3487 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3489 function api_direct_messages_new($type)
3494 if (api_user() === false) {
3495 throw new ForbiddenException();
3498 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3502 $sender = api_get_user($a);
3504 if ($_POST['screen_name']) {
3506 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3508 dbesc($_POST['screen_name'])
3511 // Selecting the id by priority, friendica first
3512 api_best_nickname($r);
3514 $recipient = api_get_user($a, $r[0]['nurl']);
3516 $recipient = api_get_user($a, $_POST['user_id']);
3521 if (x($_REQUEST, 'replyto')) {
3523 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3525 intval($_REQUEST['replyto'])
3527 $replyto = $r[0]['parent-uri'];
3528 $sub = $r[0]['title'];
3530 if (x($_REQUEST, 'title')) {
3531 $sub = $_REQUEST['title'];
3533 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3537 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3540 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3541 $ret = api_format_messages($r[0], $recipient, $sender);
3543 $ret = ["error"=>$id];
3546 $data = ['direct_message'=>$ret];
3551 $data = api_rss_extra($a, $data, $sender);
3554 return api_format_data("direct-messages", $type, $data);
3557 /// @TODO move to top of file or somewhere better
3558 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3561 * Destroys a direct message.
3563 * @brief delete a direct_message from mail table through api
3565 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3566 * @return string|array
3567 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3569 function api_direct_messages_destroy($type)
3573 if (api_user() === false) {
3574 throw new ForbiddenException();
3578 $user_info = api_get_user($a);
3580 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3582 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3583 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3584 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3586 $uid = $user_info['uid'];
3587 // error if no id or parenturi specified (for clients posting parent-uri as well)
3588 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3589 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3590 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3593 // BadRequestException if no id specified (for clients using Twitter API)
3595 throw new BadRequestException('Message id not specified');
3598 // add parent-uri to sql command if specified by calling app
3599 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3601 // get data of the specified message id
3603 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3608 // error message if specified id is not in database
3609 if (!DBM::is_result($r)) {
3610 if ($verbose == "true") {
3611 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3612 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3614 /// @todo BadRequestException ok for Twitter API clients?
3615 throw new BadRequestException('message id not in database');
3620 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3625 if ($verbose == "true") {
3628 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3629 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3631 $answer = ['result' => 'error', 'message' => 'unknown error'];
3632 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3635 /// @todo return JSON data like Twitter API not yet implemented
3638 /// @TODO move to top of file or somewhere better
3639 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3643 * @param string $type Return type (atom, rss, xml, json)
3644 * @param string $box
3645 * @param string $verbose
3647 * @return array|string
3649 function api_direct_messages_box($type, $box, $verbose)
3652 $user_info = api_get_user($a);
3654 if (api_user() === false || $user_info === false) {
3655 throw new ForbiddenException();
3659 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3660 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3665 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3666 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3668 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3669 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3672 unset($_REQUEST["user_id"]);
3673 unset($_GET["user_id"]);
3675 unset($_REQUEST["screen_name"]);
3676 unset($_GET["screen_name"]);
3678 $profile_url = $user_info["url"];
3681 $start = $page * $count;
3686 if ($box=="sentbox") {
3687 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3688 } elseif ($box == "conversation") {
3689 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3690 } elseif ($box == "all") {
3691 $sql_extra = "true";
3692 } elseif ($box == "inbox") {
3693 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3697 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3700 if ($user_id != "") {
3701 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3702 } elseif ($screen_name !="") {
3703 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3707 "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",
3713 if ($verbose == "true" && !DBM::is_result($r)) {
3714 $answer = ['result' => 'error', 'message' => 'no mails available'];
3715 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3719 foreach ($r as $item) {
3720 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3721 $recipient = $user_info;
3722 $sender = api_get_user($a, normalise_link($item['contact-url']));
3723 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3724 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3725 $sender = $user_info;
3728 if (isset($recipient) && isset($sender)) {
3729 $ret[] = api_format_messages($item, $recipient, $sender);
3734 $data = ['direct_message' => $ret];
3738 $data = api_rss_extra($a, $data, $user_info);
3741 return api_format_data("direct-messages", $type, $data);
3745 * Returns the most recent direct messages sent by the user.
3747 * @param string $type Return type (atom, rss, xml, json)
3749 * @return array|string
3750 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3752 function api_direct_messages_sentbox($type)
3754 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3755 return api_direct_messages_box($type, "sentbox", $verbose);
3759 * Returns the most recent direct messages sent to the user.
3761 * @param string $type Return type (atom, rss, xml, json)
3763 * @return array|string
3764 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3766 function api_direct_messages_inbox($type)
3768 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3769 return api_direct_messages_box($type, "inbox", $verbose);
3774 * @param string $type Return type (atom, rss, xml, json)
3776 * @return array|string
3778 function api_direct_messages_all($type)
3780 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3781 return api_direct_messages_box($type, "all", $verbose);
3786 * @param string $type Return type (atom, rss, xml, json)
3788 * @return array|string
3790 function api_direct_messages_conversation($type)
3792 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3793 return api_direct_messages_box($type, "conversation", $verbose);
3796 /// @TODO move to top of file or somewhere better
3797 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3798 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3799 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3800 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3803 * Returns an OAuth Request Token.
3805 * @see https://oauth.net/core/1.0/#auth_step1
3807 function api_oauth_request_token()
3809 $oauth1 = new FKOAuth1();
3811 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3812 } catch (Exception $e) {
3813 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3821 * Returns an OAuth Access Token.
3823 * @return array|string
3824 * @see https://oauth.net/core/1.0/#auth_step3
3826 function api_oauth_access_token()
3828 $oauth1 = new FKOAuth1();
3830 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3831 } catch (Exception $e) {
3832 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3839 /// @TODO move to top of file or somewhere better
3840 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3841 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3845 * @brief delete a complete photoalbum with all containing photos from database through api
3847 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3848 * @return string|array
3850 function api_fr_photoalbum_delete($type)
3852 if (api_user() === false) {
3853 throw new ForbiddenException();
3856 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3858 // we do not allow calls without album string
3860 throw new BadRequestException("no albumname specified");
3862 // check if album is existing
3864 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3868 if (!DBM::is_result($r)) {
3869 throw new BadRequestException("album not available");
3872 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3873 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3874 foreach ($r as $rr) {
3876 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3877 intval(local_user()),
3878 dbesc($rr['resource-id'])
3881 if (!DBM::is_result($photo_item)) {
3882 throw new InternalServerErrorException("problem with deleting items occured");
3884 Item::deleteForUser(['id' => $photo_item[0]['id']], api_user());
3887 // now let's delete all photos from the album
3888 $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
3890 // return success of deletion or error message
3892 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
3893 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
3895 throw new InternalServerErrorException("unknown error - deleting from database failed");
3900 * @brief update the name of the album for all photos of an album
3902 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3903 * @return string|array
3905 function api_fr_photoalbum_update($type)
3907 if (api_user() === false) {
3908 throw new ForbiddenException();
3911 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3912 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3914 // we do not allow calls without album string
3916 throw new BadRequestException("no albumname specified");
3918 if ($album_new == "") {
3919 throw new BadRequestException("no new albumname specified");
3921 // check if album is existing
3922 if (!dba::exists('photo', ['uid' => api_user(), 'album' => $album])) {
3923 throw new BadRequestException("album not available");
3925 // now let's update all photos to the albumname
3926 $result = dba::update('photo', ['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
3928 // return success of updating or error message
3930 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
3931 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
3933 throw new InternalServerErrorException("unknown error - updating in database failed");
3939 * @brief list all photos of the authenticated user
3941 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3942 * @return string|array
3944 function api_fr_photos_list($type)
3946 if (api_user() === false) {
3947 throw new ForbiddenException();
3950 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3951 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3952 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3953 intval(local_user())
3956 'image/jpeg' => 'jpg',
3957 'image/png' => 'png',
3958 'image/gif' => 'gif'
3960 $data = ['photo'=>[]];
3961 if (DBM::is_result($r)) {
3962 foreach ($r as $rr) {
3964 $photo['id'] = $rr['resource-id'];
3965 $photo['album'] = $rr['album'];
3966 $photo['filename'] = $rr['filename'];
3967 $photo['type'] = $rr['type'];
3968 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3969 $photo['created'] = $rr['created'];
3970 $photo['edited'] = $rr['edited'];
3971 $photo['desc'] = $rr['desc'];
3973 if ($type == "xml") {
3974 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3976 $photo['thumb'] = $thumb;
3977 $data['photo'][] = $photo;
3981 return api_format_data("photos", $type, $data);
3985 * @brief upload a new photo or change an existing photo
3987 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3988 * @return string|array
3990 function api_fr_photo_create_update($type)
3992 if (api_user() === false) {
3993 throw new ForbiddenException();
3996 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3997 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3998 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3999 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4000 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4001 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4002 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4003 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4004 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4006 // do several checks on input parameters
4007 // we do not allow calls without album string
4008 if ($album == null) {
4009 throw new BadRequestException("no albumname specified");
4011 // if photo_id == null --> we are uploading a new photo
4012 if ($photo_id == null) {
4015 // error if no media posted in create-mode
4016 if (!x($_FILES, 'media')) {
4018 throw new BadRequestException("no media data submitted");
4021 // album_new will be ignored in create-mode
4026 // check if photo is existing in database
4028 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4033 if (!DBM::is_result($r)) {
4034 throw new BadRequestException("photo not available");
4038 // checks on acl strings provided by clients
4039 $acl_input_error = false;
4040 $acl_input_error |= check_acl_input($allow_cid);
4041 $acl_input_error |= check_acl_input($deny_cid);
4042 $acl_input_error |= check_acl_input($allow_gid);
4043 $acl_input_error |= check_acl_input($deny_gid);
4044 if ($acl_input_error) {
4045 throw new BadRequestException("acl data invalid");
4047 // now let's upload the new media in create-mode
4048 if ($mode == "create") {
4049 $media = $_FILES['media'];
4050 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4052 // return success of updating or error message
4053 if (!is_null($data)) {
4054 return api_format_data("photo_create", $type, $data);
4056 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4060 // now let's do the changes in update-mode
4061 if ($mode == "update") {
4064 if (!is_null($desc)) {
4065 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4068 if (!is_null($album_new)) {
4069 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4072 if (!is_null($allow_cid)) {
4073 $allow_cid = trim($allow_cid);
4074 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4077 if (!is_null($deny_cid)) {
4078 $deny_cid = trim($deny_cid);
4079 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4082 if (!is_null($allow_gid)) {
4083 $allow_gid = trim($allow_gid);
4084 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4087 if (!is_null($deny_gid)) {
4088 $deny_gid = trim($deny_gid);
4089 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4093 if ($sql_extra != "") {
4094 $nothingtodo = false;
4096 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4098 DateTimeFormat::utcNow(), // update edited timestamp
4104 $nothingtodo = true;
4107 if (x($_FILES, 'media')) {
4108 $nothingtodo = false;
4109 $media = $_FILES['media'];
4110 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4111 if (!is_null($data)) {
4112 return api_format_data("photo_update", $type, $data);
4116 // return success of updating or error message
4118 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4119 return api_format_data("photo_update", $type, ['$result' => $answer]);
4122 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4123 return api_format_data("photo_update", $type, ['$result' => $answer]);
4125 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4128 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4132 * @brief delete a single photo from the database through api
4134 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4135 * @return string|array
4137 function api_fr_photo_delete($type)
4139 if (api_user() === false) {
4140 throw new ForbiddenException();
4143 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4145 // do several checks on input parameters
4146 // we do not allow calls without photo id
4147 if ($photo_id == null) {
4148 throw new BadRequestException("no photo_id specified");
4150 // check if photo is existing in database
4152 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4156 if (!DBM::is_result($r)) {
4157 throw new BadRequestException("photo not available");
4159 // now we can perform on the deletion of the photo
4160 $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4162 // return success of deletion or error message
4164 // retrieve the id of the parent element (the photo element)
4166 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4167 intval(local_user()),
4171 if (!DBM::is_result($photo_item)) {
4172 throw new InternalServerErrorException("problem with deleting items occured");
4174 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4175 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4176 Item::deleteForUser(['id' => $photo_item[0]['id']], api_user());
4178 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4179 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4181 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4187 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4189 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4190 * @return string|array
4192 function api_fr_photo_detail($type)
4194 if (api_user() === false) {
4195 throw new ForbiddenException();
4197 if (!x($_REQUEST, 'photo_id')) {
4198 throw new BadRequestException("No photo id.");
4201 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4202 $photo_id = $_REQUEST['photo_id'];
4204 // prepare json/xml output with data from database for the requested photo
4205 $data = prepare_photo_data($type, $scale, $photo_id);
4207 return api_format_data("photo_detail", $type, $data);
4212 * Updates the user’s profile image.
4214 * @brief updates the profile image for the user (either a specified profile or the default profile)
4216 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4218 * @return string|array
4219 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4221 function api_account_update_profile_image($type)
4223 if (api_user() === false) {
4224 throw new ForbiddenException();
4227 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4229 // error if image data is missing
4230 if (!x($_FILES, 'image')) {
4231 throw new BadRequestException("no media data submitted");
4234 // check if specified profile id is valid
4235 if ($profile_id != 0) {
4236 $profile = dba::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4237 // error message if specified profile id is not in database
4238 if (!DBM::is_result($profile)) {
4239 throw new BadRequestException("profile_id not available");
4241 $is_default_profile = $profile['is-default'];
4243 $is_default_profile = 1;
4246 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4248 if (x($_FILES, 'image')) {
4249 $media = $_FILES['image'];
4250 } elseif (x($_FILES, 'media')) {
4251 $media = $_FILES['media'];
4253 // save new profile image
4254 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4257 if (is_array($media['type'])) {
4258 $filetype = $media['type'][0];
4260 $filetype = $media['type'];
4262 if ($filetype == "image/jpeg") {
4264 } elseif ($filetype == "image/png") {
4267 throw new InternalServerErrorException('Unsupported filetype');
4270 // change specified profile or all profiles to the new resource-id
4271 if ($is_default_profile) {
4272 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4273 dba::update('photo', ['profile' => false], $condition);
4275 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype,
4276 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype];
4277 dba::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4280 Contact::updateSelfFromUserID(api_user(), true);
4282 // Update global directory in background
4283 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4284 if ($url && strlen(Config::get('system', 'directory'))) {
4285 Worker::add(PRIORITY_LOW, "Directory", $url);
4288 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4290 // output for client
4292 return api_account_verify_credentials($type);
4294 // SaveMediaToDatabase failed for some reason
4295 throw new InternalServerErrorException("image upload failed");
4299 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4300 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4301 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4302 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4303 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4304 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4305 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4306 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4307 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4310 * Update user profile
4312 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4314 * @return array|string
4316 function api_account_update_profile($type)
4318 $local_user = api_user();
4319 $api_user = api_get_user(get_app());
4321 if (!empty($_POST['name'])) {
4322 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4323 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4324 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4325 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4328 if (isset($_POST['description'])) {
4329 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4330 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4331 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4334 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4335 // Update global directory in background
4336 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4337 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4340 return api_account_verify_credentials($type);
4343 /// @TODO move to top of file or somewhere better
4344 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4348 * @param string $acl_string
4350 function check_acl_input($acl_string)
4352 if ($acl_string == null || $acl_string == " ") {
4355 $contact_not_found = false;
4357 // split <x><y><z> into array of cid's
4358 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4360 // check for each cid if it is available on server
4361 $cid_array = $array[0];
4362 foreach ($cid_array as $cid) {
4363 $cid = str_replace("<", "", $cid);
4364 $cid = str_replace(">", "", $cid);
4366 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4370 $contact_not_found |= !DBM::is_result($contact);
4372 return $contact_not_found;
4377 * @param string $mediatype
4378 * @param array $media
4379 * @param string $type
4380 * @param string $album
4381 * @param string $allow_cid
4382 * @param string $deny_cid
4383 * @param string $allow_gid
4384 * @param string $deny_gid
4385 * @param string $desc
4386 * @param integer $profile
4387 * @param boolean $visibility
4388 * @param string $photo_id
4390 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)
4398 if (is_array($media)) {
4399 if (is_array($media['tmp_name'])) {
4400 $src = $media['tmp_name'][0];
4402 $src = $media['tmp_name'];
4404 if (is_array($media['name'])) {
4405 $filename = basename($media['name'][0]);
4407 $filename = basename($media['name']);
4409 if (is_array($media['size'])) {
4410 $filesize = intval($media['size'][0]);
4412 $filesize = intval($media['size']);
4414 if (is_array($media['type'])) {
4415 $filetype = $media['type'][0];
4417 $filetype = $media['type'];
4421 if ($filetype == "") {
4422 $filetype=Image::guessType($filename);
4424 $imagedata = getimagesize($src);
4426 $filetype = $imagedata['mime'];
4429 "File upload src: " . $src . " - filename: " . $filename .
4430 " - size: " . $filesize . " - type: " . $filetype,
4434 // check if there was a php upload error
4435 if ($filesize == 0 && $media['error'] == 1) {
4436 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4438 // check against max upload size within Friendica instance
4439 $maximagesize = Config::get('system', 'maximagesize');
4440 if ($maximagesize && ($filesize > $maximagesize)) {
4441 $formattedBytes = formatBytes($maximagesize);
4442 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4445 // create Photo instance with the data of the image
4446 $imagedata = @file_get_contents($src);
4447 $Image = new Image($imagedata, $filetype);
4448 if (! $Image->isValid()) {
4449 throw new InternalServerErrorException("unable to process image data");
4452 // check orientation of image
4453 $Image->orient($src);
4456 // check max length of images on server
4457 $max_length = Config::get('system', 'max_image_length');
4458 if (! $max_length) {
4459 $max_length = MAX_IMAGE_LENGTH;
4461 if ($max_length > 0) {
4462 $Image->scaleDown($max_length);
4463 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4465 $width = $Image->getWidth();
4466 $height = $Image->getHeight();
4468 // create a new resource-id if not already provided
4469 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4471 if ($mediatype == "photo") {
4472 // upload normal image (scales 0, 1, 2)
4473 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4475 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4477 logger("photo upload: image upload with scale 0 (original size) failed");
4479 if ($width > 640 || $height > 640) {
4480 $Image->scaleDown(640);
4481 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4483 logger("photo upload: image upload with scale 1 (640x640) failed");
4487 if ($width > 320 || $height > 320) {
4488 $Image->scaleDown(320);
4489 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4491 logger("photo upload: image upload with scale 2 (320x320) failed");
4494 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4495 } elseif ($mediatype == "profileimage") {
4496 // upload profile image (scales 4, 5, 6)
4497 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4499 if ($width > 175 || $height > 175) {
4500 $Image->scaleDown(175);
4501 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4503 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4507 if ($width > 80 || $height > 80) {
4508 $Image->scaleDown(80);
4509 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4511 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4515 if ($width > 48 || $height > 48) {
4516 $Image->scaleDown(48);
4517 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4519 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4522 $Image->__destruct();
4523 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4526 if (isset($r) && $r) {
4527 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4528 if ($photo_id == null && $mediatype == "photo") {
4529 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4531 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4532 return prepare_photo_data($type, false, $hash);
4534 throw new InternalServerErrorException("image upload failed");
4540 * @param string $hash
4541 * @param string $allow_cid
4542 * @param string $deny_cid
4543 * @param string $allow_gid
4544 * @param string $deny_gid
4545 * @param string $filetype
4546 * @param boolean $visibility
4548 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4550 // get data about the api authenticated user
4551 $uri = Item::newURI(intval(api_user()));
4552 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4555 $arr['guid'] = get_guid(32);
4556 $arr['uid'] = intval(api_user());
4558 $arr['parent-uri'] = $uri;
4559 $arr['type'] = 'photo';
4561 $arr['resource-id'] = $hash;
4562 $arr['contact-id'] = $owner_record[0]['id'];
4563 $arr['owner-name'] = $owner_record[0]['name'];
4564 $arr['owner-link'] = $owner_record[0]['url'];
4565 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4566 $arr['author-name'] = $owner_record[0]['name'];
4567 $arr['author-link'] = $owner_record[0]['url'];
4568 $arr['author-avatar'] = $owner_record[0]['thumb'];
4570 $arr['allow_cid'] = $allow_cid;
4571 $arr['allow_gid'] = $allow_gid;
4572 $arr['deny_cid'] = $deny_cid;
4573 $arr['deny_gid'] = $deny_gid;
4574 $arr['visible'] = $visibility;
4578 'image/jpeg' => 'jpg',
4579 'image/png' => 'png',
4580 'image/gif' => 'gif'
4583 // adds link to the thumbnail scale photo
4584 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4585 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4588 // do the magic for storing the item in the database and trigger the federation to other contacts
4594 * @param string $type
4596 * @param string $photo_id
4600 function prepare_photo_data($type, $scale, $photo_id)
4603 $user_info = api_get_user($a);
4605 if ($user_info === false) {
4606 throw new ForbiddenException();
4609 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4610 $data_sql = ($scale === false ? "" : "data, ");
4612 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4613 // clients needs to convert this in their way for further processing
4615 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4616 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4617 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4618 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4620 intval(local_user()),
4626 'image/jpeg' => 'jpg',
4627 'image/png' => 'png',
4628 'image/gif' => 'gif'
4631 // prepare output data for photo
4632 if (DBM::is_result($r)) {
4633 $data = ['photo' => $r[0]];
4634 $data['photo']['id'] = $data['photo']['resource-id'];
4635 if ($scale !== false) {
4636 $data['photo']['data'] = base64_encode($data['photo']['data']);
4638 unset($data['photo']['datasize']); //needed only with scale param
4640 if ($type == "xml") {
4641 $data['photo']['links'] = [];
4642 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4643 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4645 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4648 $data['photo']['link'] = [];
4649 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4651 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4652 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4656 unset($data['photo']['resource-id']);
4657 unset($data['photo']['minscale']);
4658 unset($data['photo']['maxscale']);
4660 throw new NotFoundException();
4663 // retrieve item element for getting activities (like, dislike etc.) related to photo
4665 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4666 intval(local_user()),
4669 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4671 // retrieve comments on photo
4672 $condition = ["`parent` = ? AND `uid` = ? AND (`verb` = ? OR `type`='photo')",
4673 $item[0]['parent'], api_user(), ACTIVITY_POST];
4675 $statuses = Item::selectForUser(api_user(), [], $condition);
4677 // prepare output of comments
4678 $commentData = api_format_items(dba::inArray($statuses), $user_info, false, $type);
4680 if ($type == "xml") {
4682 foreach ($commentData as $comment) {
4683 $comments[$k++ . ":comment"] = $comment;
4686 foreach ($commentData as $comment) {
4687 $comments[] = $comment;
4690 $data['photo']['friendica_comments'] = $comments;
4692 // include info if rights on photo and rights on item are mismatching
4693 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4694 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4695 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4696 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4697 $data['photo']['rights_mismatch'] = $rights_mismatch;
4704 * Similar as /mod/redir.php
4705 * redirect to 'url' after dfrn auth
4707 * Why this when there is mod/redir.php already?
4708 * This use api_user() and api_login()
4711 * c_url: url of remote contact to auth to
4712 * url: string, url to redirect after auth
4714 function api_friendica_remoteauth()
4716 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4717 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4719 if ($url === '' || $c_url === '') {
4720 throw new BadRequestException("Wrong parameters.");
4723 $c_url = normalise_link($c_url);
4727 $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4729 if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
4730 throw new BadRequestException("Unknown contact");
4733 $cid = $contact['id'];
4735 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4737 if ($contact['duplex'] && $contact['issued-id']) {
4738 $orig_id = $contact['issued-id'];
4739 $dfrn_id = '1:' . $orig_id;
4741 if ($contact['duplex'] && $contact['dfrn-id']) {
4742 $orig_id = $contact['dfrn-id'];
4743 $dfrn_id = '0:' . $orig_id;
4746 $sec = random_string();
4748 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4749 'sec' => $sec, 'expire' => time() + 45];
4750 dba::insert('profile_check', $fields);
4752 logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
4753 $dest = ($url ? '&destination_url=' . $url : '');
4755 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4756 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4757 . '&type=profile&sec=' . $sec . $dest
4760 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4763 * @brief Return the item shared, if the item contains only the [share] tag
4765 * @param array $item Sharer item
4766 * @return array|false Shared item or false if not a reshare
4768 function api_share_as_retweet(&$item)
4770 $body = trim($item["body"]);
4772 if (Diaspora::isReshare($body, false)===false) {
4776 /// @TODO "$1" should maybe mean '$1' ?
4777 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4779 * Skip if there is no shared message in there
4780 * we already checked this in diaspora::isReshare()
4781 * but better one more than one less...
4783 if ($body == $attributes) {
4788 // build the fake reshared item
4789 $reshared_item = $item;
4792 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4793 if ($matches[1] != "") {
4794 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4797 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4798 if ($matches[1] != "") {
4799 $author = $matches[1];
4803 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4804 if ($matches[1] != "") {
4805 $profile = $matches[1];
4808 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4809 if ($matches[1] != "") {
4810 $profile = $matches[1];
4814 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4815 if ($matches[1] != "") {
4816 $avatar = $matches[1];
4819 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4820 if ($matches[1] != "") {
4821 $avatar = $matches[1];
4825 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4826 if ($matches[1] != "") {
4827 $link = $matches[1];
4830 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4831 if ($matches[1] != "") {
4832 $link = $matches[1];
4836 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4837 if ($matches[1] != "") {
4838 $posted = $matches[1];
4841 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4842 if ($matches[1] != "") {
4843 $posted = $matches[1];
4846 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4848 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4852 $reshared_item["body"] = $shared_body;
4853 $reshared_item["author-name"] = $author;
4854 $reshared_item["author-link"] = $profile;
4855 $reshared_item["author-avatar"] = $avatar;
4856 $reshared_item["plink"] = $link;
4857 $reshared_item["created"] = $posted;
4858 $reshared_item["edited"] = $posted;
4860 return $reshared_item;
4865 * @param string $profile
4867 * @return string|false
4868 * @todo remove trailing junk from profile url
4869 * @todo pump.io check has to check the website
4871 function api_get_nick($profile)
4876 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4877 dbesc(normalise_link($profile))
4880 if (DBM::is_result($r)) {
4881 $nick = $r[0]["nick"];
4886 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4887 dbesc(normalise_link($profile))
4890 if (DBM::is_result($r)) {
4891 $nick = $r[0]["nick"];
4896 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4897 if ($friendica != $profile) {
4903 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4904 if ($diaspora != $profile) {
4910 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4911 if ($twitter != $profile) {
4918 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4919 if ($StatusnetHost != $profile) {
4920 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4921 if ($StatusnetUser != $profile) {
4922 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4923 $user = json_decode($UserData);
4925 $nick = $user->screen_name;
4931 // To-Do: look at the page if its really a pumpio site
4932 //if (!$nick == "") {
4933 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4934 // if ($pumpio != $profile)
4936 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4949 * @param array $item
4953 function api_in_reply_to($item)
4957 $in_reply_to['status_id'] = null;
4958 $in_reply_to['user_id'] = null;
4959 $in_reply_to['status_id_str'] = null;
4960 $in_reply_to['user_id_str'] = null;
4961 $in_reply_to['screen_name'] = null;
4963 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4965 "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4966 intval($item['uid']),
4967 dbesc($item['thr-parent'])
4970 if (DBM::is_result($r)) {
4971 $in_reply_to['status_id'] = intval($r[0]['id']);
4973 $in_reply_to['status_id'] = intval($item['parent']);
4976 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4979 "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM `item`
4980 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4981 WHERE `item`.`id` = %d LIMIT 1",
4982 intval($in_reply_to['status_id'])
4985 if (DBM::is_result($r)) {
4986 if ($r[0]['nick'] == "") {
4987 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4990 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4991 $in_reply_to['user_id'] = intval($r[0]['id']);
4992 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4995 // There seems to be situation, where both fields are identical:
4996 // https://github.com/friendica/friendica/issues/1010
4997 // This is a bugfix for that.
4998 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4999 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
5000 $in_reply_to['status_id'] = null;
5001 $in_reply_to['user_id'] = null;
5002 $in_reply_to['status_id_str'] = null;
5003 $in_reply_to['user_id_str'] = null;
5004 $in_reply_to['screen_name'] = null;
5008 return $in_reply_to;
5013 * @param string $text
5017 function api_clean_plain_items($text)
5019 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5021 $text = BBCode::cleanPictureLinks($text);
5022 $URLSearchString = "^\[\]";
5024 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5026 if ($include_entities == "true") {
5027 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5030 // Simplify "attachment" element
5031 $text = api_clean_attachments($text);
5037 * @brief Removes most sharing information for API text export
5039 * @param string $body The original body
5041 * @return string Cleaned body
5043 function api_clean_attachments($body)
5045 $data = BBCode::getAttachmentData($body);
5052 if (isset($data["text"])) {
5053 $body = $data["text"];
5055 if (($body == "") && isset($data["title"])) {
5056 $body = $data["title"];
5058 if (isset($data["url"])) {
5059 $body .= "\n".$data["url"];
5061 $body .= $data["after"];
5068 * @param array $contacts
5072 function api_best_nickname(&$contacts)
5076 if (count($contacts) == 0) {
5080 foreach ($contacts as $contact) {
5081 if ($contact["network"] == "") {
5082 $contact["network"] = "dfrn";
5083 $best_contact = [$contact];
5087 if (sizeof($best_contact) == 0) {
5088 foreach ($contacts as $contact) {
5089 if ($contact["network"] == "dfrn") {
5090 $best_contact = [$contact];
5095 if (sizeof($best_contact) == 0) {
5096 foreach ($contacts as $contact) {
5097 if ($contact["network"] == "dspr") {
5098 $best_contact = [$contact];
5103 if (sizeof($best_contact) == 0) {
5104 foreach ($contacts as $contact) {
5105 if ($contact["network"] == "stat") {
5106 $best_contact = [$contact];
5111 if (sizeof($best_contact) == 0) {
5112 foreach ($contacts as $contact) {
5113 if ($contact["network"] == "pump") {
5114 $best_contact = [$contact];
5119 if (sizeof($best_contact) == 0) {
5120 foreach ($contacts as $contact) {
5121 if ($contact["network"] == "twit") {
5122 $best_contact = [$contact];
5127 if (sizeof($best_contact) == 1) {
5128 $contacts = $best_contact;
5130 $contacts = [$contacts[0]];
5135 * Return all or a specified group of the user with the containing contacts.
5137 * @param string $type Return type (atom, rss, xml, json)
5139 * @return array|string
5141 function api_friendica_group_show($type)
5145 if (api_user() === false) {
5146 throw new ForbiddenException();
5150 $user_info = api_get_user($a);
5151 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5152 $uid = $user_info['uid'];
5154 // get data of the specified group id or all groups if not specified
5157 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5161 // error message if specified gid is not in database
5162 if (!DBM::is_result($r)) {
5163 throw new BadRequestException("gid not available");
5167 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5172 // loop through all groups and retrieve all members for adding data in the user array
5174 foreach ($r as $rr) {
5175 $members = Contact::getByGroupId($rr['id']);
5178 if ($type == "xml") {
5179 $user_element = "users";
5181 foreach ($members as $member) {
5182 $user = api_get_user($a, $member['nurl']);
5183 $users[$k++.":user"] = $user;
5186 $user_element = "user";
5187 foreach ($members as $member) {
5188 $user = api_get_user($a, $member['nurl']);
5192 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5194 return api_format_data("groups", $type, ['group' => $grps]);
5196 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5200 * Delete the specified group of the user.
5202 * @param string $type Return type (atom, rss, xml, json)
5204 * @return array|string
5206 function api_friendica_group_delete($type)
5210 if (api_user() === false) {
5211 throw new ForbiddenException();
5215 $user_info = api_get_user($a);
5216 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5217 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5218 $uid = $user_info['uid'];
5220 // error if no gid specified
5221 if ($gid == 0 || $name == "") {
5222 throw new BadRequestException('gid or name not specified');
5225 // get data of the specified group id
5227 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5231 // error message if specified gid is not in database
5232 if (!DBM::is_result($r)) {
5233 throw new BadRequestException('gid not available');
5236 // get data of the specified group id and group name
5238 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5243 // error message if specified gid is not in database
5244 if (!DBM::is_result($rname)) {
5245 throw new BadRequestException('wrong group name');
5249 $ret = Group::removeByName($uid, $name);
5252 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5253 return api_format_data("group_delete", $type, ['result' => $success]);
5255 throw new BadRequestException('other API error');
5258 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5263 * @param string $type Return type (atom, rss, xml, json)
5265 * @return array|string
5266 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5268 function api_lists_destroy($type)
5272 if (api_user() === false) {
5273 throw new ForbiddenException();
5277 $user_info = api_get_user($a);
5278 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5279 $uid = $user_info['uid'];
5281 // error if no gid specified
5283 throw new BadRequestException('gid not specified');
5286 // get data of the specified group id
5287 $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5288 // error message if specified gid is not in database
5290 throw new BadRequestException('gid not available');
5293 if (Group::remove($gid)) {
5295 'name' => $group['name'],
5296 'id' => intval($gid),
5297 'id_str' => (string) $gid,
5298 'user' => $user_info
5301 return api_format_data("lists", $type, ['lists' => $list]);
5304 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5307 * Add a new group to the database.
5309 * @param string $name Group name
5310 * @param int $uid User ID
5311 * @param array $users List of users to add to the group
5315 function group_create($name, $uid, $users = [])
5317 // error if no name specified
5319 throw new BadRequestException('group name not specified');
5322 // get data of the specified group name
5324 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5328 // error message if specified group name already exists
5329 if (DBM::is_result($rname)) {
5330 throw new BadRequestException('group name already exists');
5333 // check if specified group name is a deleted group
5335 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5339 // error message if specified group name already exists
5340 if (DBM::is_result($rname)) {
5341 $reactivate_group = true;
5345 $ret = Group::create($uid, $name);
5347 $gid = Group::getIdByName($uid, $name);
5349 throw new BadRequestException('other API error');
5353 $erroraddinguser = false;
5355 foreach ($users as $user) {
5356 $cid = $user['cid'];
5357 // check if user really exists as contact
5359 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5363 if (count($contact)) {
5364 Group::addMember($gid, $cid);
5366 $erroraddinguser = true;
5367 $errorusers[] = $cid;
5371 // return success message incl. missing users in array
5372 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5374 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5378 * Create the specified group with the posted array of contacts.
5380 * @param string $type Return type (atom, rss, xml, json)
5382 * @return array|string
5384 function api_friendica_group_create($type)
5388 if (api_user() === false) {
5389 throw new ForbiddenException();
5393 $user_info = api_get_user($a);
5394 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5395 $uid = $user_info['uid'];
5396 $json = json_decode($_POST['json'], true);
5397 $users = $json['user'];
5399 $success = group_create($name, $uid, $users);
5401 return api_format_data("group_create", $type, ['result' => $success]);
5403 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5406 * Create a new group.
5408 * @param string $type Return type (atom, rss, xml, json)
5410 * @return array|string
5411 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5413 function api_lists_create($type)
5417 if (api_user() === false) {
5418 throw new ForbiddenException();
5422 $user_info = api_get_user($a);
5423 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5424 $uid = $user_info['uid'];
5426 $success = group_create($name, $uid);
5427 if ($success['success']) {
5429 'name' => $success['name'],
5430 'id' => intval($success['gid']),
5431 'id_str' => (string) $success['gid'],
5432 'user' => $user_info
5435 return api_format_data("lists", $type, ['lists'=>$grp]);
5438 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5441 * Update the specified group with the posted array of contacts.
5443 * @param string $type Return type (atom, rss, xml, json)
5445 * @return array|string
5447 function api_friendica_group_update($type)
5451 if (api_user() === false) {
5452 throw new ForbiddenException();
5456 $user_info = api_get_user($a);
5457 $uid = $user_info['uid'];
5458 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5459 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5460 $json = json_decode($_POST['json'], true);
5461 $users = $json['user'];
5463 // error if no name specified
5465 throw new BadRequestException('group name not specified');
5468 // error if no gid specified
5470 throw new BadRequestException('gid not specified');
5474 $members = Contact::getByGroupId($gid);
5475 foreach ($members as $member) {
5476 $cid = $member['id'];
5477 foreach ($users as $user) {
5478 $found = ($user['cid'] == $cid ? true : false);
5480 if (!isset($found) || !$found) {
5481 Group::removeMemberByName($uid, $name, $cid);
5486 $erroraddinguser = false;
5488 foreach ($users as $user) {
5489 $cid = $user['cid'];
5490 // check if user really exists as contact
5492 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5497 if (count($contact)) {
5498 Group::addMember($gid, $cid);
5500 $erroraddinguser = true;
5501 $errorusers[] = $cid;
5505 // return success message incl. missing users in array
5506 $status = ($erroraddinguser ? "missing user" : "ok");
5507 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5508 return api_format_data("group_update", $type, ['result' => $success]);
5511 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5514 * Update information about a group.
5516 * @param string $type Return type (atom, rss, xml, json)
5518 * @return array|string
5519 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5521 function api_lists_update($type)
5525 if (api_user() === false) {
5526 throw new ForbiddenException();
5530 $user_info = api_get_user($a);
5531 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5532 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5533 $uid = $user_info['uid'];
5535 // error if no gid specified
5537 throw new BadRequestException('gid not specified');
5540 // get data of the specified group id
5541 $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5542 // error message if specified gid is not in database
5544 throw new BadRequestException('gid not available');
5547 if (Group::update($gid, $name)) {
5550 'id' => intval($gid),
5551 'id_str' => (string) $gid,
5552 'user' => $user_info
5555 return api_format_data("lists", $type, ['lists' => $list]);
5559 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5563 * @param string $type Return type (atom, rss, xml, json)
5565 * @return array|string
5567 function api_friendica_activity($type)
5571 if (api_user() === false) {
5572 throw new ForbiddenException();
5574 $verb = strtolower($a->argv[3]);
5575 $verb = preg_replace("|\..*$|", "", $verb);
5577 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5579 $res = Item::performLike($id, $verb);
5582 if ($type == "xml") {
5587 return api_format_data('ok', $type, ['ok' => $ok]);
5589 throw new BadRequestException('Error adding activity');
5593 /// @TODO move to top of file or somewhere better
5594 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5595 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5596 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5597 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5598 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5599 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5600 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5601 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5602 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5603 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5606 * @brief Returns notifications
5608 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5609 * @return string|array
5611 function api_friendica_notification($type)
5615 if (api_user() === false) {
5616 throw new ForbiddenException();
5619 throw new BadRequestException("Invalid argument count");
5621 $nm = new NotificationsManager();
5623 $notes = $nm->getAll([], "+seen -date", 50);
5625 if ($type == "xml") {
5627 foreach ($notes as $note) {
5628 $xmlnotes[] = ["@attributes" => $note];
5634 return api_format_data("notes", $type, ['note' => $notes]);
5638 * POST request with 'id' param as notification id
5640 * @brief Set notification as seen and returns associated item (if possible)
5642 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5643 * @return string|array
5645 function api_friendica_notification_seen($type)
5648 $user_info = api_get_user($a);
5650 if (api_user() === false || $user_info === false) {
5651 throw new ForbiddenException();
5654 throw new BadRequestException("Invalid argument count");
5657 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5659 $nm = new NotificationsManager();
5660 $note = $nm->getByID($id);
5661 if (is_null($note)) {
5662 throw new BadRequestException("Invalid argument");
5665 $nm->setSeen($note);
5666 if ($note['otype']=='item') {
5667 // would be really better with an ItemsManager and $im->getByID() :-P
5668 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5669 if (DBM::is_result($$item)) {
5670 // we found the item, return it to the user
5671 $ret = api_format_items([$item], $user_info, false, $type);
5672 $data = ['status' => $ret];
5673 return api_format_data("status", $type, $data);
5675 // the item can't be found, but we set the note as seen, so we count this as a success
5677 return api_format_data('result', $type, ['result' => "success"]);
5680 /// @TODO move to top of file or somewhere better
5681 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5682 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5685 * @brief update a direct_message to seen state
5687 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5688 * @return string|array (success result=ok, error result=error with error message)
5690 function api_friendica_direct_messages_setseen($type)
5693 if (api_user() === false) {
5694 throw new ForbiddenException();
5698 $user_info = api_get_user($a);
5699 $uid = $user_info['uid'];
5700 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5702 // return error if id is zero
5704 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5705 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5708 // error message if specified id is not in database
5709 if (!dba::exists('mail', ['id' => $id, 'uid' => $uid])) {
5710 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5711 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5714 // update seen indicator
5715 $result = dba::update('mail', ['seen' => true], ['id' => $id]);
5719 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5720 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5722 $answer = ['result' => 'error', 'message' => 'unknown error'];
5723 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5727 /// @TODO move to top of file or somewhere better
5728 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5731 * @brief search for direct_messages containing a searchstring through api
5733 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5734 * @param string $box
5735 * @return string|array (success: success=true if found and search_result contains found messages,
5736 * success=false if nothing was found, search_result='nothing found',
5737 * error: result=error with error message)
5739 function api_friendica_direct_messages_search($type, $box = "")
5743 if (api_user() === false) {
5744 throw new ForbiddenException();
5748 $user_info = api_get_user($a);
5749 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5750 $uid = $user_info['uid'];
5752 // error if no searchstring specified
5753 if ($searchstring == "") {
5754 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5755 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5758 // get data for the specified searchstring
5760 "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",
5762 dbesc('%'.$searchstring.'%')
5765 $profile_url = $user_info["url"];
5767 // message if nothing was found
5768 if (!DBM::is_result($r)) {
5769 $success = ['success' => false, 'search_results' => 'problem with query'];
5770 } elseif (count($r) == 0) {
5771 $success = ['success' => false, 'search_results' => 'nothing found'];
5774 foreach ($r as $item) {
5775 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5776 $recipient = $user_info;
5777 $sender = api_get_user($a, normalise_link($item['contact-url']));
5778 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5779 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5780 $sender = $user_info;
5783 if (isset($recipient) && isset($sender)) {
5784 $ret[] = api_format_messages($item, $recipient, $sender);
5787 $success = ['success' => true, 'search_results' => $ret];
5790 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5793 /// @TODO move to top of file or somewhere better
5794 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5797 * @brief return data of all the profiles a user has to the client
5799 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5800 * @return string|array
5802 function api_friendica_profile_show($type)
5806 if (api_user() === false) {
5807 throw new ForbiddenException();
5811 $profile_id = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5813 // retrieve general information about profiles for user
5814 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5815 $directory = Config::get('system', 'directory');
5817 // get data of the specified profile id or all profiles of the user if not specified
5818 if ($profile_id != 0) {
5820 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5825 // error message if specified gid is not in database
5826 if (!DBM::is_result($r)) {
5827 throw new BadRequestException("profile_id not available");
5831 "SELECT * FROM `profile` WHERE `uid` = %d",
5835 // loop through all returned profiles and retrieve data and users
5838 foreach ($r as $rr) {
5839 $profile = api_format_items_profiles($rr);
5841 // select all users from contact table, loop and prepare standard return for user data
5844 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5846 intval($rr['profile_id'])
5849 foreach ($nurls as $nurl) {
5850 $user = api_get_user($a, $nurl['nurl']);
5851 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5853 $profile['users'] = $users;
5855 // add prepared profile data to array for final return
5856 if ($type == "xml") {
5857 $profiles[$k++ . ":profile"] = $profile;
5859 $profiles[] = $profile;
5863 // return settings, authenticated user and profiles data
5864 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5866 $result = ['multi_profiles' => $multi_profiles ? true : false,
5867 'global_dir' => $directory,
5868 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5869 'profiles' => $profiles];
5870 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5872 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5875 * Returns a list of saved searches.
5877 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5879 * @param string $type Return format: json or xml
5881 * @return string|array
5883 function api_saved_searches_list($type)
5885 $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
5888 while ($term = $terms->fetch()) {
5890 'created_at' => api_date(time()),
5891 'id' => intval($term['id']),
5892 'id_str' => $term['id'],
5893 'name' => $term['term'],
5895 'query' => $term['term']
5901 return api_format_data("terms", $type, ['terms' => $result]);
5904 /// @TODO move to top of file or somewhere better
5905 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5908 @TODO Maybe open to implement?
5910 [pagename] => api/1.1/statuses/lookup.json
5911 [id] => 605138389168451584
5912 [include_cards] => true
5913 [cards_platform] => Android-12
5914 [include_entities] => true
5915 [include_my_retweet] => 1
5917 [include_reply_count] => true
5918 [include_descendent_reply_count] => true
5922 Not implemented by now:
5923 statuses/retweets_of_me
5928 account/update_location
5929 account/update_profile_background_image
5932 friendica/profile/update
5933 friendica/profile/create
5934 friendica/profile/delete
5936 Not implemented in status.net:
5937 statuses/retweeted_to_me
5938 statuses/retweeted_by_me
5939 direct_messages/destroy
5941 account/update_delivery_device
5942 notifications/follow