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]);
692 /// @TODO old-lost code? (twice)
693 // Counting is deactivated by now, due to performance issues
694 // count public wall messages
695 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
696 // intval($uinfo[0]['uid'])
698 //$countitms = $r[0]['count'];
701 // Counting is deactivated by now, due to performance issues
702 //$r = q("SELECT count(*) as `count` FROM `item`
703 // WHERE `contact-id` = %d",
704 // intval($uinfo[0]['id'])
706 //$countitms = $r[0]['count'];
710 /// @TODO old-lost code? (twice)
712 // Counting is deactivated by now, due to performance issues
714 $r = q("SELECT count(*) as `count` FROM `contact`
715 WHERE `uid` = %d AND `rel` IN ( %d, %d )
716 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
717 intval($uinfo[0]['uid']),
718 intval(CONTACT_IS_SHARING),
719 intval(CONTACT_IS_FRIEND)
721 $countfriends = $r[0]['count'];
723 $r = q("SELECT count(*) as `count` FROM `contact`
724 WHERE `uid` = %d AND `rel` IN ( %d, %d )
725 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
726 intval($uinfo[0]['uid']),
727 intval(CONTACT_IS_FOLLOWER),
728 intval(CONTACT_IS_FRIEND)
730 $countfollowers = $r[0]['count'];
732 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
733 intval($uinfo[0]['uid'])
735 $starred = $r[0]['count'];
738 if (! $uinfo[0]['self']) {
748 // Add a nick if it isn't present there
749 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
750 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
753 $network_name = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
755 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
757 if (!empty($profile['about'])) {
758 $description = $profile['about'];
760 $description = $uinfo[0]["about"];
763 if (!empty($usr['default-location'])) {
764 $location = $usr['default-location'];
765 } elseif (!empty($uinfo[0]["location"])) {
766 $location = $uinfo[0]["location"];
768 $location = $network_name;
772 'id' => intval($pcontact_id),
773 'id_str' => (string) intval($pcontact_id),
774 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
775 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
776 'location' => $location,
777 'description' => $description,
778 'profile_image_url' => $uinfo[0]['micro'],
779 'profile_image_url_https' => $uinfo[0]['micro'],
780 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
781 'profile_image_url_large' => $uinfo[0]["photo"],
782 'url' => $uinfo[0]['url'],
783 'protected' => false,
784 'followers_count' => intval($countfollowers),
785 'friends_count' => intval($countfriends),
787 'created_at' => api_date($uinfo[0]['created']),
788 'favourites_count' => intval($starred),
790 'time_zone' => 'UTC',
791 'geo_enabled' => false,
793 'statuses_count' => intval($countitms),
795 'contributors_enabled' => false,
796 'is_translator' => false,
797 'is_translation_enabled' => false,
798 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
799 'follow_request_sent' => false,
800 'statusnet_blocking' => false,
801 'notifications' => false,
803 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
804 'statusnet_profile_url' => $uinfo[0]['url'],
805 'uid' => intval($uinfo[0]['uid']),
806 'cid' => intval($uinfo[0]['cid']),
807 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
808 'self' => $uinfo[0]['self'],
809 'network' => $uinfo[0]['network'],
812 // If this is a local user and it uses Frio, we can get its color preferences.
814 $theme_info = dba::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
815 if ($theme_info['theme'] === 'frio') {
816 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
817 if ($schema && ($schema != '---')) {
818 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
819 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
820 require_once $schemefile;
823 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
824 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
825 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
831 $link_color = "#6fdbe8";
834 $bgcolor = "#ededed";
837 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
838 $ret['profile_link_color'] = str_replace('#', '', $link_color);
839 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
847 * @brief return api-formatted array for item's author and owner
849 * @param object $a App
850 * @param array $item item from db
851 * @return array(array:author, array:owner)
853 function api_item_get_user(App $a, $item)
855 $status_user = api_get_user($a, $item["author-id"]);
857 $status_user["protected"] = $item["private"];
859 if ($item['thr-parent'] == $item['uri']) {
860 $owner_user = api_get_user($a, $item["owner-id"]);
862 $owner_user = $status_user;
865 return ([$status_user, $owner_user]);
869 * @brief walks recursively through an array with the possibility to change value and key
871 * @param array $array The array to walk through
872 * @param string $callback The callback function
874 * @return array the transformed array
876 function api_walk_recursive(array &$array, callable $callback)
880 foreach ($array as $k => $v) {
882 if ($callback($v, $k)) {
883 $new_array[$k] = api_walk_recursive($v, $callback);
886 if ($callback($v, $k)) {
897 * @brief Callback function to transform the array in an array that can be transformed in a XML file
899 * @param mixed $item Array item value
900 * @param string $key Array key
902 * @return boolean Should the array item be deleted?
904 function api_reformat_xml(&$item, &$key)
906 if (is_bool($item)) {
907 $item = ($item ? "true" : "false");
910 if (substr($key, 0, 10) == "statusnet_") {
911 $key = "statusnet:".substr($key, 10);
912 } elseif (substr($key, 0, 10) == "friendica_") {
913 $key = "friendica:".substr($key, 10);
915 /// @TODO old-lost code?
917 // $key = "default:".$key;
923 * @brief Creates the XML from a JSON style array
925 * @param array $data JSON style array
926 * @param string $root_element Name of the root element
928 * @return string The XML data
930 function api_create_xml(array $data, $root_element)
932 $childname = key($data);
933 $data2 = array_pop($data);
936 $namespaces = ["" => "http://api.twitter.com",
937 "statusnet" => "http://status.net/schema/api/1/",
938 "friendica" => "http://friendi.ca/schema/api/1/",
939 "georss" => "http://www.georss.org/georss"];
941 /// @todo Auto detection of needed namespaces
942 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
946 if (is_array($data2)) {
947 api_walk_recursive($data2, "api_reformat_xml");
954 foreach ($data2 as $item) {
955 $data4[$i++ . ":" . $childname] = $item;
961 $data3 = [$root_element => $data2];
963 $ret = XML::fromArray($data3, $xml, false, $namespaces);
968 * @brief Formats the data according to the data type
970 * @param string $root_element Name of the root element
971 * @param string $type Return type (atom, rss, xml, json)
972 * @param array $data JSON style array
974 * @return (string|array) XML data or JSON data
976 function api_format_data($root_element, $type, $data)
982 $ret = api_create_xml($data, $root_element);
998 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
999 * returns a 401 status code and an error message if not.
1000 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
1002 * @param string $type Return type (atom, rss, xml, json)
1004 function api_account_verify_credentials($type)
1009 if (api_user() === false) {
1010 throw new ForbiddenException();
1013 unset($_REQUEST["user_id"]);
1014 unset($_GET["user_id"]);
1016 unset($_REQUEST["screen_name"]);
1017 unset($_GET["screen_name"]);
1019 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
1021 $user_info = api_get_user($a);
1023 // "verified" isn't used here in the standard
1024 unset($user_info["verified"]);
1026 // - Adding last status
1027 if (!$skip_status) {
1028 $user_info["status"] = api_status_show("raw");
1029 if (!count($user_info["status"])) {
1030 unset($user_info["status"]);
1032 unset($user_info["status"]["user"]);
1036 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1037 unset($user_info["uid"]);
1038 unset($user_info["self"]);
1040 return api_format_data("user", $type, ['user' => $user_info]);
1043 /// @TODO move to top of file or somewhere better
1044 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1047 * Get data from $_POST or $_GET
1051 function requestdata($k)
1053 if (x($_POST, $k)) {
1063 * Deprecated function to upload media.
1065 * @param string $type Return type (atom, rss, xml, json)
1067 * @return array|string
1069 function api_statuses_mediap($type)
1073 if (api_user() === false) {
1074 logger('api_statuses_update: no user');
1075 throw new ForbiddenException();
1077 $user_info = api_get_user($a);
1079 $_REQUEST['type'] = 'wall';
1080 $_REQUEST['profile_uid'] = api_user();
1081 $_REQUEST['api_source'] = true;
1082 $txt = requestdata('status');
1083 /// @TODO old-lost code?
1084 //$txt = urldecode(requestdata('status'));
1086 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1087 $txt = html2bb_video($txt);
1088 $config = HTMLPurifier_Config::createDefault();
1089 $config->set('Cache.DefinitionImpl', null);
1090 $purifier = new HTMLPurifier($config);
1091 $txt = $purifier->purify($txt);
1093 $txt = HTML::toBBCode($txt);
1095 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1097 $picture = wall_upload_post($a, false);
1099 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1100 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1103 // this should output the last post (the one we just posted).
1104 return api_status_show($type);
1107 /// @TODO move this to top of file or somewhere better!
1108 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1111 * Updates the user’s current status.
1113 * @param string $type Return type (atom, rss, xml, json)
1115 * @return array|string
1116 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1118 function api_statuses_update($type)
1123 if (api_user() === false) {
1124 logger('api_statuses_update: no user');
1125 throw new ForbiddenException();
1130 // convert $_POST array items to the form we use for web posts.
1131 if (requestdata('htmlstatus')) {
1132 $txt = requestdata('htmlstatus');
1133 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1134 $txt = html2bb_video($txt);
1136 $config = HTMLPurifier_Config::createDefault();
1137 $config->set('Cache.DefinitionImpl', null);
1139 $purifier = new HTMLPurifier($config);
1140 $txt = $purifier->purify($txt);
1142 $_REQUEST['body'] = HTML::toBBCode($txt);
1145 $_REQUEST['body'] = requestdata('status');
1148 $_REQUEST['title'] = requestdata('title');
1150 $parent = requestdata('in_reply_to_status_id');
1152 // Twidere sends "-1" if it is no reply ...
1153 if ($parent == -1) {
1157 if (ctype_digit($parent)) {
1158 $_REQUEST['parent'] = $parent;
1160 $_REQUEST['parent_uri'] = $parent;
1163 if (requestdata('lat') && requestdata('long')) {
1164 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1166 $_REQUEST['profile_uid'] = api_user();
1169 $_REQUEST['type'] = 'net-comment';
1171 // Check for throttling (maximum posts per day, week and month)
1172 $throttle_day = Config::get('system', 'throttle_limit_day');
1173 if ($throttle_day > 0) {
1174 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1177 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1178 AND `created` > '%s' AND `id` = `parent`",
1183 if (DBM::is_result($r)) {
1184 $posts_day = $r[0]["posts_day"];
1189 if ($posts_day > $throttle_day) {
1190 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1191 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1192 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));
1196 $throttle_week = Config::get('system', 'throttle_limit_week');
1197 if ($throttle_week > 0) {
1198 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1201 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1202 AND `created` > '%s' AND `id` = `parent`",
1207 if (DBM::is_result($r)) {
1208 $posts_week = $r[0]["posts_week"];
1213 if ($posts_week > $throttle_week) {
1214 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1215 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1216 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));
1220 $throttle_month = Config::get('system', 'throttle_limit_month');
1221 if ($throttle_month > 0) {
1222 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1225 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1226 AND `created` > '%s' AND `id` = `parent`",
1231 if (DBM::is_result($r)) {
1232 $posts_month = $r[0]["posts_month"];
1237 if ($posts_month > $throttle_month) {
1238 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1239 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1240 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));
1244 $_REQUEST['type'] = 'wall';
1247 if (x($_FILES, 'media')) {
1248 // upload the image if we have one
1249 $picture = wall_upload_post($a, false);
1250 if (is_array($picture)) {
1251 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1255 // To-Do: Multiple IDs
1256 if (requestdata('media_ids')) {
1258 "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",
1259 intval(requestdata('media_ids')),
1262 if (DBM::is_result($r)) {
1263 $phototypes = Image::supportedTypes();
1264 $ext = $phototypes[$r[0]['type']];
1265 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1266 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1270 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1272 $_REQUEST['api_source'] = true;
1274 if (!x($_REQUEST, "source")) {
1275 $_REQUEST["source"] = api_source();
1278 // call out normal post function
1281 // this should output the last post (the one we just posted).
1282 return api_status_show($type);
1285 /// @TODO move to top of file or somewhere better
1286 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1287 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1290 * Uploads an image to Friendica.
1293 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1295 function api_media_upload()
1299 if (api_user() === false) {
1301 throw new ForbiddenException();
1306 if (!x($_FILES, 'media')) {
1308 throw new BadRequestException("No media.");
1311 $media = wall_upload_post($a, false);
1314 throw new InternalServerErrorException();
1318 $returndata["media_id"] = $media["id"];
1319 $returndata["media_id_string"] = (string)$media["id"];
1320 $returndata["size"] = $media["size"];
1321 $returndata["image"] = ["w" => $media["width"],
1322 "h" => $media["height"],
1323 "image_type" => $media["type"]];
1325 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1327 return ["media" => $returndata];
1330 /// @TODO move to top of file or somewhere better
1331 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1335 * @param string $type Return type (atom, rss, xml, json)
1337 * @return array|string
1339 function api_status_show($type)
1343 $user_info = api_get_user($a);
1345 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1347 if ($type == "raw") {
1348 $privacy_sql = "AND NOT `private`";
1353 // get last public wall message
1354 $condition = ["`owner-id` = ? AND `uid` = ? AND `type` != 'activity' ".$privacy_sql,
1355 $user_info['pid'], api_user()];
1356 $lastwall = dba::selectFirst('item', [], $condition, ['order' => ['id' => true]]);
1358 if (DBM::is_result($lastwall)) {
1359 $in_reply_to = api_in_reply_to($lastwall);
1361 $converted = api_convert_item($lastwall);
1363 if ($type == "xml") {
1364 $geo = "georss:point";
1370 'created_at' => api_date($lastwall['created']),
1371 'id' => intval($lastwall['id']),
1372 'id_str' => (string) $lastwall['id'],
1373 'text' => $converted["text"],
1374 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1375 'truncated' => false,
1376 'in_reply_to_status_id' => $in_reply_to['status_id'],
1377 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1378 'in_reply_to_user_id' => $in_reply_to['user_id'],
1379 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1380 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1381 'user' => $user_info,
1383 'coordinates' => "",
1385 'contributors' => "",
1386 'is_quote_status' => false,
1387 'retweet_count' => 0,
1388 'favorite_count' => 0,
1389 'favorited' => $lastwall['starred'] ? true : false,
1390 'retweeted' => false,
1391 'possibly_sensitive' => false,
1393 'statusnet_html' => $converted["html"],
1394 'statusnet_conversation_id' => $lastwall['parent'],
1395 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1398 if (count($converted["attachments"]) > 0) {
1399 $status_info["attachments"] = $converted["attachments"];
1402 if (count($converted["entities"]) > 0) {
1403 $status_info["entities"] = $converted["entities"];
1406 if ($status_info["source"] == 'web') {
1407 $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $user_info['url']);
1408 } elseif (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $status_info["source"]) {
1409 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $user_info['url']).')');
1412 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1413 unset($status_info["user"]["uid"]);
1414 unset($status_info["user"]["self"]);
1416 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1418 if ($type == "raw") {
1419 return $status_info;
1422 return api_format_data("statuses", $type, ['status' => $status_info]);
1427 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1428 * The author's most recent status will be returned inline.
1430 * @param string $type Return type (atom, rss, xml, json)
1431 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1433 function api_users_show($type)
1437 $user_info = api_get_user($a);
1439 $condition = ["`owner-id` = ? AND `uid` = ? AND `verb` = ? AND `type` != 'activity' AND NOT `private`",
1440 $user_info['pid'], api_user(), ACTIVITY_POST];
1441 $lastwall = dba::selectFirst('item', [], $condition, ['order' => ['id' => true]]);
1443 if (DBM::is_result($lastwall)) {
1444 $in_reply_to = api_in_reply_to($lastwall);
1446 $converted = api_convert_item($lastwall);
1448 if ($type == "xml") {
1449 $geo = "georss:point";
1454 $user_info['status'] = [
1455 'text' => $converted["text"],
1456 'truncated' => false,
1457 'created_at' => api_date($lastwall['created']),
1458 'in_reply_to_status_id' => $in_reply_to['status_id'],
1459 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1460 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1461 'id' => intval($lastwall['contact-id']),
1462 'id_str' => (string) $lastwall['contact-id'],
1463 'in_reply_to_user_id' => $in_reply_to['user_id'],
1464 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1465 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1467 'favorited' => $lastwall['starred'] ? true : false,
1468 'statusnet_html' => $converted["html"],
1469 'statusnet_conversation_id' => $lastwall['parent'],
1470 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1473 if (count($converted["attachments"]) > 0) {
1474 $user_info["status"]["attachments"] = $converted["attachments"];
1477 if (count($converted["entities"]) > 0) {
1478 $user_info["status"]["entities"] = $converted["entities"];
1481 if ($user_info["status"]["source"] == 'web') {
1482 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $user_info['url']);
1485 if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
1486 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $user_info['url']) . ')');
1490 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1491 unset($user_info["uid"]);
1492 unset($user_info["self"]);
1494 return api_format_data("user", $type, ['user' => $user_info]);
1497 /// @TODO move to top of file or somewhere better
1498 api_register_func('api/users/show', 'api_users_show');
1499 api_register_func('api/externalprofile/show', 'api_users_show');
1502 * Search a public user account.
1504 * @param string $type Return type (atom, rss, xml, json)
1506 * @return array|string
1507 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1509 function api_users_search($type)
1515 if (x($_GET, 'q')) {
1516 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1518 if (!DBM::is_result($r)) {
1519 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1522 if (DBM::is_result($r)) {
1524 foreach ($r as $user) {
1525 $user_info = api_get_user($a, $user["id"]);
1527 if ($type == "xml") {
1528 $userlist[$k++.":user"] = $user_info;
1530 $userlist[] = $user_info;
1533 $userlist = ["users" => $userlist];
1535 throw new BadRequestException("User ".$_GET["q"]." not found.");
1538 throw new BadRequestException("No user specified.");
1541 return api_format_data("users", $type, $userlist);
1544 /// @TODO move to top of file or somewhere better
1545 api_register_func('api/users/search', 'api_users_search');
1548 * Return user objects
1550 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1552 * @param string $type Return format: json or xml
1554 * @return array|string
1555 * @throws NotFoundException if the results are empty.
1557 function api_users_lookup($type)
1561 if (x($_REQUEST['user_id'])) {
1562 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1564 $users[] = api_get_user(get_app(), $id);
1569 if (empty($users)) {
1570 throw new NotFoundException;
1573 return api_format_data("users", $type, ['users' => $users]);
1576 /// @TODO move to top of file or somewhere better
1577 api_register_func('api/users/lookup', 'api_users_lookup', true);
1580 * Returns statuses that match a specified query.
1582 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1584 * @param string $type Return format: json, xml, atom, rss
1586 * @return array|string
1587 * @throws BadRequestException if the "q" parameter is missing.
1589 function api_search($type)
1592 $user_info = api_get_user($a);
1594 if (api_user() === false || $user_info === false) {
1595 throw new ForbiddenException();
1600 if (!x($_REQUEST, 'q')) {
1601 throw new BadRequestException("q parameter is required.");
1604 if (x($_REQUEST, 'rpp')) {
1605 $count = $_REQUEST['rpp'];
1606 } elseif (x($_REQUEST, 'count')) {
1607 $count = $_REQUEST['count'];
1612 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1613 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1614 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1616 $start = $page * $count;
1618 $condition = ["`verb` = ? AND `item`.`id` > ?
1619 AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1620 AND `item`.`body` LIKE CONCAT('%',?,'%')",
1621 ACTIVITY_POST, $since_id, api_user(), $_REQUEST['q']];
1624 $condition[0] .= " AND `item`.`id` <= ?";
1625 $condition[] = $max_id;
1628 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1629 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1631 $data['status'] = api_format_items(dba::inArray($statuses), $user_info);
1633 return api_format_data("statuses", $type, $data);
1636 /// @TODO move to top of file or somewhere better
1637 api_register_func('api/search/tweets', 'api_search', true);
1638 api_register_func('api/search', 'api_search', true);
1641 * Returns the most recent statuses posted by the user and the users they follow.
1643 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1645 * @param string $type Return type (atom, rss, xml, json)
1647 * @todo Optional parameters
1648 * @todo Add reply info
1650 function api_statuses_home_timeline($type)
1653 $user_info = api_get_user($a);
1655 if (api_user() === false || $user_info === false) {
1656 throw new ForbiddenException();
1659 unset($_REQUEST["user_id"]);
1660 unset($_GET["user_id"]);
1662 unset($_REQUEST["screen_name"]);
1663 unset($_GET["screen_name"]);
1665 // get last network messages
1668 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1669 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1673 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1674 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1675 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1676 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1677 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1679 $start = $page * $count;
1681 $condition = ["`uid` = ? AND `verb` = ? AND `item`.`id` > ?", api_user(), ACTIVITY_POST, $since_id];
1684 $condition[0] .= " AND `item`.`id` <= ?";
1685 $condition[] = $max_id;
1687 if ($exclude_replies > 0) {
1688 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1690 if ($conversation_id > 0) {
1691 $condition[0] .= " AND `item`.`parent` = ?";
1692 $condition[] = $conversation_id;
1695 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1696 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1698 $items = dba::inArray($statuses);
1700 $ret = api_format_items($items, $user_info, false, $type);
1702 // Set all posts from the query above to seen
1704 foreach ($items as $item) {
1705 $idarray[] = intval($item["id"]);
1708 if (!empty($idarray)) {
1709 $unseen = dba::exists('item', ['unseen' => true, 'id' => $idarray]);
1711 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1715 $data = ['status' => $ret];
1719 $data = api_rss_extra($a, $data, $user_info);
1723 return api_format_data("statuses", $type, $data);
1726 /// @TODO move to top of file or somewhere better
1727 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1728 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1731 * Returns the most recent statuses from public users.
1733 * @param string $type Return type (atom, rss, xml, json)
1735 * @return array|string
1737 function api_statuses_public_timeline($type)
1740 $user_info = api_get_user($a);
1742 if (api_user() === false || $user_info === false) {
1743 throw new ForbiddenException();
1746 // get last network messages
1749 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1750 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1754 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1755 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1756 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1757 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1758 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1760 $start = $page * $count;
1763 if ($exclude_replies && !$conversation_id) {
1764 $condition = ["`verb` = ? AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall`",
1765 ACTIVITY_POST, $since_id];
1768 $condition[0] .= " AND `thread`.`iid` <= ?";
1769 $condition[] = $max_id;
1772 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1773 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1775 $r = dba::inArray($statuses);
1777 $condition = ["`verb` = ? AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin`",
1778 ACTIVITY_POST, $since_id];
1781 $condition[0] .= " AND `item`.`id` <= ?";
1782 $condition[] = $max_id;
1784 if ($conversation_id > 0) {
1785 $condition[0] .= " AND `item`.`parent` = ?";
1786 $condition[] = $conversation_id;
1789 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1790 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1792 $r = dba::inArray($statuses);
1795 $ret = api_format_items($r, $user_info, false, $type);
1797 $data = ['status' => $ret];
1801 $data = api_rss_extra($a, $data, $user_info);
1805 return api_format_data("statuses", $type, $data);
1808 /// @TODO move to top of file or somewhere better
1809 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1812 * Returns the most recent statuses posted by users this node knows about.
1814 * @brief Returns the list of public federated posts this node knows about
1816 * @param string $type Return format: json, xml, atom, rss
1817 * @return array|string
1818 * @throws ForbiddenException
1820 function api_statuses_networkpublic_timeline($type)
1823 $user_info = api_get_user($a);
1825 if (api_user() === false || $user_info === false) {
1826 throw new ForbiddenException();
1829 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1830 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1833 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1834 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1838 $start = ($page - 1) * $count;
1840 $condition = ["`uid` = 0 AND `verb` = ? AND `thread`.`iid` > ? AND NOT `private`",
1841 ACTIVITY_POST, $since_id];
1844 $condition[0] .= " AND `thread`.`iid` <= ?";
1845 $condition[] = $max_id;
1848 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1849 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1851 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
1853 $data = ['status' => $ret];
1857 $data = api_rss_extra($a, $data, $user_info);
1861 return api_format_data("statuses", $type, $data);
1864 /// @TODO move to top of file or somewhere better
1865 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1868 * Returns a single status.
1870 * @param string $type Return type (atom, rss, xml, json)
1872 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1874 function api_statuses_show($type)
1877 $user_info = api_get_user($a);
1879 if (api_user() === false || $user_info === false) {
1880 throw new ForbiddenException();
1884 $id = intval($a->argv[3]);
1887 $id = intval($_REQUEST["id"]);
1892 $id = intval($a->argv[4]);
1895 logger('API: api_statuses_show: ' . $id);
1897 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1899 // try to fetch the item for the local user - or the public item, if there is no local one
1900 $uri_item = dba::selectFirst('item', ['uri'], ['id' => $id]);
1901 if (!DBM::is_result($uri_item)) {
1902 throw new BadRequestException("There is no status with this id.");
1905 $item = dba::selectFirst('item', ['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1906 if (!DBM::is_result($item)) {
1907 throw new BadRequestException("There is no status with this id.");
1912 if ($conversation) {
1913 $condition = ['parent' => $id, 'verb' => ACTIVITY_POST];
1914 $params = ['order' => ['id' => true]];
1916 $condition = ['id' => $id, 'verb' => ACTIVITY_POST];
1920 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1922 /// @TODO How about copying this to above methods which don't check $r ?
1923 if (!DBM::is_result($statuses)) {
1924 throw new BadRequestException("There is no status with this id.");
1927 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
1929 if ($conversation) {
1930 $data = ['status' => $ret];
1931 return api_format_data("statuses", $type, $data);
1933 $data = ['status' => $ret[0]];
1934 return api_format_data("status", $type, $data);
1938 /// @TODO move to top of file or somewhere better
1939 api_register_func('api/statuses/show', 'api_statuses_show', true);
1943 * @param string $type Return type (atom, rss, xml, json)
1945 * @todo nothing to say?
1947 function api_conversation_show($type)
1950 $user_info = api_get_user($a);
1952 if (api_user() === false || $user_info === false) {
1953 throw new ForbiddenException();
1957 $id = intval($a->argv[3]);
1958 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1959 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1963 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1964 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1966 $start = $page*$count;
1969 $id = intval($_REQUEST["id"]);
1974 $id = intval($a->argv[4]);
1977 logger('API: api_conversation_show: '.$id);
1979 // try to fetch the item for the local user - or the public item, if there is no local one
1980 $item = dba::selectFirst('item', ['parent-uri'], ['id' => $id]);
1981 if (!DBM::is_result($item)) {
1982 throw new BadRequestException("There is no status with this id.");
1985 $parent = dba::selectFirst('item', ['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1986 if (!DBM::is_result($parent)) {
1987 throw new BadRequestException("There is no status with this id.");
1990 $id = $parent['id'];
1992 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `verb` = ? AND `item`.`id` > ?",
1993 $id, api_user(), ACTIVITY_POST, $since_id];
1996 $condition[0] .= " AND `item`.`id` <= ?";
1997 $condition[] = $max_id;
2000 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2001 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2003 if (!DBM::is_result($statuses)) {
2004 throw new BadRequestException("There is no status with id $id.");
2007 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
2009 $data = ['status' => $ret];
2010 return api_format_data("statuses", $type, $data);
2013 /// @TODO move to top of file or somewhere better
2014 api_register_func('api/conversation/show', 'api_conversation_show', true);
2015 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2020 * @param string $type Return type (atom, rss, xml, json)
2022 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2024 function api_statuses_repeat($type)
2030 if (api_user() === false) {
2031 throw new ForbiddenException();
2037 $id = intval($a->argv[3]);
2040 $id = intval($_REQUEST["id"]);
2045 $id = intval($a->argv[4]);
2048 logger('API: api_statuses_repeat: '.$id);
2050 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2051 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2053 if (DBM::is_result($item) && $item['body'] != "") {
2054 if (strpos($item['body'], "[/share]") !== false) {
2055 $pos = strpos($item['body'], "[share");
2056 $post = substr($item['body'], $pos);
2058 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2060 $post .= $item['body'];
2061 $post .= "[/share]";
2063 $_REQUEST['body'] = $post;
2064 $_REQUEST['profile_uid'] = api_user();
2065 $_REQUEST['type'] = 'wall';
2066 $_REQUEST['api_source'] = true;
2068 if (!x($_REQUEST, "source")) {
2069 $_REQUEST["source"] = api_source();
2074 throw new ForbiddenException();
2077 // this should output the last post (the one we just posted).
2079 return api_status_show($type);
2082 /// @TODO move to top of file or somewhere better
2083 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2086 * Destroys a specific status.
2088 * @param string $type Return type (atom, rss, xml, json)
2090 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2092 function api_statuses_destroy($type)
2096 if (api_user() === false) {
2097 throw new ForbiddenException();
2103 $id = intval($a->argv[3]);
2106 $id = intval($_REQUEST["id"]);
2111 $id = intval($a->argv[4]);
2114 logger('API: api_statuses_destroy: '.$id);
2116 $ret = api_statuses_show($type);
2118 Item::deleteForUser(['id' => $id], api_user());
2123 /// @TODO move to top of file or somewhere better
2124 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2127 * Returns the most recent mentions.
2129 * @param string $type Return type (atom, rss, xml, json)
2131 * @see http://developer.twitter.com/doc/get/statuses/mentions
2133 function api_statuses_mentions($type)
2136 $user_info = api_get_user($a);
2138 if (api_user() === false || $user_info === false) {
2139 throw new ForbiddenException();
2142 unset($_REQUEST["user_id"]);
2143 unset($_GET["user_id"]);
2145 unset($_REQUEST["screen_name"]);
2146 unset($_GET["screen_name"]);
2148 // get last network messages
2151 $since_id = defaults($_REQUEST, 'since_id', 0);
2152 $max_id = defaults($_REQUEST, 'max_id' , 0);
2153 $count = defaults($_REQUEST, 'count' , 20);
2154 $page = defaults($_REQUEST, 'page' , 1);
2159 $start = ($page - 1) * $count;
2161 $condition = ["`uid` = ? AND `verb` = ? AND `item`.`id` > ? AND `author-id` != ?
2162 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = ? AND `mention` AND NOT `ignored`)",
2163 api_user(), ACTIVITY_POST, $since_id, $user_info['pid'], api_user()];
2166 $condition[0] .= " AND `item`.`id` <= ?";
2167 $condition[] = $max_id;
2170 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2171 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2173 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
2175 $data = ['status' => $ret];
2179 $data = api_rss_extra($a, $data, $user_info);
2183 return api_format_data("statuses", $type, $data);
2186 /// @TODO move to top of file or somewhere better
2187 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2188 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2191 * Returns the most recent statuses posted by the user.
2193 * @brief Returns a user's public timeline
2195 * @param string $type Either "json" or "xml"
2196 * @return string|array
2197 * @throws ForbiddenException
2198 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2200 function api_statuses_user_timeline($type)
2203 $user_info = api_get_user($a);
2205 if (api_user() === false || $user_info === false) {
2206 throw new ForbiddenException();
2210 "api_statuses_user_timeline: api_user: ". api_user() .
2211 "\nuser_info: ".print_r($user_info, true) .
2212 "\n_REQUEST: ".print_r($_REQUEST, true),
2216 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2217 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2218 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2219 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2222 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2223 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2227 $start = ($page - 1) * $count;
2229 $condition = ["`uid` = ? AND `verb` = ? AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2230 api_user(), ACTIVITY_POST, $since_id, $user_info['cid']];
2232 if ($user_info['self'] == 1) {
2233 $condition[0] .= ' AND `item`.`wall` ';
2236 if ($exclude_replies > 0) {
2237 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2240 if ($conversation_id > 0) {
2241 $condition[0] .= " AND `item`.`parent` = ?";
2242 $condition[] = $conversation_id;
2246 $condition[0] .= " AND `item`.`id` <= ?";
2247 $condition[] = $max_id;
2250 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2251 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2253 $ret = api_format_items(dba::inArray($statuses), $user_info, true, $type);
2255 $data = ['status' => $ret];
2259 $data = api_rss_extra($a, $data, $user_info);
2263 return api_format_data("statuses", $type, $data);
2266 /// @TODO move to top of file or somewhere better
2267 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2270 * Star/unstar an item.
2271 * param: id : id of the item
2273 * @param string $type Return type (atom, rss, xml, json)
2275 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2277 function api_favorites_create_destroy($type)
2281 if (api_user() === false) {
2282 throw new ForbiddenException();
2285 // for versioned api.
2286 /// @TODO We need a better global soluton
2287 $action_argv_id = 2;
2288 if ($a->argv[1] == "1.1") {
2289 $action_argv_id = 3;
2292 if ($a->argc <= $action_argv_id) {
2293 throw new BadRequestException("Invalid request.");
2295 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2296 if ($a->argc == $action_argv_id + 2) {
2297 $itemid = intval($a->argv[$action_argv_id + 1]);
2299 /// @TODO use x() to check if _REQUEST contains 'id'
2300 $itemid = intval($_REQUEST['id']);
2303 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2305 if (!DBM::is_result($item)) {
2306 throw new BadRequestException("Invalid item.");
2311 $item['starred'] = 1;
2314 $item['starred'] = 0;
2317 throw new BadRequestException("Invalid action ".$action);
2320 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2323 throw new InternalServerErrorException("DB error");
2327 $user_info = api_get_user($a);
2328 $rets = api_format_items([$item], $user_info, false, $type);
2331 $data = ['status' => $ret];
2335 $data = api_rss_extra($a, $data, $user_info);
2338 return api_format_data("status", $type, $data);
2341 /// @TODO move to top of file or somewhere better
2342 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2343 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2346 * Returns the most recent favorite statuses.
2348 * @param string $type Return type (atom, rss, xml, json)
2350 * @return string|array
2352 function api_favorites($type)
2357 $user_info = api_get_user($a);
2359 if (api_user() === false || $user_info === false) {
2360 throw new ForbiddenException();
2365 // in friendica starred item are private
2366 // return favorites only for self
2367 logger('api_favorites: self:' . $user_info['self']);
2369 if ($user_info['self'] == 0) {
2373 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2374 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2375 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2376 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2381 $start = $page*$count;
2383 $condition = ["`uid` = ? AND `verb` = ? AND `id` > ? AND `starred`",
2384 api_user(), ACTIVITY_POST, $since_id];
2386 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2389 $condition[0] .= " AND `item`.`id` <= ?";
2390 $condition[] = $max_id;
2393 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2395 $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
2398 $data = ['status' => $ret];
2402 $data = api_rss_extra($a, $data, $user_info);
2405 return api_format_data("statuses", $type, $data);
2408 /// @TODO move to top of file or somewhere better
2409 api_register_func('api/favorites', 'api_favorites', true);
2413 * @param array $item
2414 * @param array $recipient
2415 * @param array $sender
2419 function api_format_messages($item, $recipient, $sender)
2421 // standard meta information
2423 'id' => $item['id'],
2424 'sender_id' => $sender['id'] ,
2426 'recipient_id' => $recipient['id'],
2427 'created_at' => api_date($item['created']),
2428 'sender_screen_name' => $sender['screen_name'],
2429 'recipient_screen_name' => $recipient['screen_name'],
2430 'sender' => $sender,
2431 'recipient' => $recipient,
2433 'friendica_seen' => $item['seen'],
2434 'friendica_parent_uri' => $item['parent-uri'],
2437 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2438 unset($ret["sender"]["uid"]);
2439 unset($ret["sender"]["self"]);
2440 unset($ret["recipient"]["uid"]);
2441 unset($ret["recipient"]["self"]);
2443 //don't send title to regular StatusNET requests to avoid confusing these apps
2444 if (x($_GET, 'getText')) {
2445 $ret['title'] = $item['title'];
2446 if ($_GET['getText'] == 'html') {
2447 $ret['text'] = BBCode::convert($item['body'], false);
2448 } elseif ($_GET['getText'] == 'plain') {
2449 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2452 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2454 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2455 unset($ret['sender']);
2456 unset($ret['recipient']);
2464 * @param array $item
2468 function api_convert_item($item)
2470 $body = $item['body'];
2471 $attachments = api_get_attachments($body);
2473 // Workaround for ostatus messages where the title is identically to the body
2474 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2475 $statusbody = trim(HTML::toPlaintext($html, 0));
2477 // handle data: images
2478 $statusbody = api_format_items_embeded_images($item, $statusbody);
2480 $statustitle = trim($item['title']);
2482 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2483 $statustext = trim($statusbody);
2485 $statustext = trim($statustitle."\n\n".$statusbody);
2488 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2489 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2492 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2494 // Workaround for clients with limited HTML parser functionality
2495 $search = ["<br>", "<blockquote>", "</blockquote>",
2496 "<h1>", "</h1>", "<h2>", "</h2>",
2497 "<h3>", "</h3>", "<h4>", "</h4>",
2498 "<h5>", "</h5>", "<h6>", "</h6>"];
2499 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2500 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2501 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2502 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2503 $statushtml = str_replace($search, $replace, $statushtml);
2505 if ($item['title'] != "") {
2506 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2510 $oldtext = $statushtml;
2511 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2512 } while ($oldtext != $statushtml);
2514 if (substr($statushtml, 0, 4) == '<br>') {
2515 $statushtml = substr($statushtml, 4);
2518 if (substr($statushtml, 0, -4) == '<br>') {
2519 $statushtml = substr($statushtml, -4);
2522 // feeds without body should contain the link
2523 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2524 $statushtml .= BBCode::convert($item['plink']);
2527 $entities = api_get_entitities($statustext, $body);
2530 "text" => $statustext,
2531 "html" => $statushtml,
2532 "attachments" => $attachments,
2533 "entities" => $entities
2539 * @param string $body
2543 function api_get_attachments(&$body)
2546 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2548 $URLSearchString = "^\[\]";
2549 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2557 foreach ($images[1] as $image) {
2558 $imagedata = Image::getInfoFromURL($image);
2561 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2565 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2566 foreach ($images[0] as $orig) {
2567 $body = str_replace($orig, "", $body);
2571 return $attachments;
2576 * @param string $text
2577 * @param string $bbcode
2580 * @todo Links at the first character of the post
2582 function api_get_entitities(&$text, $bbcode)
2584 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2586 if ($include_entities != "true") {
2587 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2589 foreach ($images[1] as $image) {
2590 $replace = proxy_url($image);
2591 $text = str_replace($image, $replace, $text);
2596 $bbcode = BBCode::cleanPictureLinks($bbcode);
2598 // Change pure links in text to bbcode uris
2599 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2602 $entities["hashtags"] = [];
2603 $entities["symbols"] = [];
2604 $entities["urls"] = [];
2605 $entities["user_mentions"] = [];
2607 $URLSearchString = "^\[\]";
2609 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2611 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2612 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2613 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2615 $bbcode = preg_replace(
2616 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2617 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2620 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2622 $bbcode = preg_replace(
2623 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2624 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2627 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2629 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2631 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2632 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2635 foreach ($urls[1] as $id => $url) {
2636 //$start = strpos($text, $url, $offset);
2637 $start = iconv_strpos($text, $url, 0, "UTF-8");
2638 if (!($start === false)) {
2639 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2643 ksort($ordered_urls);
2646 //foreach ($urls[1] AS $id=>$url) {
2647 foreach ($ordered_urls as $url) {
2648 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2649 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2651 $display_url = $url["title"];
2653 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2654 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2656 if (strlen($display_url) > 26) {
2657 $display_url = substr($display_url, 0, 25)."…";
2661 //$start = strpos($text, $url, $offset);
2662 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2663 if (!($start === false)) {
2664 $entities["urls"][] = ["url" => $url["url"],
2665 "expanded_url" => $url["url"],
2666 "display_url" => $display_url,
2667 "indices" => [$start, $start+strlen($url["url"])]];
2668 $offset = $start + 1;
2672 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2673 $ordered_images = [];
2674 foreach ($images[1] as $image) {
2675 //$start = strpos($text, $url, $offset);
2676 $start = iconv_strpos($text, $image, 0, "UTF-8");
2677 if (!($start === false)) {
2678 $ordered_images[$start] = $image;
2681 //$entities["media"] = array();
2684 foreach ($ordered_images as $url) {
2685 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2686 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2688 if (strlen($display_url) > 26) {
2689 $display_url = substr($display_url, 0, 25)."…";
2692 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2693 if (!($start === false)) {
2694 $image = Image::getInfoFromURL($url);
2696 // If image cache is activated, then use the following sizes:
2697 // thumb (150), small (340), medium (600) and large (1024)
2698 if (!Config::get("system", "proxy_disabled")) {
2699 $media_url = proxy_url($url);
2702 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2703 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2705 if (($image[0] > 150) || ($image[1] > 150)) {
2706 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2707 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2710 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2711 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2713 if (($image[0] > 600) || ($image[1] > 600)) {
2714 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2715 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2719 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2722 $entities["media"][] = [
2724 "id_str" => (string)$start+1,
2725 "indices" => [$start, $start+strlen($url)],
2726 "media_url" => normalise_link($media_url),
2727 "media_url_https" => $media_url,
2729 "display_url" => $display_url,
2730 "expanded_url" => $url,
2734 $offset = $start + 1;
2743 * @param array $item
2744 * @param string $text
2748 function api_format_items_embeded_images($item, $text)
2750 $text = preg_replace_callback(
2751 '|data:image/([^;]+)[^=]+=*|m',
2752 function () use ($item) {
2753 return System::baseUrl() . '/display/' . $item['guid'];
2761 * @brief return <a href='url'>name</a> as array
2763 * @param string $txt text
2768 function api_contactlink_to_array($txt)
2771 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2772 if ($r && count($match)==3) {
2774 'name' => $match[2],
2788 * @brief return likes, dislikes and attend status for item
2790 * @param array $item array
2791 * @param string $type Return type (atom, rss, xml, json)
2794 * likes => int count,
2795 * dislikes => int count
2797 function api_format_items_activities(&$item, $type = "json")
2806 'attendmaybe' => [],
2810 'SELECT * FROM `item`
2811 WHERE `uid` = %d AND `thr-parent` = "%s" AND `visible` AND NOT `deleted`',
2812 intval($item['uid']),
2816 foreach ($items as $i) {
2817 // not used as result should be structured like other user data
2818 //builtin_activity_puller($i, $activities);
2820 // get user data and add it to the array of the activity
2821 $user = api_get_user($a, $i['author-id']);
2822 switch ($i['verb']) {
2824 $activities['like'][] = $user;
2826 case ACTIVITY_DISLIKE:
2827 $activities['dislike'][] = $user;
2829 case ACTIVITY_ATTEND:
2830 $activities['attendyes'][] = $user;
2832 case ACTIVITY_ATTENDNO:
2833 $activities['attendno'][] = $user;
2835 case ACTIVITY_ATTENDMAYBE:
2836 $activities['attendmaybe'][] = $user;
2843 if ($type == "xml") {
2844 $xml_activities = [];
2845 foreach ($activities as $k => $v) {
2846 // change xml element from "like" to "friendica:like"
2847 $xml_activities["friendica:".$k] = $v;
2848 // add user data into xml output
2850 foreach ($v as $user) {
2851 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2854 $activities = $xml_activities;
2862 * @brief return data from profiles
2864 * @param array $profile_row array containing data from db table 'profile'
2867 function api_format_items_profiles($profile_row)
2870 'profile_id' => $profile_row['id'],
2871 'profile_name' => $profile_row['profile-name'],
2872 'is_default' => $profile_row['is-default'] ? true : false,
2873 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2874 'profile_photo' => $profile_row['photo'],
2875 'profile_thumb' => $profile_row['thumb'],
2876 'publish' => $profile_row['publish'] ? true : false,
2877 'net_publish' => $profile_row['net-publish'] ? true : false,
2878 'description' => $profile_row['pdesc'],
2879 'date_of_birth' => $profile_row['dob'],
2880 'address' => $profile_row['address'],
2881 'city' => $profile_row['locality'],
2882 'region' => $profile_row['region'],
2883 'postal_code' => $profile_row['postal-code'],
2884 'country' => $profile_row['country-name'],
2885 'hometown' => $profile_row['hometown'],
2886 'gender' => $profile_row['gender'],
2887 'marital' => $profile_row['marital'],
2888 'marital_with' => $profile_row['with'],
2889 'marital_since' => $profile_row['howlong'],
2890 'sexual' => $profile_row['sexual'],
2891 'politic' => $profile_row['politic'],
2892 'religion' => $profile_row['religion'],
2893 'public_keywords' => $profile_row['pub_keywords'],
2894 'private_keywords' => $profile_row['prv_keywords'],
2895 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2896 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2897 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2898 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2899 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2900 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2901 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2902 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2903 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2904 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2905 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2906 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2907 'homepage' => $profile_row['homepage'],
2914 * @brief format items to be returned by api
2916 * @param array $r array of items
2917 * @param array $user_info
2918 * @param bool $filter_user filter items by $user_info
2919 * @param string $type Return type (atom, rss, xml, json)
2921 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2927 foreach ($r as $item) {
2928 localize_item($item);
2929 list($status_user, $owner_user) = api_item_get_user($a, $item);
2931 // Look if the posts are matching if they should be filtered by user id
2932 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2936 $in_reply_to = api_in_reply_to($item);
2938 $converted = api_convert_item($item);
2940 if ($type == "xml") {
2941 $geo = "georss:point";
2947 'text' => $converted["text"],
2948 'truncated' => false,
2949 'created_at'=> api_date($item['created']),
2950 'in_reply_to_status_id' => $in_reply_to['status_id'],
2951 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2952 'source' => (($item['app']) ? $item['app'] : 'web'),
2953 'id' => intval($item['id']),
2954 'id_str' => (string) intval($item['id']),
2955 'in_reply_to_user_id' => $in_reply_to['user_id'],
2956 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2957 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2959 'favorited' => $item['starred'] ? true : false,
2960 'user' => $status_user ,
2961 'friendica_owner' => $owner_user,
2962 //'entities' => NULL,
2963 'statusnet_html' => $converted["html"],
2964 'statusnet_conversation_id' => $item['parent'],
2965 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2966 'friendica_activities' => api_format_items_activities($item, $type),
2969 if (count($converted["attachments"]) > 0) {
2970 $status["attachments"] = $converted["attachments"];
2973 if (count($converted["entities"]) > 0) {
2974 $status["entities"] = $converted["entities"];
2977 if ($status["source"] == 'web') {
2978 $status["source"] = ContactSelector::networkToName($item['network'], $user_info['url']);
2979 } elseif (ContactSelector::networkToName($item['network'], $user_info['url']) != $status["source"]) {
2980 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $user_info['url']).')');
2983 if ($item["id"] == $item["parent"]) {
2984 $retweeted_item = api_share_as_retweet($item);
2985 if ($retweeted_item !== false) {
2986 $retweeted_status = $status;
2988 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
2989 } catch (BadRequestException $e) {
2990 // user not found. should be found?
2991 /// @todo check if the user should be always found
2992 $retweeted_status["user"] = [];
2995 $rt_converted = api_convert_item($retweeted_item);
2997 $retweeted_status['text'] = $rt_converted["text"];
2998 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2999 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3000 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3001 $status['retweeted_status'] = $retweeted_status;
3005 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3006 unset($status["user"]["uid"]);
3007 unset($status["user"]["self"]);
3009 if ($item["coord"] != "") {
3010 $coords = explode(' ', $item["coord"]);
3011 if (count($coords) == 2) {
3012 if ($type == "json") {
3013 $status["geo"] = ['type' => 'Point',
3014 'coordinates' => [(float) $coords[0],
3015 (float) $coords[1]]];
3016 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3017 $status["georss:point"] = $item["coord"];
3027 * Returns the remaining number of API requests available to the user before the API limit is reached.
3029 * @param string $type Return type (atom, rss, xml, json)
3031 * @return array|string
3033 function api_account_rate_limit_status($type)
3035 if ($type == "xml") {
3037 'remaining-hits' => '150',
3038 '@attributes' => ["type" => "integer"],
3039 'hourly-limit' => '150',
3040 '@attributes2' => ["type" => "integer"],
3041 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3042 '@attributes3' => ["type" => "datetime"],
3043 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3044 '@attributes4' => ["type" => "integer"],
3048 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3049 'remaining_hits' => '150',
3050 'hourly_limit' => '150',
3051 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3055 return api_format_data('hash', $type, ['hash' => $hash]);
3058 /// @TODO move to top of file or somewhere better
3059 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3062 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3064 * @param string $type Return type (atom, rss, xml, json)
3066 * @return array|string
3068 function api_help_test($type)
3070 if ($type == 'xml') {
3076 return api_format_data('ok', $type, ["ok" => $ok]);
3079 /// @TODO move to top of file or somewhere better
3080 api_register_func('api/help/test', 'api_help_test', false);
3083 * Returns all lists the user subscribes to.
3085 * @param string $type Return type (atom, rss, xml, json)
3087 * @return array|string
3088 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3090 function api_lists_list($type)
3093 /// @TODO $ret is not filled here?
3094 return api_format_data('lists', $type, ["lists_list" => $ret]);
3097 /// @TODO move to top of file or somewhere better
3098 api_register_func('api/lists/list', 'api_lists_list', true);
3099 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3102 * Returns all groups the user owns.
3104 * @param string $type Return type (atom, rss, xml, json)
3106 * @return array|string
3107 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3109 function api_lists_ownerships($type)
3113 if (api_user() === false) {
3114 throw new ForbiddenException();
3118 $user_info = api_get_user($a);
3119 $uid = $user_info['uid'];
3121 $groups = dba::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3123 // loop through all groups
3125 foreach ($groups as $group) {
3126 if ($group['visible']) {
3132 'name' => $group['name'],
3133 'id' => intval($group['id']),
3134 'id_str' => (string) $group['id'],
3135 'user' => $user_info,
3139 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3142 /// @TODO move to top of file or somewhere better
3143 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3146 * Returns recent statuses from users in the specified group.
3148 * @param string $type Return type (atom, rss, xml, json)
3150 * @return array|string
3151 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3153 function api_lists_statuses($type)
3157 $user_info = api_get_user($a);
3158 if (api_user() === false || $user_info === false) {
3159 throw new ForbiddenException();
3162 unset($_REQUEST["user_id"]);
3163 unset($_GET["user_id"]);
3165 unset($_REQUEST["screen_name"]);
3166 unset($_GET["screen_name"]);
3168 if (empty($_REQUEST['list_id'])) {
3169 throw new BadRequestException('list_id not specified');
3173 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
3174 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
3178 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3179 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3180 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
3181 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
3183 $start = $page * $count;
3185 $condition = ["`uid` = ? AND `verb` = ? AND `id` > ? AND `group_member`.`gid` = ?",
3186 api_user(), ACTIVITY_POST, $since_id, $_REQUEST['list_id']];
3189 $condition[0] .= " AND `item`.`id` <= ?";
3190 $condition[] = $max_id;
3192 if ($exclude_replies > 0) {
3193 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3195 if ($conversation_id > 0) {
3196 $condition[0] .= " AND `item`.`parent` = ?";
3197 $condition[] = $conversation_id;
3200 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3201 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3203 $items = api_format_items(dba::inArray($statuses), $user_info, false, $type);
3205 $data = ['status' => $items];
3209 $data = api_rss_extra($a, $data, $user_info);
3213 return api_format_data("statuses", $type, $data);
3216 /// @TODO move to top of file or somewhere better
3217 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3220 * Considers friends and followers lists to be private and won't return
3221 * anything if any user_id parameter is passed.
3223 * @brief Returns either the friends of the follower list
3225 * @param string $qtype Either "friends" or "followers"
3226 * @return boolean|array
3227 * @throws ForbiddenException
3229 function api_statuses_f($qtype)
3233 if (api_user() === false) {
3234 throw new ForbiddenException();
3238 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3239 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3243 $start = ($page - 1) * $count;
3245 $user_info = api_get_user($a);
3247 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3248 /* this is to stop Hotot to load friends multiple times
3249 * I'm not sure if I'm missing return something or
3250 * is a bug in hotot. Workaround, meantime
3254 return array('$users' => $ret);*/
3259 if ($qtype == 'friends') {
3260 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3261 } elseif ($qtype == 'followers') {
3262 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3265 // friends and followers only for self
3266 if ($user_info['self'] == 0) {
3267 $sql_extra = " AND false ";
3270 if ($qtype == 'blocks') {
3271 $sql_filter = 'AND `blocked` AND NOT `pending`';
3272 } elseif ($qtype == 'incoming') {
3273 $sql_filter = 'AND `pending`';
3275 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3293 foreach ($r as $cid) {
3294 $user = api_get_user($a, $cid['nurl']);
3295 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3296 unset($user["uid"]);
3297 unset($user["self"]);
3304 return ['user' => $ret];
3309 * Returns the user's friends.
3311 * @brief Returns the list of friends of the provided user
3313 * @deprecated By Twitter API in favor of friends/list
3315 * @param string $type Either "json" or "xml"
3316 * @return boolean|string|array
3318 function api_statuses_friends($type)
3320 $data = api_statuses_f("friends");
3321 if ($data === false) {
3324 return api_format_data("users", $type, $data);
3328 * Returns the user's followers.
3330 * @brief Returns the list of followers of the provided user
3332 * @deprecated By Twitter API in favor of friends/list
3334 * @param string $type Either "json" or "xml"
3335 * @return boolean|string|array
3337 function api_statuses_followers($type)
3339 $data = api_statuses_f("followers");
3340 if ($data === false) {
3343 return api_format_data("users", $type, $data);
3346 /// @TODO move to top of file or somewhere better
3347 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3348 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3351 * Returns the list of blocked users
3353 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3355 * @param string $type Either "json" or "xml"
3357 * @return boolean|string|array
3359 function api_blocks_list($type)
3361 $data = api_statuses_f('blocks');
3362 if ($data === false) {
3365 return api_format_data("users", $type, $data);
3368 /// @TODO move to top of file or somewhere better
3369 api_register_func('api/blocks/list', 'api_blocks_list', true);
3372 * Returns the list of pending users IDs
3374 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3376 * @param string $type Either "json" or "xml"
3378 * @return boolean|string|array
3380 function api_friendships_incoming($type)
3382 $data = api_statuses_f('incoming');
3383 if ($data === false) {
3388 foreach ($data['user'] as $user) {
3389 $ids[] = $user['id'];
3392 return api_format_data("ids", $type, ['id' => $ids]);
3395 /// @TODO move to top of file or somewhere better
3396 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3399 * Returns the instance's configuration information.
3401 * @param string $type Return type (atom, rss, xml, json)
3403 * @return array|string
3405 function api_statusnet_config($type)
3409 $name = $a->config['sitename'];
3410 $server = $a->get_hostname();
3411 $logo = System::baseUrl() . '/images/friendica-64.png';
3412 $email = $a->config['admin_email'];
3413 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3414 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3415 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3416 if ($a->config['api_import_size']) {
3417 $textlimit = (string) $a->config['api_import_size'];
3419 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3420 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3423 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3424 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3425 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3426 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3427 'shorturllength' => '30',
3429 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3430 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3431 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3432 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3437 return api_format_data('config', $type, ['config' => $config]);
3440 /// @TODO move to top of file or somewhere better
3441 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3442 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3446 * @param string $type Return type (atom, rss, xml, json)
3448 * @return array|string
3450 function api_statusnet_version($type)
3453 $fake_statusnet_version = "0.9.7";
3455 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3458 /// @TODO move to top of file or somewhere better
3459 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3460 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3464 * @param string $type Return type (atom, rss, xml, json)
3466 * @todo use api_format_data() to return data
3468 function api_ff_ids($type)
3471 throw new ForbiddenException();
3478 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3481 "SELECT `pcontact`.`id` FROM `contact`
3482 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3483 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3486 if (!DBM::is_result($r)) {
3491 foreach ($r as $rr) {
3492 if ($stringify_ids) {
3495 $ids[] = intval($rr['id']);
3499 return api_format_data("ids", $type, ['id' => $ids]);
3503 * Returns the ID of every user the user is following.
3505 * @param string $type Return type (atom, rss, xml, json)
3507 * @return array|string
3508 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3510 function api_friends_ids($type)
3512 return api_ff_ids($type);
3516 * Returns the ID of every user following the user.
3518 * @param string $type Return type (atom, rss, xml, json)
3520 * @return array|string
3521 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3523 function api_followers_ids($type)
3525 return api_ff_ids($type);
3528 /// @TODO move to top of file or somewhere better
3529 api_register_func('api/friends/ids', 'api_friends_ids', true);
3530 api_register_func('api/followers/ids', 'api_followers_ids', true);
3533 * Sends a new direct message.
3535 * @param string $type Return type (atom, rss, xml, json)
3537 * @return array|string
3538 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3540 function api_direct_messages_new($type)
3545 if (api_user() === false) {
3546 throw new ForbiddenException();
3549 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3553 $sender = api_get_user($a);
3555 if ($_POST['screen_name']) {
3557 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3559 dbesc($_POST['screen_name'])
3562 // Selecting the id by priority, friendica first
3563 api_best_nickname($r);
3565 $recipient = api_get_user($a, $r[0]['nurl']);
3567 $recipient = api_get_user($a, $_POST['user_id']);
3572 if (x($_REQUEST, 'replyto')) {
3574 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3576 intval($_REQUEST['replyto'])
3578 $replyto = $r[0]['parent-uri'];
3579 $sub = $r[0]['title'];
3581 if (x($_REQUEST, 'title')) {
3582 $sub = $_REQUEST['title'];
3584 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3588 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3591 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3592 $ret = api_format_messages($r[0], $recipient, $sender);
3594 $ret = ["error"=>$id];
3597 $data = ['direct_message'=>$ret];
3602 $data = api_rss_extra($a, $data, $sender);
3605 return api_format_data("direct-messages", $type, $data);
3608 /// @TODO move to top of file or somewhere better
3609 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3612 * Destroys a direct message.
3614 * @brief delete a direct_message from mail table through api
3616 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3617 * @return string|array
3618 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3620 function api_direct_messages_destroy($type)
3624 if (api_user() === false) {
3625 throw new ForbiddenException();
3629 $user_info = api_get_user($a);
3631 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3633 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3634 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3635 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3637 $uid = $user_info['uid'];
3638 // error if no id or parenturi specified (for clients posting parent-uri as well)
3639 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3640 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3641 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3644 // BadRequestException if no id specified (for clients using Twitter API)
3646 throw new BadRequestException('Message id not specified');
3649 // add parent-uri to sql command if specified by calling app
3650 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3652 // get data of the specified message id
3654 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3659 // error message if specified id is not in database
3660 if (!DBM::is_result($r)) {
3661 if ($verbose == "true") {
3662 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3663 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3665 /// @todo BadRequestException ok for Twitter API clients?
3666 throw new BadRequestException('message id not in database');
3671 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3676 if ($verbose == "true") {
3679 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3680 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3682 $answer = ['result' => 'error', 'message' => 'unknown error'];
3683 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3686 /// @todo return JSON data like Twitter API not yet implemented
3689 /// @TODO move to top of file or somewhere better
3690 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3694 * @param string $type Return type (atom, rss, xml, json)
3695 * @param string $box
3696 * @param string $verbose
3698 * @return array|string
3700 function api_direct_messages_box($type, $box, $verbose)
3703 $user_info = api_get_user($a);
3705 if (api_user() === false || $user_info === false) {
3706 throw new ForbiddenException();
3710 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3711 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3716 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3717 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3719 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3720 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3723 unset($_REQUEST["user_id"]);
3724 unset($_GET["user_id"]);
3726 unset($_REQUEST["screen_name"]);
3727 unset($_GET["screen_name"]);
3729 $profile_url = $user_info["url"];
3732 $start = $page * $count;
3737 if ($box=="sentbox") {
3738 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3739 } elseif ($box == "conversation") {
3740 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3741 } elseif ($box == "all") {
3742 $sql_extra = "true";
3743 } elseif ($box == "inbox") {
3744 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3748 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3751 if ($user_id != "") {
3752 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3753 } elseif ($screen_name !="") {
3754 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3758 "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",
3764 if ($verbose == "true" && !DBM::is_result($r)) {
3765 $answer = ['result' => 'error', 'message' => 'no mails available'];
3766 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3770 foreach ($r as $item) {
3771 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3772 $recipient = $user_info;
3773 $sender = api_get_user($a, normalise_link($item['contact-url']));
3774 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3775 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3776 $sender = $user_info;
3779 if (isset($recipient) && isset($sender)) {
3780 $ret[] = api_format_messages($item, $recipient, $sender);
3785 $data = ['direct_message' => $ret];
3789 $data = api_rss_extra($a, $data, $user_info);
3792 return api_format_data("direct-messages", $type, $data);
3796 * Returns the most recent direct messages sent by the user.
3798 * @param string $type Return type (atom, rss, xml, json)
3800 * @return array|string
3801 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3803 function api_direct_messages_sentbox($type)
3805 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3806 return api_direct_messages_box($type, "sentbox", $verbose);
3810 * Returns the most recent direct messages sent to the user.
3812 * @param string $type Return type (atom, rss, xml, json)
3814 * @return array|string
3815 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3817 function api_direct_messages_inbox($type)
3819 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3820 return api_direct_messages_box($type, "inbox", $verbose);
3825 * @param string $type Return type (atom, rss, xml, json)
3827 * @return array|string
3829 function api_direct_messages_all($type)
3831 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3832 return api_direct_messages_box($type, "all", $verbose);
3837 * @param string $type Return type (atom, rss, xml, json)
3839 * @return array|string
3841 function api_direct_messages_conversation($type)
3843 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3844 return api_direct_messages_box($type, "conversation", $verbose);
3847 /// @TODO move to top of file or somewhere better
3848 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3849 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3850 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3851 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3854 * Returns an OAuth Request Token.
3856 * @see https://oauth.net/core/1.0/#auth_step1
3858 function api_oauth_request_token()
3860 $oauth1 = new FKOAuth1();
3862 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3863 } catch (Exception $e) {
3864 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3872 * Returns an OAuth Access Token.
3874 * @return array|string
3875 * @see https://oauth.net/core/1.0/#auth_step3
3877 function api_oauth_access_token()
3879 $oauth1 = new FKOAuth1();
3881 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3882 } catch (Exception $e) {
3883 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3890 /// @TODO move to top of file or somewhere better
3891 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3892 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3896 * @brief delete a complete photoalbum with all containing photos from database through api
3898 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3899 * @return string|array
3901 function api_fr_photoalbum_delete($type)
3903 if (api_user() === false) {
3904 throw new ForbiddenException();
3907 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3909 // we do not allow calls without album string
3911 throw new BadRequestException("no albumname specified");
3913 // check if album is existing
3915 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3919 if (!DBM::is_result($r)) {
3920 throw new BadRequestException("album not available");
3923 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3924 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3925 foreach ($r as $rr) {
3927 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3928 intval(local_user()),
3929 dbesc($rr['resource-id'])
3932 if (!DBM::is_result($photo_item)) {
3933 throw new InternalServerErrorException("problem with deleting items occured");
3935 Item::deleteForUser(['id' => $photo_item[0]['id']], api_user());
3938 // now let's delete all photos from the album
3939 $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
3941 // return success of deletion or error message
3943 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
3944 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
3946 throw new InternalServerErrorException("unknown error - deleting from database failed");
3951 * @brief update the name of the album for all photos of an album
3953 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3954 * @return string|array
3956 function api_fr_photoalbum_update($type)
3958 if (api_user() === false) {
3959 throw new ForbiddenException();
3962 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3963 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3965 // we do not allow calls without album string
3967 throw new BadRequestException("no albumname specified");
3969 if ($album_new == "") {
3970 throw new BadRequestException("no new albumname specified");
3972 // check if album is existing
3973 if (!dba::exists('photo', ['uid' => api_user(), 'album' => $album])) {
3974 throw new BadRequestException("album not available");
3976 // now let's update all photos to the albumname
3977 $result = dba::update('photo', ['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
3979 // return success of updating or error message
3981 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
3982 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
3984 throw new InternalServerErrorException("unknown error - updating in database failed");
3990 * @brief list all photos of the authenticated user
3992 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3993 * @return string|array
3995 function api_fr_photos_list($type)
3997 if (api_user() === false) {
3998 throw new ForbiddenException();
4001 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4002 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4003 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4004 intval(local_user())
4007 'image/jpeg' => 'jpg',
4008 'image/png' => 'png',
4009 'image/gif' => 'gif'
4011 $data = ['photo'=>[]];
4012 if (DBM::is_result($r)) {
4013 foreach ($r as $rr) {
4015 $photo['id'] = $rr['resource-id'];
4016 $photo['album'] = $rr['album'];
4017 $photo['filename'] = $rr['filename'];
4018 $photo['type'] = $rr['type'];
4019 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4020 $photo['created'] = $rr['created'];
4021 $photo['edited'] = $rr['edited'];
4022 $photo['desc'] = $rr['desc'];
4024 if ($type == "xml") {
4025 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4027 $photo['thumb'] = $thumb;
4028 $data['photo'][] = $photo;
4032 return api_format_data("photos", $type, $data);
4036 * @brief upload a new photo or change an existing photo
4038 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4039 * @return string|array
4041 function api_fr_photo_create_update($type)
4043 if (api_user() === false) {
4044 throw new ForbiddenException();
4047 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4048 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4049 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4050 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4051 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4052 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4053 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4054 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4055 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4057 // do several checks on input parameters
4058 // we do not allow calls without album string
4059 if ($album == null) {
4060 throw new BadRequestException("no albumname specified");
4062 // if photo_id == null --> we are uploading a new photo
4063 if ($photo_id == null) {
4066 // error if no media posted in create-mode
4067 if (!x($_FILES, 'media')) {
4069 throw new BadRequestException("no media data submitted");
4072 // album_new will be ignored in create-mode
4077 // check if photo is existing in database
4079 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4084 if (!DBM::is_result($r)) {
4085 throw new BadRequestException("photo not available");
4089 // checks on acl strings provided by clients
4090 $acl_input_error = false;
4091 $acl_input_error |= check_acl_input($allow_cid);
4092 $acl_input_error |= check_acl_input($deny_cid);
4093 $acl_input_error |= check_acl_input($allow_gid);
4094 $acl_input_error |= check_acl_input($deny_gid);
4095 if ($acl_input_error) {
4096 throw new BadRequestException("acl data invalid");
4098 // now let's upload the new media in create-mode
4099 if ($mode == "create") {
4100 $media = $_FILES['media'];
4101 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4103 // return success of updating or error message
4104 if (!is_null($data)) {
4105 return api_format_data("photo_create", $type, $data);
4107 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4111 // now let's do the changes in update-mode
4112 if ($mode == "update") {
4115 if (!is_null($desc)) {
4116 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4119 if (!is_null($album_new)) {
4120 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4123 if (!is_null($allow_cid)) {
4124 $allow_cid = trim($allow_cid);
4125 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4128 if (!is_null($deny_cid)) {
4129 $deny_cid = trim($deny_cid);
4130 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4133 if (!is_null($allow_gid)) {
4134 $allow_gid = trim($allow_gid);
4135 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4138 if (!is_null($deny_gid)) {
4139 $deny_gid = trim($deny_gid);
4140 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4144 if ($sql_extra != "") {
4145 $nothingtodo = false;
4147 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4149 DateTimeFormat::utcNow(), // update edited timestamp
4155 $nothingtodo = true;
4158 if (x($_FILES, 'media')) {
4159 $nothingtodo = false;
4160 $media = $_FILES['media'];
4161 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4162 if (!is_null($data)) {
4163 return api_format_data("photo_update", $type, $data);
4167 // return success of updating or error message
4169 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4170 return api_format_data("photo_update", $type, ['$result' => $answer]);
4173 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4174 return api_format_data("photo_update", $type, ['$result' => $answer]);
4176 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4179 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4183 * @brief delete a single photo from the database through api
4185 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4186 * @return string|array
4188 function api_fr_photo_delete($type)
4190 if (api_user() === false) {
4191 throw new ForbiddenException();
4194 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4196 // do several checks on input parameters
4197 // we do not allow calls without photo id
4198 if ($photo_id == null) {
4199 throw new BadRequestException("no photo_id specified");
4201 // check if photo is existing in database
4203 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4207 if (!DBM::is_result($r)) {
4208 throw new BadRequestException("photo not available");
4210 // now we can perform on the deletion of the photo
4211 $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4213 // return success of deletion or error message
4215 // retrieve the id of the parent element (the photo element)
4217 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4218 intval(local_user()),
4222 if (!DBM::is_result($photo_item)) {
4223 throw new InternalServerErrorException("problem with deleting items occured");
4225 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4226 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4227 Item::deleteForUser(['id' => $photo_item[0]['id']], api_user());
4229 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4230 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4232 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4238 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4240 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4241 * @return string|array
4243 function api_fr_photo_detail($type)
4245 if (api_user() === false) {
4246 throw new ForbiddenException();
4248 if (!x($_REQUEST, 'photo_id')) {
4249 throw new BadRequestException("No photo id.");
4252 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4253 $photo_id = $_REQUEST['photo_id'];
4255 // prepare json/xml output with data from database for the requested photo
4256 $data = prepare_photo_data($type, $scale, $photo_id);
4258 return api_format_data("photo_detail", $type, $data);
4263 * Updates the user’s profile image.
4265 * @brief updates the profile image for the user (either a specified profile or the default profile)
4267 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4269 * @return string|array
4270 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4272 function api_account_update_profile_image($type)
4274 if (api_user() === false) {
4275 throw new ForbiddenException();
4278 $profile_id = defaults($_REQUEST, 'profile_id', 0);
4280 // error if image data is missing
4281 if (!x($_FILES, 'image')) {
4282 throw new BadRequestException("no media data submitted");
4285 // check if specified profile id is valid
4286 if ($profile_id != 0) {
4287 $profile = dba::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4288 // error message if specified profile id is not in database
4289 if (!DBM::is_result($profile)) {
4290 throw new BadRequestException("profile_id not available");
4292 $is_default_profile = $profile['is-default'];
4294 $is_default_profile = 1;
4297 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4299 if (x($_FILES, 'image')) {
4300 $media = $_FILES['image'];
4301 } elseif (x($_FILES, 'media')) {
4302 $media = $_FILES['media'];
4304 // save new profile image
4305 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4308 if (is_array($media['type'])) {
4309 $filetype = $media['type'][0];
4311 $filetype = $media['type'];
4313 if ($filetype == "image/jpeg") {
4315 } elseif ($filetype == "image/png") {
4318 throw new InternalServerErrorException('Unsupported filetype');
4321 // change specified profile or all profiles to the new resource-id
4322 if ($is_default_profile) {
4323 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4324 dba::update('photo', ['profile' => false], $condition);
4326 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype,
4327 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype];
4328 dba::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4331 Contact::updateSelfFromUserID(api_user(), true);
4333 // Update global directory in background
4334 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4335 if ($url && strlen(Config::get('system', 'directory'))) {
4336 Worker::add(PRIORITY_LOW, "Directory", $url);
4339 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4341 // output for client
4343 return api_account_verify_credentials($type);
4345 // SaveMediaToDatabase failed for some reason
4346 throw new InternalServerErrorException("image upload failed");
4350 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4351 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4352 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4353 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4354 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4355 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4356 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4357 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4358 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4361 * Update user profile
4363 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4365 * @return array|string
4367 function api_account_update_profile($type)
4369 $local_user = api_user();
4370 $api_user = api_get_user(get_app());
4372 if (!empty($_POST['name'])) {
4373 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4374 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4375 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4376 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4379 if (isset($_POST['description'])) {
4380 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4381 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4382 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4385 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4386 // Update global directory in background
4387 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4388 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4391 return api_account_verify_credentials($type);
4394 /// @TODO move to top of file or somewhere better
4395 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4399 * @param string $acl_string
4401 function check_acl_input($acl_string)
4403 if ($acl_string == null || $acl_string == " ") {
4406 $contact_not_found = false;
4408 // split <x><y><z> into array of cid's
4409 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4411 // check for each cid if it is available on server
4412 $cid_array = $array[0];
4413 foreach ($cid_array as $cid) {
4414 $cid = str_replace("<", "", $cid);
4415 $cid = str_replace(">", "", $cid);
4417 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4421 $contact_not_found |= !DBM::is_result($contact);
4423 return $contact_not_found;
4428 * @param string $mediatype
4429 * @param array $media
4430 * @param string $type
4431 * @param string $album
4432 * @param string $allow_cid
4433 * @param string $deny_cid
4434 * @param string $allow_gid
4435 * @param string $deny_gid
4436 * @param string $desc
4437 * @param integer $profile
4438 * @param boolean $visibility
4439 * @param string $photo_id
4441 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)
4449 if (is_array($media)) {
4450 if (is_array($media['tmp_name'])) {
4451 $src = $media['tmp_name'][0];
4453 $src = $media['tmp_name'];
4455 if (is_array($media['name'])) {
4456 $filename = basename($media['name'][0]);
4458 $filename = basename($media['name']);
4460 if (is_array($media['size'])) {
4461 $filesize = intval($media['size'][0]);
4463 $filesize = intval($media['size']);
4465 if (is_array($media['type'])) {
4466 $filetype = $media['type'][0];
4468 $filetype = $media['type'];
4472 if ($filetype == "") {
4473 $filetype=Image::guessType($filename);
4475 $imagedata = getimagesize($src);
4477 $filetype = $imagedata['mime'];
4480 "File upload src: " . $src . " - filename: " . $filename .
4481 " - size: " . $filesize . " - type: " . $filetype,
4485 // check if there was a php upload error
4486 if ($filesize == 0 && $media['error'] == 1) {
4487 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4489 // check against max upload size within Friendica instance
4490 $maximagesize = Config::get('system', 'maximagesize');
4491 if ($maximagesize && ($filesize > $maximagesize)) {
4492 $formattedBytes = formatBytes($maximagesize);
4493 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4496 // create Photo instance with the data of the image
4497 $imagedata = @file_get_contents($src);
4498 $Image = new Image($imagedata, $filetype);
4499 if (! $Image->isValid()) {
4500 throw new InternalServerErrorException("unable to process image data");
4503 // check orientation of image
4504 $Image->orient($src);
4507 // check max length of images on server
4508 $max_length = Config::get('system', 'max_image_length');
4509 if (! $max_length) {
4510 $max_length = MAX_IMAGE_LENGTH;
4512 if ($max_length > 0) {
4513 $Image->scaleDown($max_length);
4514 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4516 $width = $Image->getWidth();
4517 $height = $Image->getHeight();
4519 // create a new resource-id if not already provided
4520 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4522 if ($mediatype == "photo") {
4523 // upload normal image (scales 0, 1, 2)
4524 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4526 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4528 logger("photo upload: image upload with scale 0 (original size) failed");
4530 if ($width > 640 || $height > 640) {
4531 $Image->scaleDown(640);
4532 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4534 logger("photo upload: image upload with scale 1 (640x640) failed");
4538 if ($width > 320 || $height > 320) {
4539 $Image->scaleDown(320);
4540 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4542 logger("photo upload: image upload with scale 2 (320x320) failed");
4545 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4546 } elseif ($mediatype == "profileimage") {
4547 // upload profile image (scales 4, 5, 6)
4548 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4550 if ($width > 175 || $height > 175) {
4551 $Image->scaleDown(175);
4552 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4554 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4558 if ($width > 80 || $height > 80) {
4559 $Image->scaleDown(80);
4560 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4562 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4566 if ($width > 48 || $height > 48) {
4567 $Image->scaleDown(48);
4568 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4570 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4573 $Image->__destruct();
4574 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4577 if (isset($r) && $r) {
4578 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4579 if ($photo_id == null && $mediatype == "photo") {
4580 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4582 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4583 return prepare_photo_data($type, false, $hash);
4585 throw new InternalServerErrorException("image upload failed");
4591 * @param string $hash
4592 * @param string $allow_cid
4593 * @param string $deny_cid
4594 * @param string $allow_gid
4595 * @param string $deny_gid
4596 * @param string $filetype
4597 * @param boolean $visibility
4599 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4601 // get data about the api authenticated user
4602 $uri = Item::newURI(intval(api_user()));
4603 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4606 $arr['guid'] = get_guid(32);
4607 $arr['uid'] = intval(api_user());
4609 $arr['parent-uri'] = $uri;
4610 $arr['type'] = 'photo';
4612 $arr['resource-id'] = $hash;
4613 $arr['contact-id'] = $owner_record[0]['id'];
4614 $arr['owner-name'] = $owner_record[0]['name'];
4615 $arr['owner-link'] = $owner_record[0]['url'];
4616 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4617 $arr['author-name'] = $owner_record[0]['name'];
4618 $arr['author-link'] = $owner_record[0]['url'];
4619 $arr['author-avatar'] = $owner_record[0]['thumb'];
4621 $arr['allow_cid'] = $allow_cid;
4622 $arr['allow_gid'] = $allow_gid;
4623 $arr['deny_cid'] = $deny_cid;
4624 $arr['deny_gid'] = $deny_gid;
4625 $arr['visible'] = $visibility;
4629 'image/jpeg' => 'jpg',
4630 'image/png' => 'png',
4631 'image/gif' => 'gif'
4634 // adds link to the thumbnail scale photo
4635 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4636 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4639 // do the magic for storing the item in the database and trigger the federation to other contacts
4645 * @param string $type
4647 * @param string $photo_id
4651 function prepare_photo_data($type, $scale, $photo_id)
4654 $user_info = api_get_user($a);
4656 if ($user_info === false) {
4657 throw new ForbiddenException();
4660 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4661 $data_sql = ($scale === false ? "" : "data, ");
4663 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4664 // clients needs to convert this in their way for further processing
4666 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4667 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4668 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4669 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4671 intval(local_user()),
4677 'image/jpeg' => 'jpg',
4678 'image/png' => 'png',
4679 'image/gif' => 'gif'
4682 // prepare output data for photo
4683 if (DBM::is_result($r)) {
4684 $data = ['photo' => $r[0]];
4685 $data['photo']['id'] = $data['photo']['resource-id'];
4686 if ($scale !== false) {
4687 $data['photo']['data'] = base64_encode($data['photo']['data']);
4689 unset($data['photo']['datasize']); //needed only with scale param
4691 if ($type == "xml") {
4692 $data['photo']['links'] = [];
4693 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4694 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4696 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4699 $data['photo']['link'] = [];
4700 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4702 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4703 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4707 unset($data['photo']['resource-id']);
4708 unset($data['photo']['minscale']);
4709 unset($data['photo']['maxscale']);
4711 throw new NotFoundException();
4714 // retrieve item element for getting activities (like, dislike etc.) related to photo
4716 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4717 intval(local_user()),
4720 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4722 // retrieve comments on photo
4723 $condition = ["`parent` = ? AND `uid` = ? AND (`verb` = ? OR `type`='photo')",
4724 $item[0]['parent'], api_user(), ACTIVITY_POST];
4726 $statuses = Item::selectForUser(api_user(), [], $condition);
4728 // prepare output of comments
4729 $commentData = api_format_items(dba::inArray($statuses), $user_info, false, $type);
4731 if ($type == "xml") {
4733 foreach ($commentData as $comment) {
4734 $comments[$k++ . ":comment"] = $comment;
4737 foreach ($commentData as $comment) {
4738 $comments[] = $comment;
4741 $data['photo']['friendica_comments'] = $comments;
4743 // include info if rights on photo and rights on item are mismatching
4744 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4745 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4746 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4747 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4748 $data['photo']['rights_mismatch'] = $rights_mismatch;
4755 * Similar as /mod/redir.php
4756 * redirect to 'url' after dfrn auth
4758 * Why this when there is mod/redir.php already?
4759 * This use api_user() and api_login()
4762 * c_url: url of remote contact to auth to
4763 * url: string, url to redirect after auth
4765 function api_friendica_remoteauth()
4767 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4768 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4770 if ($url === '' || $c_url === '') {
4771 throw new BadRequestException("Wrong parameters.");
4774 $c_url = normalise_link($c_url);
4778 $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4780 if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
4781 throw new BadRequestException("Unknown contact");
4784 $cid = $contact['id'];
4786 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4788 if ($contact['duplex'] && $contact['issued-id']) {
4789 $orig_id = $contact['issued-id'];
4790 $dfrn_id = '1:' . $orig_id;
4792 if ($contact['duplex'] && $contact['dfrn-id']) {
4793 $orig_id = $contact['dfrn-id'];
4794 $dfrn_id = '0:' . $orig_id;
4797 $sec = random_string();
4799 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4800 'sec' => $sec, 'expire' => time() + 45];
4801 dba::insert('profile_check', $fields);
4803 logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
4804 $dest = ($url ? '&destination_url=' . $url : '');
4806 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4807 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4808 . '&type=profile&sec=' . $sec . $dest
4811 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4814 * @brief Return the item shared, if the item contains only the [share] tag
4816 * @param array $item Sharer item
4817 * @return array|false Shared item or false if not a reshare
4819 function api_share_as_retweet(&$item)
4821 $body = trim($item["body"]);
4823 if (Diaspora::isReshare($body, false)===false) {
4827 /// @TODO "$1" should maybe mean '$1' ?
4828 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4830 * Skip if there is no shared message in there
4831 * we already checked this in diaspora::isReshare()
4832 * but better one more than one less...
4834 if ($body == $attributes) {
4839 // build the fake reshared item
4840 $reshared_item = $item;
4843 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4844 if ($matches[1] != "") {
4845 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4848 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4849 if ($matches[1] != "") {
4850 $author = $matches[1];
4854 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4855 if ($matches[1] != "") {
4856 $profile = $matches[1];
4859 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4860 if ($matches[1] != "") {
4861 $profile = $matches[1];
4865 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4866 if ($matches[1] != "") {
4867 $avatar = $matches[1];
4870 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4871 if ($matches[1] != "") {
4872 $avatar = $matches[1];
4876 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4877 if ($matches[1] != "") {
4878 $link = $matches[1];
4881 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4882 if ($matches[1] != "") {
4883 $link = $matches[1];
4887 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4888 if ($matches[1] != "") {
4889 $posted = $matches[1];
4892 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4893 if ($matches[1] != "") {
4894 $posted = $matches[1];
4897 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4899 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4903 $reshared_item["body"] = $shared_body;
4904 $reshared_item["author-name"] = $author;
4905 $reshared_item["author-link"] = $profile;
4906 $reshared_item["author-avatar"] = $avatar;
4907 $reshared_item["plink"] = $link;
4908 $reshared_item["created"] = $posted;
4909 $reshared_item["edited"] = $posted;
4911 return $reshared_item;
4916 * @param string $profile
4918 * @return string|false
4919 * @todo remove trailing junk from profile url
4920 * @todo pump.io check has to check the website
4922 function api_get_nick($profile)
4927 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4928 dbesc(normalise_link($profile))
4931 if (DBM::is_result($r)) {
4932 $nick = $r[0]["nick"];
4937 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4938 dbesc(normalise_link($profile))
4941 if (DBM::is_result($r)) {
4942 $nick = $r[0]["nick"];
4947 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4948 if ($friendica != $profile) {
4954 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4955 if ($diaspora != $profile) {
4961 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4962 if ($twitter != $profile) {
4969 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4970 if ($StatusnetHost != $profile) {
4971 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4972 if ($StatusnetUser != $profile) {
4973 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4974 $user = json_decode($UserData);
4976 $nick = $user->screen_name;
4982 // To-Do: look at the page if its really a pumpio site
4983 //if (!$nick == "") {
4984 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4985 // if ($pumpio != $profile)
4987 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5000 * @param array $item
5004 function api_in_reply_to($item)
5008 $in_reply_to['status_id'] = null;
5009 $in_reply_to['user_id'] = null;
5010 $in_reply_to['status_id_str'] = null;
5011 $in_reply_to['user_id_str'] = null;
5012 $in_reply_to['screen_name'] = null;
5014 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5016 "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
5017 intval($item['uid']),
5018 dbesc($item['thr-parent'])
5021 if (DBM::is_result($r)) {
5022 $in_reply_to['status_id'] = intval($r[0]['id']);
5024 $in_reply_to['status_id'] = intval($item['parent']);
5027 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5030 "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM `item`
5031 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
5032 WHERE `item`.`id` = %d LIMIT 1",
5033 intval($in_reply_to['status_id'])
5036 if (DBM::is_result($r)) {
5037 if ($r[0]['nick'] == "") {
5038 $r[0]['nick'] = api_get_nick($r[0]["url"]);
5041 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
5042 $in_reply_to['user_id'] = intval($r[0]['id']);
5043 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
5046 // There seems to be situation, where both fields are identical:
5047 // https://github.com/friendica/friendica/issues/1010
5048 // This is a bugfix for that.
5049 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5050 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
5051 $in_reply_to['status_id'] = null;
5052 $in_reply_to['user_id'] = null;
5053 $in_reply_to['status_id_str'] = null;
5054 $in_reply_to['user_id_str'] = null;
5055 $in_reply_to['screen_name'] = null;
5059 return $in_reply_to;
5064 * @param string $text
5068 function api_clean_plain_items($text)
5070 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5072 $text = BBCode::cleanPictureLinks($text);
5073 $URLSearchString = "^\[\]";
5075 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5077 if ($include_entities == "true") {
5078 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5081 // Simplify "attachment" element
5082 $text = api_clean_attachments($text);
5088 * @brief Removes most sharing information for API text export
5090 * @param string $body The original body
5092 * @return string Cleaned body
5094 function api_clean_attachments($body)
5096 $data = BBCode::getAttachmentData($body);
5103 if (isset($data["text"])) {
5104 $body = $data["text"];
5106 if (($body == "") && isset($data["title"])) {
5107 $body = $data["title"];
5109 if (isset($data["url"])) {
5110 $body .= "\n".$data["url"];
5112 $body .= $data["after"];
5119 * @param array $contacts
5123 function api_best_nickname(&$contacts)
5127 if (count($contacts) == 0) {
5131 foreach ($contacts as $contact) {
5132 if ($contact["network"] == "") {
5133 $contact["network"] = "dfrn";
5134 $best_contact = [$contact];
5138 if (sizeof($best_contact) == 0) {
5139 foreach ($contacts as $contact) {
5140 if ($contact["network"] == "dfrn") {
5141 $best_contact = [$contact];
5146 if (sizeof($best_contact) == 0) {
5147 foreach ($contacts as $contact) {
5148 if ($contact["network"] == "dspr") {
5149 $best_contact = [$contact];
5154 if (sizeof($best_contact) == 0) {
5155 foreach ($contacts as $contact) {
5156 if ($contact["network"] == "stat") {
5157 $best_contact = [$contact];
5162 if (sizeof($best_contact) == 0) {
5163 foreach ($contacts as $contact) {
5164 if ($contact["network"] == "pump") {
5165 $best_contact = [$contact];
5170 if (sizeof($best_contact) == 0) {
5171 foreach ($contacts as $contact) {
5172 if ($contact["network"] == "twit") {
5173 $best_contact = [$contact];
5178 if (sizeof($best_contact) == 1) {
5179 $contacts = $best_contact;
5181 $contacts = [$contacts[0]];
5186 * Return all or a specified group of the user with the containing contacts.
5188 * @param string $type Return type (atom, rss, xml, json)
5190 * @return array|string
5192 function api_friendica_group_show($type)
5196 if (api_user() === false) {
5197 throw new ForbiddenException();
5201 $user_info = api_get_user($a);
5202 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5203 $uid = $user_info['uid'];
5205 // get data of the specified group id or all groups if not specified
5208 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5212 // error message if specified gid is not in database
5213 if (!DBM::is_result($r)) {
5214 throw new BadRequestException("gid not available");
5218 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5223 // loop through all groups and retrieve all members for adding data in the user array
5225 foreach ($r as $rr) {
5226 $members = Contact::getByGroupId($rr['id']);
5229 if ($type == "xml") {
5230 $user_element = "users";
5232 foreach ($members as $member) {
5233 $user = api_get_user($a, $member['nurl']);
5234 $users[$k++.":user"] = $user;
5237 $user_element = "user";
5238 foreach ($members as $member) {
5239 $user = api_get_user($a, $member['nurl']);
5243 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5245 return api_format_data("groups", $type, ['group' => $grps]);
5247 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5251 * Delete the specified group of the user.
5253 * @param string $type Return type (atom, rss, xml, json)
5255 * @return array|string
5257 function api_friendica_group_delete($type)
5261 if (api_user() === false) {
5262 throw new ForbiddenException();
5266 $user_info = api_get_user($a);
5267 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5268 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5269 $uid = $user_info['uid'];
5271 // error if no gid specified
5272 if ($gid == 0 || $name == "") {
5273 throw new BadRequestException('gid or name not specified');
5276 // get data of the specified group id
5278 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5282 // error message if specified gid is not in database
5283 if (!DBM::is_result($r)) {
5284 throw new BadRequestException('gid not available');
5287 // get data of the specified group id and group name
5289 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5294 // error message if specified gid is not in database
5295 if (!DBM::is_result($rname)) {
5296 throw new BadRequestException('wrong group name');
5300 $ret = Group::removeByName($uid, $name);
5303 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5304 return api_format_data("group_delete", $type, ['result' => $success]);
5306 throw new BadRequestException('other API error');
5309 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5314 * @param string $type Return type (atom, rss, xml, json)
5316 * @return array|string
5317 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5319 function api_lists_destroy($type)
5323 if (api_user() === false) {
5324 throw new ForbiddenException();
5328 $user_info = api_get_user($a);
5329 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5330 $uid = $user_info['uid'];
5332 // error if no gid specified
5334 throw new BadRequestException('gid not specified');
5337 // get data of the specified group id
5338 $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5339 // error message if specified gid is not in database
5341 throw new BadRequestException('gid not available');
5344 if (Group::remove($gid)) {
5346 'name' => $group['name'],
5347 'id' => intval($gid),
5348 'id_str' => (string) $gid,
5349 'user' => $user_info
5352 return api_format_data("lists", $type, ['lists' => $list]);
5355 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5358 * Add a new group to the database.
5360 * @param string $name Group name
5361 * @param int $uid User ID
5362 * @param array $users List of users to add to the group
5366 function group_create($name, $uid, $users = [])
5368 // error if no name specified
5370 throw new BadRequestException('group name not specified');
5373 // get data of the specified group name
5375 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5379 // error message if specified group name already exists
5380 if (DBM::is_result($rname)) {
5381 throw new BadRequestException('group name already exists');
5384 // check if specified group name is a deleted group
5386 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5390 // error message if specified group name already exists
5391 if (DBM::is_result($rname)) {
5392 $reactivate_group = true;
5396 $ret = Group::create($uid, $name);
5398 $gid = Group::getIdByName($uid, $name);
5400 throw new BadRequestException('other API error');
5404 $erroraddinguser = false;
5406 foreach ($users as $user) {
5407 $cid = $user['cid'];
5408 // check if user really exists as contact
5410 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5414 if (count($contact)) {
5415 Group::addMember($gid, $cid);
5417 $erroraddinguser = true;
5418 $errorusers[] = $cid;
5422 // return success message incl. missing users in array
5423 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5425 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5429 * Create the specified group with the posted array of contacts.
5431 * @param string $type Return type (atom, rss, xml, json)
5433 * @return array|string
5435 function api_friendica_group_create($type)
5439 if (api_user() === false) {
5440 throw new ForbiddenException();
5444 $user_info = api_get_user($a);
5445 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5446 $uid = $user_info['uid'];
5447 $json = json_decode($_POST['json'], true);
5448 $users = $json['user'];
5450 $success = group_create($name, $uid, $users);
5452 return api_format_data("group_create", $type, ['result' => $success]);
5454 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5457 * Create a new group.
5459 * @param string $type Return type (atom, rss, xml, json)
5461 * @return array|string
5462 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5464 function api_lists_create($type)
5468 if (api_user() === false) {
5469 throw new ForbiddenException();
5473 $user_info = api_get_user($a);
5474 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5475 $uid = $user_info['uid'];
5477 $success = group_create($name, $uid);
5478 if ($success['success']) {
5480 'name' => $success['name'],
5481 'id' => intval($success['gid']),
5482 'id_str' => (string) $success['gid'],
5483 'user' => $user_info
5486 return api_format_data("lists", $type, ['lists'=>$grp]);
5489 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5492 * Update the specified group with the posted array of contacts.
5494 * @param string $type Return type (atom, rss, xml, json)
5496 * @return array|string
5498 function api_friendica_group_update($type)
5502 if (api_user() === false) {
5503 throw new ForbiddenException();
5507 $user_info = api_get_user($a);
5508 $uid = $user_info['uid'];
5509 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5510 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5511 $json = json_decode($_POST['json'], true);
5512 $users = $json['user'];
5514 // error if no name specified
5516 throw new BadRequestException('group name not specified');
5519 // error if no gid specified
5521 throw new BadRequestException('gid not specified');
5525 $members = Contact::getByGroupId($gid);
5526 foreach ($members as $member) {
5527 $cid = $member['id'];
5528 foreach ($users as $user) {
5529 $found = ($user['cid'] == $cid ? true : false);
5531 if (!isset($found) || !$found) {
5532 Group::removeMemberByName($uid, $name, $cid);
5537 $erroraddinguser = false;
5539 foreach ($users as $user) {
5540 $cid = $user['cid'];
5541 // check if user really exists as contact
5543 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5548 if (count($contact)) {
5549 Group::addMember($gid, $cid);
5551 $erroraddinguser = true;
5552 $errorusers[] = $cid;
5556 // return success message incl. missing users in array
5557 $status = ($erroraddinguser ? "missing user" : "ok");
5558 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5559 return api_format_data("group_update", $type, ['result' => $success]);
5562 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5565 * Update information about a group.
5567 * @param string $type Return type (atom, rss, xml, json)
5569 * @return array|string
5570 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5572 function api_lists_update($type)
5576 if (api_user() === false) {
5577 throw new ForbiddenException();
5581 $user_info = api_get_user($a);
5582 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5583 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5584 $uid = $user_info['uid'];
5586 // error if no gid specified
5588 throw new BadRequestException('gid not specified');
5591 // get data of the specified group id
5592 $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5593 // error message if specified gid is not in database
5595 throw new BadRequestException('gid not available');
5598 if (Group::update($gid, $name)) {
5601 'id' => intval($gid),
5602 'id_str' => (string) $gid,
5603 'user' => $user_info
5606 return api_format_data("lists", $type, ['lists' => $list]);
5610 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5614 * @param string $type Return type (atom, rss, xml, json)
5616 * @return array|string
5618 function api_friendica_activity($type)
5622 if (api_user() === false) {
5623 throw new ForbiddenException();
5625 $verb = strtolower($a->argv[3]);
5626 $verb = preg_replace("|\..*$|", "", $verb);
5628 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5630 $res = Item::performLike($id, $verb);
5633 if ($type == "xml") {
5638 return api_format_data('ok', $type, ['ok' => $ok]);
5640 throw new BadRequestException('Error adding activity');
5644 /// @TODO move to top of file or somewhere better
5645 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5646 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5647 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5648 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5649 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5650 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5651 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5652 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5653 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5654 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5657 * @brief Returns notifications
5659 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5660 * @return string|array
5662 function api_friendica_notification($type)
5666 if (api_user() === false) {
5667 throw new ForbiddenException();
5670 throw new BadRequestException("Invalid argument count");
5672 $nm = new NotificationsManager();
5674 $notes = $nm->getAll([], "+seen -date", 50);
5676 if ($type == "xml") {
5678 foreach ($notes as $note) {
5679 $xmlnotes[] = ["@attributes" => $note];
5685 return api_format_data("notes", $type, ['note' => $notes]);
5689 * POST request with 'id' param as notification id
5691 * @brief Set notification as seen and returns associated item (if possible)
5693 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5694 * @return string|array
5696 function api_friendica_notification_seen($type)
5699 $user_info = api_get_user($a);
5701 if (api_user() === false || $user_info === false) {
5702 throw new ForbiddenException();
5705 throw new BadRequestException("Invalid argument count");
5708 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5710 $nm = new NotificationsManager();
5711 $note = $nm->getByID($id);
5712 if (is_null($note)) {
5713 throw new BadRequestException("Invalid argument");
5716 $nm->setSeen($note);
5717 if ($note['otype']=='item') {
5718 // would be really better with an ItemsManager and $im->getByID() :-P
5719 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5720 if (DBM::is_result($$item)) {
5721 // we found the item, return it to the user
5722 $ret = api_format_items([$item], $user_info, false, $type);
5723 $data = ['status' => $ret];
5724 return api_format_data("status", $type, $data);
5726 // the item can't be found, but we set the note as seen, so we count this as a success
5728 return api_format_data('result', $type, ['result' => "success"]);
5731 /// @TODO move to top of file or somewhere better
5732 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5733 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5736 * @brief update a direct_message to seen state
5738 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5739 * @return string|array (success result=ok, error result=error with error message)
5741 function api_friendica_direct_messages_setseen($type)
5744 if (api_user() === false) {
5745 throw new ForbiddenException();
5749 $user_info = api_get_user($a);
5750 $uid = $user_info['uid'];
5751 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5753 // return error if id is zero
5755 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5756 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5759 // error message if specified id is not in database
5760 if (!dba::exists('mail', ['id' => $id, 'uid' => $uid])) {
5761 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5762 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5765 // update seen indicator
5766 $result = dba::update('mail', ['seen' => true], ['id' => $id]);
5770 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5771 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5773 $answer = ['result' => 'error', 'message' => 'unknown error'];
5774 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5778 /// @TODO move to top of file or somewhere better
5779 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5782 * @brief search for direct_messages containing a searchstring through api
5784 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5785 * @param string $box
5786 * @return string|array (success: success=true if found and search_result contains found messages,
5787 * success=false if nothing was found, search_result='nothing found',
5788 * error: result=error with error message)
5790 function api_friendica_direct_messages_search($type, $box = "")
5794 if (api_user() === false) {
5795 throw new ForbiddenException();
5799 $user_info = api_get_user($a);
5800 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5801 $uid = $user_info['uid'];
5803 // error if no searchstring specified
5804 if ($searchstring == "") {
5805 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5806 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5809 // get data for the specified searchstring
5811 "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",
5813 dbesc('%'.$searchstring.'%')
5816 $profile_url = $user_info["url"];
5818 // message if nothing was found
5819 if (!DBM::is_result($r)) {
5820 $success = ['success' => false, 'search_results' => 'problem with query'];
5821 } elseif (count($r) == 0) {
5822 $success = ['success' => false, 'search_results' => 'nothing found'];
5825 foreach ($r as $item) {
5826 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5827 $recipient = $user_info;
5828 $sender = api_get_user($a, normalise_link($item['contact-url']));
5829 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5830 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5831 $sender = $user_info;
5834 if (isset($recipient) && isset($sender)) {
5835 $ret[] = api_format_messages($item, $recipient, $sender);
5838 $success = ['success' => true, 'search_results' => $ret];
5841 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5844 /// @TODO move to top of file or somewhere better
5845 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5848 * @brief return data of all the profiles a user has to the client
5850 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5851 * @return string|array
5853 function api_friendica_profile_show($type)
5857 if (api_user() === false) {
5858 throw new ForbiddenException();
5862 $profile_id = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5864 // retrieve general information about profiles for user
5865 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5866 $directory = Config::get('system', 'directory');
5868 // get data of the specified profile id or all profiles of the user if not specified
5869 if ($profile_id != 0) {
5871 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5876 // error message if specified gid is not in database
5877 if (!DBM::is_result($r)) {
5878 throw new BadRequestException("profile_id not available");
5882 "SELECT * FROM `profile` WHERE `uid` = %d",
5886 // loop through all returned profiles and retrieve data and users
5889 foreach ($r as $rr) {
5890 $profile = api_format_items_profiles($rr);
5892 // select all users from contact table, loop and prepare standard return for user data
5895 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5897 intval($rr['profile_id'])
5900 foreach ($nurls as $nurl) {
5901 $user = api_get_user($a, $nurl['nurl']);
5902 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5904 $profile['users'] = $users;
5906 // add prepared profile data to array for final return
5907 if ($type == "xml") {
5908 $profiles[$k++ . ":profile"] = $profile;
5910 $profiles[] = $profile;
5914 // return settings, authenticated user and profiles data
5915 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5917 $result = ['multi_profiles' => $multi_profiles ? true : false,
5918 'global_dir' => $directory,
5919 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5920 'profiles' => $profiles];
5921 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5923 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5926 * Returns a list of saved searches.
5928 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5930 * @param string $type Return format: json or xml
5932 * @return string|array
5934 function api_saved_searches_list($type)
5936 $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
5939 while ($term = $terms->fetch()) {
5941 'created_at' => api_date(time()),
5942 'id' => intval($term['id']),
5943 'id_str' => $term['id'],
5944 'name' => $term['term'],
5946 'query' => $term['term']
5952 return api_format_data("terms", $type, ['terms' => $result]);
5955 /// @TODO move to top of file or somewhere better
5956 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5959 @TODO Maybe open to implement?
5961 [pagename] => api/1.1/statuses/lookup.json
5962 [id] => 605138389168451584
5963 [include_cards] => true
5964 [cards_platform] => Android-12
5965 [include_entities] => true
5966 [include_my_retweet] => 1
5968 [include_reply_count] => true
5969 [include_descendent_reply_count] => true
5973 Not implemented by now:
5974 statuses/retweets_of_me
5979 account/update_location
5980 account/update_profile_background_image
5983 friendica/profile/update
5984 friendica/profile/create
5985 friendica/profile/delete
5987 Not implemented in status.net:
5988 statuses/retweeted_to_me
5989 statuses/retweeted_by_me
5990 direct_messages/destroy
5992 account/update_delivery_device
5993 notifications/follow