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'], ['uid' => 0, '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 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 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),
674 'network' => $r[0]["network"],
679 throw new BadRequestException("User not found.");
683 if ($uinfo[0]['self']) {
684 if ($uinfo[0]['network'] == "") {
685 $uinfo[0]['network'] = NETWORK_DFRN;
689 "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
693 "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
697 /// @TODO old-lost code? (twice)
698 // Counting is deactivated by now, due to performance issues
699 // count public wall messages
700 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
701 // intval($uinfo[0]['uid'])
703 //$countitms = $r[0]['count'];
706 // Counting is deactivated by now, due to performance issues
707 //$r = q("SELECT count(*) as `count` FROM `item`
708 // WHERE `contact-id` = %d",
709 // intval($uinfo[0]['id'])
711 //$countitms = $r[0]['count'];
715 /// @TODO old-lost code? (twice)
717 // Counting is deactivated by now, due to performance issues
719 $r = q("SELECT count(*) as `count` FROM `contact`
720 WHERE `uid` = %d AND `rel` IN ( %d, %d )
721 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
722 intval($uinfo[0]['uid']),
723 intval(CONTACT_IS_SHARING),
724 intval(CONTACT_IS_FRIEND)
726 $countfriends = $r[0]['count'];
728 $r = q("SELECT count(*) as `count` FROM `contact`
729 WHERE `uid` = %d AND `rel` IN ( %d, %d )
730 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
731 intval($uinfo[0]['uid']),
732 intval(CONTACT_IS_FOLLOWER),
733 intval(CONTACT_IS_FRIEND)
735 $countfollowers = $r[0]['count'];
737 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
738 intval($uinfo[0]['uid'])
740 $starred = $r[0]['count'];
743 if (! $uinfo[0]['self']) {
753 // Add a nick if it isn't present there
754 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
755 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
758 $network_name = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
760 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
762 if (!empty($profile[0]['about'])) {
763 $description = $profile[0]['about'];
765 $description = $uinfo[0]["about"];
768 if (!empty($usr[0]['default-location'])) {
769 $location = $usr[0]['default-location'];
770 } elseif (!empty($uinfo[0]["location"])) {
771 $location = $uinfo[0]["location"];
773 $location = $network_name;
777 'id' => intval($pcontact_id),
778 'id_str' => (string) intval($pcontact_id),
779 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
780 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
781 'location' => $location,
782 'description' => $description,
783 'profile_image_url' => $uinfo[0]['micro'],
784 'profile_image_url_https' => $uinfo[0]['micro'],
785 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
786 'profile_image_url_large' => $uinfo[0]["photo"],
787 'url' => $uinfo[0]['url'],
788 'protected' => false,
789 'followers_count' => intval($countfollowers),
790 'friends_count' => intval($countfriends),
792 'created_at' => api_date($uinfo[0]['created']),
793 'favourites_count' => intval($starred),
795 'time_zone' => 'UTC',
796 'geo_enabled' => false,
798 'statuses_count' => intval($countitms),
800 'contributors_enabled' => false,
801 'is_translator' => false,
802 'is_translation_enabled' => false,
803 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
804 'follow_request_sent' => false,
805 'statusnet_blocking' => false,
806 'notifications' => false,
808 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
809 'statusnet_profile_url' => $uinfo[0]['url'],
810 'uid' => intval($uinfo[0]['uid']),
811 'cid' => intval($uinfo[0]['cid']),
812 'self' => $uinfo[0]['self'],
813 'network' => $uinfo[0]['network'],
816 // If this is a local user and it uses Frio, we can get its color preferences.
818 $theme_info = dba::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
819 if ($theme_info['theme'] === 'frio') {
820 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
821 if ($schema && ($schema != '---')) {
822 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
823 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
824 require_once $schemefile;
827 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
828 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
829 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
835 $link_color = "#6fdbe8";
838 $bgcolor = "#ededed";
841 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
842 $ret['profile_link_color'] = str_replace('#', '', $link_color);
843 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
851 * @brief return api-formatted array for item's author and owner
853 * @param object $a App
854 * @param array $item item from db
855 * @return array(array:author, array:owner)
857 function api_item_get_user(App $a, $item)
859 $status_user = api_get_user($a, $item["author-link"]);
861 $status_user["protected"] = (($item["allow_cid"] != "") ||
862 ($item["allow_gid"] != "") ||
863 ($item["deny_cid"] != "") ||
864 ($item["deny_gid"] != "") ||
867 if ($item['thr-parent'] == $item['uri']) {
868 $owner_user = api_get_user($a, $item["owner-link"]);
870 $owner_user = $status_user;
873 return ([$status_user, $owner_user]);
877 * @brief walks recursively through an array with the possibility to change value and key
879 * @param array $array The array to walk through
880 * @param string $callback The callback function
882 * @return array the transformed array
884 function api_walk_recursive(array &$array, callable $callback)
888 foreach ($array as $k => $v) {
890 if ($callback($v, $k)) {
891 $new_array[$k] = api_walk_recursive($v, $callback);
894 if ($callback($v, $k)) {
905 * @brief Callback function to transform the array in an array that can be transformed in a XML file
907 * @param mixed $item Array item value
908 * @param string $key Array key
910 * @return boolean Should the array item be deleted?
912 function api_reformat_xml(&$item, &$key)
914 if (is_bool($item)) {
915 $item = ($item ? "true" : "false");
918 if (substr($key, 0, 10) == "statusnet_") {
919 $key = "statusnet:".substr($key, 10);
920 } elseif (substr($key, 0, 10) == "friendica_") {
921 $key = "friendica:".substr($key, 10);
923 /// @TODO old-lost code?
925 // $key = "default:".$key;
931 * @brief Creates the XML from a JSON style array
933 * @param array $data JSON style array
934 * @param string $root_element Name of the root element
936 * @return string The XML data
938 function api_create_xml($data, $root_element)
940 $childname = key($data);
941 $data2 = array_pop($data);
944 $namespaces = ["" => "http://api.twitter.com",
945 "statusnet" => "http://status.net/schema/api/1/",
946 "friendica" => "http://friendi.ca/schema/api/1/",
947 "georss" => "http://www.georss.org/georss"];
949 /// @todo Auto detection of needed namespaces
950 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
954 if (is_array($data2)) {
955 api_walk_recursive($data2, "api_reformat_xml");
962 foreach ($data2 as $item) {
963 $data4[$i++.":".$childname] = $item;
969 $data3 = [$root_element => $data2];
971 $ret = XML::fromArray($data3, $xml, false, $namespaces);
976 * @brief Formats the data according to the data type
978 * @param string $root_element Name of the root element
979 * @param string $type Return type (atom, rss, xml, json)
980 * @param array $data JSON style array
982 * @return (string|array) XML data or JSON data
984 function api_format_data($root_element, $type, $data)
990 $ret = api_create_xml($data, $root_element);
1006 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
1007 * returns a 401 status code and an error message if not.
1008 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
1010 * @param string $type Return type (atom, rss, xml, json)
1012 function api_account_verify_credentials($type)
1017 if (api_user() === false) {
1018 throw new ForbiddenException();
1021 unset($_REQUEST["user_id"]);
1022 unset($_GET["user_id"]);
1024 unset($_REQUEST["screen_name"]);
1025 unset($_GET["screen_name"]);
1027 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
1029 $user_info = api_get_user($a);
1031 // "verified" isn't used here in the standard
1032 unset($user_info["verified"]);
1034 // - Adding last status
1035 if (!$skip_status) {
1036 $user_info["status"] = api_status_show("raw");
1037 if (!count($user_info["status"])) {
1038 unset($user_info["status"]);
1040 unset($user_info["status"]["user"]);
1044 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1045 unset($user_info["uid"]);
1046 unset($user_info["self"]);
1048 return api_format_data("user", $type, ['user' => $user_info]);
1051 /// @TODO move to top of file or somewhere better
1052 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1055 * Get data from $_POST or $_GET
1059 function requestdata($k)
1061 if (x($_POST, $k)) {
1071 * Waitman Gobble Mod
1073 * @param string $type Return type (atom, rss, xml, json)
1075 * @return array|string
1077 function api_statuses_mediap($type)
1081 if (api_user() === false) {
1082 logger('api_statuses_update: no user');
1083 throw new ForbiddenException();
1085 $user_info = api_get_user($a);
1087 $_REQUEST['type'] = 'wall';
1088 $_REQUEST['profile_uid'] = api_user();
1089 $_REQUEST['api_source'] = true;
1090 $txt = requestdata('status');
1091 /// @TODO old-lost code?
1092 //$txt = urldecode(requestdata('status'));
1094 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1095 $txt = html2bb_video($txt);
1096 $config = HTMLPurifier_Config::createDefault();
1097 $config->set('Cache.DefinitionImpl', null);
1098 $purifier = new HTMLPurifier($config);
1099 $txt = $purifier->purify($txt);
1101 $txt = HTML::toBBCode($txt);
1103 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1105 // tell wall_upload function to return img info instead of echo
1106 $_REQUEST['hush'] = 'yeah';
1107 $bebop = wall_upload_post($a);
1109 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1110 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1113 // this should output the last post (the one we just posted).
1114 return api_status_show($type);
1117 /// @TODO move this to top of file or somewhere better!
1118 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1121 * Updates the user’s current status.
1123 * @param string $type Return type (atom, rss, xml, json)
1125 * @return array|string
1126 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1128 function api_statuses_update($type)
1133 if (api_user() === false) {
1134 logger('api_statuses_update: no user');
1135 throw new ForbiddenException();
1140 // convert $_POST array items to the form we use for web posts.
1141 if (requestdata('htmlstatus')) {
1142 $txt = requestdata('htmlstatus');
1143 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1144 $txt = html2bb_video($txt);
1146 $config = HTMLPurifier_Config::createDefault();
1147 $config->set('Cache.DefinitionImpl', null);
1149 $purifier = new HTMLPurifier($config);
1150 $txt = $purifier->purify($txt);
1152 $_REQUEST['body'] = HTML::toBBCode($txt);
1155 $_REQUEST['body'] = requestdata('status');
1158 $_REQUEST['title'] = requestdata('title');
1160 $parent = requestdata('in_reply_to_status_id');
1162 // Twidere sends "-1" if it is no reply ...
1163 if ($parent == -1) {
1167 if (ctype_digit($parent)) {
1168 $_REQUEST['parent'] = $parent;
1170 $_REQUEST['parent_uri'] = $parent;
1173 if (requestdata('lat') && requestdata('long')) {
1174 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1176 $_REQUEST['profile_uid'] = api_user();
1179 $_REQUEST['type'] = 'net-comment';
1181 // Check for throttling (maximum posts per day, week and month)
1182 $throttle_day = Config::get('system', 'throttle_limit_day');
1183 if ($throttle_day > 0) {
1184 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1187 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1188 AND `created` > '%s' AND `id` = `parent`",
1193 if (DBM::is_result($r)) {
1194 $posts_day = $r[0]["posts_day"];
1199 if ($posts_day > $throttle_day) {
1200 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1201 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1202 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));
1206 $throttle_week = Config::get('system', 'throttle_limit_week');
1207 if ($throttle_week > 0) {
1208 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1211 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1212 AND `created` > '%s' AND `id` = `parent`",
1217 if (DBM::is_result($r)) {
1218 $posts_week = $r[0]["posts_week"];
1223 if ($posts_week > $throttle_week) {
1224 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1225 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1226 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));
1230 $throttle_month = Config::get('system', 'throttle_limit_month');
1231 if ($throttle_month > 0) {
1232 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1235 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1236 AND `created` > '%s' AND `id` = `parent`",
1241 if (DBM::is_result($r)) {
1242 $posts_month = $r[0]["posts_month"];
1247 if ($posts_month > $throttle_month) {
1248 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1249 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1250 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));
1254 $_REQUEST['type'] = 'wall';
1257 if (x($_FILES, 'media')) {
1258 // upload the image if we have one
1259 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1260 $media = wall_upload_post($a);
1261 if (strlen($media) > 0) {
1262 $_REQUEST['body'] .= "\n\n" . $media;
1266 // To-Do: Multiple IDs
1267 if (requestdata('media_ids')) {
1269 "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",
1270 intval(requestdata('media_ids')),
1273 if (DBM::is_result($r)) {
1274 $phototypes = Image::supportedTypes();
1275 $ext = $phototypes[$r[0]['type']];
1276 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1277 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1281 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1283 $_REQUEST['api_source'] = true;
1285 if (!x($_REQUEST, "source")) {
1286 $_REQUEST["source"] = api_source();
1289 // call out normal post function
1292 // this should output the last post (the one we just posted).
1293 return api_status_show($type);
1296 /// @TODO move to top of file or somewhere better
1297 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1298 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1301 * Uploads an image to Friendica.
1304 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1306 function api_media_upload()
1310 if (api_user() === false) {
1312 throw new ForbiddenException();
1317 if (!x($_FILES, 'media')) {
1319 throw new BadRequestException("No media.");
1322 $media = wall_upload_post($a, false);
1325 throw new InternalServerErrorException();
1329 $returndata["media_id"] = $media["id"];
1330 $returndata["media_id_string"] = (string)$media["id"];
1331 $returndata["size"] = $media["size"];
1332 $returndata["image"] = ["w" => $media["width"],
1333 "h" => $media["height"],
1334 "image_type" => $media["type"]];
1336 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1338 return ["media" => $returndata];
1341 /// @TODO move to top of file or somewhere better
1342 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1346 * @param string $type Return type (atom, rss, xml, json)
1348 * @return array|string
1350 function api_status_show($type)
1354 $user_info = api_get_user($a);
1356 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1358 if ($type == "raw") {
1359 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1364 // get last public wall message
1368 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1369 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1370 AND `item`.`type` != 'activity' $privacy_sql
1371 ORDER BY `item`.`id` DESC
1373 intval($user_info['cid']),
1375 dbesc($user_info['url']),
1376 dbesc(normalise_link($user_info['url'])),
1377 dbesc($user_info['url']),
1378 dbesc(normalise_link($user_info['url']))
1381 if (DBM::is_result($lastwall)) {
1382 $lastwall = $lastwall[0];
1384 $in_reply_to = api_in_reply_to($lastwall);
1386 $converted = api_convert_item($lastwall);
1388 if ($type == "xml") {
1389 $geo = "georss:point";
1395 'created_at' => api_date($lastwall['created']),
1396 'id' => intval($lastwall['id']),
1397 'id_str' => (string) $lastwall['id'],
1398 'text' => $converted["text"],
1399 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1400 'truncated' => false,
1401 'in_reply_to_status_id' => $in_reply_to['status_id'],
1402 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1403 'in_reply_to_user_id' => $in_reply_to['user_id'],
1404 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1405 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1406 'user' => $user_info,
1408 'coordinates' => "",
1410 'contributors' => "",
1411 'is_quote_status' => false,
1412 'retweet_count' => 0,
1413 'favorite_count' => 0,
1414 'favorited' => $lastwall['starred'] ? true : false,
1415 'retweeted' => false,
1416 'possibly_sensitive' => false,
1418 'statusnet_html' => $converted["html"],
1419 'statusnet_conversation_id' => $lastwall['parent'],
1420 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1423 if (count($converted["attachments"]) > 0) {
1424 $status_info["attachments"] = $converted["attachments"];
1427 if (count($converted["entities"]) > 0) {
1428 $status_info["entities"] = $converted["entities"];
1431 if (($lastwall['item_network'] != "") && ($status_info["source"] == 'web')) {
1432 $status_info["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1433 } elseif (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1434 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['item_network'], $user_info['url']).')');
1437 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1438 unset($status_info["user"]["uid"]);
1439 unset($status_info["user"]["self"]);
1441 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1443 if ($type == "raw") {
1444 return $status_info;
1447 return api_format_data("statuses", $type, ['status' => $status_info]);
1452 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1453 * The author's most recent status will be returned inline.
1455 * @param string $type Return type (atom, rss, xml, json)
1456 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1458 function api_users_show($type)
1462 $user_info = api_get_user($a);
1466 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1467 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1468 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1469 AND `type`!='activity'
1470 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1474 dbesc(ACTIVITY_POST),
1475 intval($user_info['cid']),
1476 dbesc($user_info['url']),
1477 dbesc(normalise_link($user_info['url'])),
1478 dbesc($user_info['url']),
1479 dbesc(normalise_link($user_info['url']))
1482 if (DBM::is_result($lastwall)) {
1483 $lastwall = $lastwall[0];
1485 $in_reply_to = api_in_reply_to($lastwall);
1487 $converted = api_convert_item($lastwall);
1489 if ($type == "xml") {
1490 $geo = "georss:point";
1495 $user_info['status'] = [
1496 'text' => $converted["text"],
1497 'truncated' => false,
1498 'created_at' => api_date($lastwall['created']),
1499 'in_reply_to_status_id' => $in_reply_to['status_id'],
1500 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1501 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1502 'id' => intval($lastwall['contact-id']),
1503 'id_str' => (string) $lastwall['contact-id'],
1504 'in_reply_to_user_id' => $in_reply_to['user_id'],
1505 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1506 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1508 'favorited' => $lastwall['starred'] ? true : false,
1509 'statusnet_html' => $converted["html"],
1510 'statusnet_conversation_id' => $lastwall['parent'],
1511 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1514 if (count($converted["attachments"]) > 0) {
1515 $user_info["status"]["attachments"] = $converted["attachments"];
1518 if (count($converted["entities"]) > 0) {
1519 $user_info["status"]["entities"] = $converted["entities"];
1522 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1523 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1526 if (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1527 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) . ')');
1531 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1532 unset($user_info["uid"]);
1533 unset($user_info["self"]);
1535 return api_format_data("user", $type, ['user' => $user_info]);
1538 /// @TODO move to top of file or somewhere better
1539 api_register_func('api/users/show', 'api_users_show');
1540 api_register_func('api/externalprofile/show', 'api_users_show');
1543 * Search a public user account.
1545 * @param string $type Return type (atom, rss, xml, json)
1547 * @return array|string
1548 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1550 function api_users_search($type)
1556 if (x($_GET, 'q')) {
1557 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1559 if (!DBM::is_result($r)) {
1560 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1563 if (DBM::is_result($r)) {
1565 foreach ($r as $user) {
1566 $user_info = api_get_user($a, $user["id"]);
1568 if ($type == "xml") {
1569 $userlist[$k++.":user"] = $user_info;
1571 $userlist[] = $user_info;
1574 $userlist = ["users" => $userlist];
1576 throw new BadRequestException("User not found.");
1579 throw new BadRequestException("User not found.");
1582 return api_format_data("users", $type, $userlist);
1585 /// @TODO move to top of file or somewhere better
1586 api_register_func('api/users/search', 'api_users_search');
1589 * Return user objects
1591 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1593 * @param string $type Return format: json or xml
1595 * @return array|string
1596 * @throws NotFoundException if the results are empty.
1598 function api_users_lookup($type)
1602 if (x($_REQUEST['user_id'])) {
1603 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1605 $users[] = api_get_user(get_app(), $id);
1610 if (empty($users)) {
1611 throw new NotFoundException;
1614 return api_format_data("users", $type, ['users' => $users]);
1617 /// @TODO move to top of file or somewhere better
1618 api_register_func('api/users/lookup', 'api_users_lookup', true);
1621 * Returns statuses that match a specified query.
1623 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1625 * @param string $type Return format: json, xml, atom, rss
1627 * @return array|string
1628 * @throws BadRequestException if the "q" parameter is missing.
1630 function api_search($type)
1633 $user_info = api_get_user($a);
1635 if (api_user() === false || $user_info === false) {
1636 throw new ForbiddenException();
1642 if (!x($_REQUEST, 'q')) {
1643 throw new BadRequestException("q parameter is required.");
1646 if (x($_REQUEST, 'rpp')) {
1647 $count = $_REQUEST['rpp'];
1648 } elseif (x($_REQUEST, 'count')) {
1649 $count = $_REQUEST['count'];
1654 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1655 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1656 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1658 $start = $page * $count;
1661 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1665 "SELECT ".item_fieldlists()."
1666 FROM `item` ".item_joins()."
1667 WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1668 AND `item`.`body` LIKE CONCAT('%',?,'%')
1671 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
1677 $data['status'] = api_format_items(dba::inArray($r), $user_info);
1679 return api_format_data("statuses", $type, $data);
1682 /// @TODO move to top of file or somewhere better
1683 api_register_func('api/search/tweets', 'api_search', true);
1684 api_register_func('api/search', 'api_search', true);
1687 * Returns the most recent statuses posted by the user and the users they follow.
1689 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1691 * @param string $type Return type (atom, rss, xml, json)
1693 * @todo Optional parameters
1694 * @todo Add reply info
1696 function api_statuses_home_timeline($type)
1699 $user_info = api_get_user($a);
1701 if (api_user() === false || $user_info === false) {
1702 throw new ForbiddenException();
1705 unset($_REQUEST["user_id"]);
1706 unset($_GET["user_id"]);
1708 unset($_REQUEST["screen_name"]);
1709 unset($_GET["screen_name"]);
1711 // get last network messages
1714 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1715 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1719 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1720 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1721 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1722 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1723 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1725 $start = $page * $count;
1729 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1731 if ($exclude_replies > 0) {
1732 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1734 if ($conversation_id > 0) {
1735 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1739 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1740 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1741 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1742 `contact`.`id` AS `cid`
1744 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1745 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1746 WHERE `item`.`uid` = %d AND `verb` = '%s'
1747 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1750 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1752 dbesc(ACTIVITY_POST),
1758 $ret = api_format_items($r, $user_info, false, $type);
1760 // Set all posts from the query above to seen
1762 foreach ($r as $item) {
1763 $idarray[] = intval($item["id"]);
1766 if (!empty($idarray)) {
1767 $unseen = dba::exists('item', ['unseen' => true, 'id' => $idarray]);
1769 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1773 $data = ['status' => $ret];
1777 $data = api_rss_extra($a, $data, $user_info);
1781 return api_format_data("statuses", $type, $data);
1784 /// @TODO move to top of file or somewhere better
1785 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1786 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1789 * Returns the most recent statuses from public users.
1791 * @param string $type Return type (atom, rss, xml, json)
1793 * @return array|string
1795 function api_statuses_public_timeline($type)
1798 $user_info = api_get_user($a);
1800 if (api_user() === false || $user_info === false) {
1801 throw new ForbiddenException();
1804 // get last network messages
1807 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1808 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1812 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1813 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1814 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1815 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1816 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1818 $start = $page * $count;
1821 if ($exclude_replies && !$conversation_id) {
1823 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1827 "SELECT " . item_fieldlists() . "
1829 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1830 " . item_joins() . "
1831 STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1832 AND NOT `user`.`hidewall`
1834 AND NOT `thread`.`private`
1836 AND `thread`.`visible`
1837 AND NOT `thread`.`deleted`
1838 AND NOT `thread`.`moderated`
1839 AND `thread`.`iid` > ?
1841 ORDER BY `thread`.`iid` DESC
1842 LIMIT " . intval($start) . ", " . intval($count),
1847 $r = dba::inArray($r);
1850 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1852 if ($conversation_id > 0) {
1853 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1857 "SELECT " . item_fieldlists() . "
1859 " . item_joins() . "
1860 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1861 AND NOT `user`.`hidewall`
1863 AND NOT `item`.`private`
1865 AND `item`.`visible`
1866 AND NOT `item`.`deleted`
1867 AND NOT `item`.`moderated`
1870 ORDER BY `item`.`id` DESC
1871 LIMIT " . intval($start) . ", " . intval($count),
1876 $r = dba::inArray($r);
1879 $ret = api_format_items($r, $user_info, false, $type);
1881 $data = ['status' => $ret];
1885 $data = api_rss_extra($a, $data, $user_info);
1889 return api_format_data("statuses", $type, $data);
1892 /// @TODO move to top of file or somewhere better
1893 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1896 * Returns the most recent statuses posted by users this node knows about.
1898 * @brief Returns the list of public federated posts this node knows about
1900 * @param string $type Return format: json, xml, atom, rss
1901 * @return array|string
1902 * @throws ForbiddenException
1904 function api_statuses_networkpublic_timeline($type)
1907 $user_info = api_get_user($a);
1909 if (api_user() === false || $user_info === false) {
1910 throw new ForbiddenException();
1913 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1914 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1917 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1918 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1922 $start = ($page - 1) * $count;
1926 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1930 "SELECT " . item_fieldlists() . "
1932 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1933 " . item_joins() . "
1934 WHERE `thread`.`uid` = 0
1936 AND NOT `thread`.`private`
1937 AND `thread`.`visible`
1938 AND NOT `thread`.`deleted`
1939 AND NOT `thread`.`moderated`
1940 AND `thread`.`iid` > ?
1942 ORDER BY `thread`.`iid` DESC
1943 LIMIT " . intval($start) . ", " . intval($count),
1948 $r = dba::inArray($r);
1950 $ret = api_format_items($r, $user_info, false, $type);
1952 $data = ['status' => $ret];
1956 $data = api_rss_extra($a, $data, $user_info);
1960 return api_format_data("statuses", $type, $data);
1963 /// @TODO move to top of file or somewhere better
1964 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1967 * Returns a single status.
1969 * @param string $type Return type (atom, rss, xml, json)
1971 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1973 function api_statuses_show($type)
1976 $user_info = api_get_user($a);
1978 if (api_user() === false || $user_info === false) {
1979 throw new ForbiddenException();
1983 $id = intval($a->argv[3]);
1986 $id = intval($_REQUEST["id"]);
1991 $id = intval($a->argv[4]);
1994 logger('API: api_statuses_show: ' . $id);
1996 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1999 if ($conversation) {
2000 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
2002 $sql_extra .= " AND `item`.`id` = %d";
2006 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2007 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2008 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2009 `contact`.`id` AS `cid`
2011 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2012 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2013 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2014 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2017 dbesc(ACTIVITY_POST),
2021 /// @TODO How about copying this to above methods which don't check $r ?
2022 if (!DBM::is_result($r)) {
2023 throw new BadRequestException("There is no status with this id.");
2026 $ret = api_format_items($r, $user_info, false, $type);
2028 if ($conversation) {
2029 $data = ['status' => $ret];
2030 return api_format_data("statuses", $type, $data);
2032 $data = ['status' => $ret[0]];
2033 return api_format_data("status", $type, $data);
2037 /// @TODO move to top of file or somewhere better
2038 api_register_func('api/statuses/show', 'api_statuses_show', true);
2042 * @param string $type Return type (atom, rss, xml, json)
2044 * @todo nothing to say?
2046 function api_conversation_show($type)
2049 $user_info = api_get_user($a);
2051 if (api_user() === false || $user_info === false) {
2052 throw new ForbiddenException();
2056 $id = intval($a->argv[3]);
2057 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2058 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
2062 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2063 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2065 $start = $page*$count;
2068 $id = intval($_REQUEST["id"]);
2073 $id = intval($a->argv[4]);
2076 logger('API: api_conversation_show: '.$id);
2078 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
2079 if (DBM::is_result($r)) {
2080 $id = $r[0]["parent"];
2086 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2089 // Not sure why this query was so complicated. We should keep it here for a while,
2090 // just to make sure that we really don't need it.
2091 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
2092 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
2095 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2096 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2097 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2098 `contact`.`id` AS `cid`
2100 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2101 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2102 WHERE `item`.`parent` = %d AND `item`.`visible`
2103 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2104 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2105 AND `item`.`id`>%d $sql_extra
2106 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2109 dbesc(ACTIVITY_POST),
2115 if (!DBM::is_result($r)) {
2116 throw new BadRequestException("There is no status with this id.");
2119 $ret = api_format_items($r, $user_info, false, $type);
2121 $data = ['status' => $ret];
2122 return api_format_data("statuses", $type, $data);
2125 /// @TODO move to top of file or somewhere better
2126 api_register_func('api/conversation/show', 'api_conversation_show', true);
2127 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2132 * @param string $type Return type (atom, rss, xml, json)
2134 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2136 function api_statuses_repeat($type)
2142 if (api_user() === false) {
2143 throw new ForbiddenException();
2149 $id = intval($a->argv[3]);
2152 $id = intval($_REQUEST["id"]);
2157 $id = intval($a->argv[4]);
2160 logger('API: api_statuses_repeat: '.$id);
2163 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2164 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2165 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2166 `contact`.`id` AS `cid`
2168 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2169 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2170 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2171 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2172 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2173 AND `item`.`id`=%d",
2177 /// @TODO other style than above functions!
2178 if (DBM::is_result($r) && $r[0]['body'] != "") {
2179 if (strpos($r[0]['body'], "[/share]") !== false) {
2180 $pos = strpos($r[0]['body'], "[share");
2181 $post = substr($r[0]['body'], $pos);
2183 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2185 $post .= $r[0]['body'];
2186 $post .= "[/share]";
2188 $_REQUEST['body'] = $post;
2189 $_REQUEST['profile_uid'] = api_user();
2190 $_REQUEST['type'] = 'wall';
2191 $_REQUEST['api_source'] = true;
2193 if (!x($_REQUEST, "source")) {
2194 $_REQUEST["source"] = api_source();
2199 throw new ForbiddenException();
2202 // this should output the last post (the one we just posted).
2204 return api_status_show($type);
2207 /// @TODO move to top of file or somewhere better
2208 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2211 * Destroys a specific status.
2213 * @param string $type Return type (atom, rss, xml, json)
2215 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2217 function api_statuses_destroy($type)
2221 if (api_user() === false) {
2222 throw new ForbiddenException();
2228 $id = intval($a->argv[3]);
2231 $id = intval($_REQUEST["id"]);
2236 $id = intval($a->argv[4]);
2239 logger('API: api_statuses_destroy: '.$id);
2241 $ret = api_statuses_show($type);
2243 Item::deleteById($id);
2248 /// @TODO move to top of file or somewhere better
2249 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2252 * Returns the most recent mentions.
2254 * @param string $type Return type (atom, rss, xml, json)
2256 * @see http://developer.twitter.com/doc/get/statuses/mentions
2258 function api_statuses_mentions($type)
2261 $user_info = api_get_user($a);
2263 if (api_user() === false || $user_info === false) {
2264 throw new ForbiddenException();
2267 unset($_REQUEST["user_id"]);
2268 unset($_GET["user_id"]);
2270 unset($_REQUEST["screen_name"]);
2271 unset($_GET["screen_name"]);
2273 // get last network messages
2276 $since_id = defaults($_REQUEST, 'since_id', 0);
2277 $max_id = defaults($_REQUEST, 'max_id' , 0);
2278 $count = defaults($_REQUEST, 'count' , 20);
2279 $page = defaults($_REQUEST, 'page' , 1);
2284 $start = ($page - 1) * $count;
2286 // Ugly code - should be changed
2287 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2288 $myurl = substr($myurl, strpos($myurl, '://') + 3);
2289 $myurl = str_replace('www.', '', $myurl);
2294 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2298 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2299 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2300 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2301 `contact`.`id` AS `cid`
2302 FROM `item` FORCE INDEX (`uid_id`)
2303 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2304 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2305 WHERE `item`.`uid` = %d AND `verb` = '%s'
2306 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2307 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2308 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2311 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2313 dbesc(ACTIVITY_POST),
2314 dbesc(protect_sprintf($myurl)),
2315 dbesc(protect_sprintf($myurl)),
2322 $ret = api_format_items($r, $user_info, false, $type);
2324 $data = ['status' => $ret];
2328 $data = api_rss_extra($a, $data, $user_info);
2332 return api_format_data("statuses", $type, $data);
2335 /// @TODO move to top of file or somewhere better
2336 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2337 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2340 * Returns the most recent statuses posted by the user.
2342 * @brief Returns a user's public timeline
2344 * @param string $type Either "json" or "xml"
2345 * @return string|array
2346 * @throws ForbiddenException
2347 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2349 function api_statuses_user_timeline($type)
2352 $user_info = api_get_user($a);
2354 if (api_user() === false || $user_info === false) {
2355 throw new ForbiddenException();
2359 "api_statuses_user_timeline: api_user: ". api_user() .
2360 "\nuser_info: ".print_r($user_info, true) .
2361 "\n_REQUEST: ".print_r($_REQUEST, true),
2365 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2366 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2367 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2368 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2371 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2372 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2376 $start = ($page - 1) * $count;
2379 if ($user_info['self'] == 1) {
2380 $sql_extra .= " AND `item`.`wall` = 1 ";
2383 if ($exclude_replies > 0) {
2384 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2387 if ($conversation_id > 0) {
2388 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2392 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2396 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2397 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2398 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2399 `contact`.`id` AS `cid`
2400 FROM `item` FORCE INDEX (`uid_contactid_id`)
2401 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2402 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2403 WHERE `item`.`uid` = %d AND `verb` = '%s'
2404 AND `item`.`contact-id` = %d
2405 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2407 AND `item`.`id` > %d
2408 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2410 dbesc(ACTIVITY_POST),
2411 intval($user_info['cid']),
2417 $ret = api_format_items($r, $user_info, true, $type);
2419 $data = ['status' => $ret];
2423 $data = api_rss_extra($a, $data, $user_info);
2427 return api_format_data("statuses", $type, $data);
2430 /// @TODO move to top of file or somewhere better
2431 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2434 * Star/unstar an item.
2435 * param: id : id of the item
2437 * @param string $type Return type (atom, rss, xml, json)
2439 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2441 function api_favorites_create_destroy($type)
2445 if (api_user() === false) {
2446 throw new ForbiddenException();
2449 // for versioned api.
2450 /// @TODO We need a better global soluton
2451 $action_argv_id = 2;
2452 if ($a->argv[1] == "1.1") {
2453 $action_argv_id = 3;
2456 if ($a->argc <= $action_argv_id) {
2457 throw new BadRequestException("Invalid request.");
2459 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2460 if ($a->argc == $action_argv_id + 2) {
2461 $itemid = intval($a->argv[$action_argv_id + 1]);
2463 /// @TODO use x() to check if _REQUEST contains 'id'
2464 $itemid = intval($_REQUEST['id']);
2467 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2469 if (!DBM::is_result($item) || count($item) == 0) {
2470 throw new BadRequestException("Invalid item.");
2475 $item[0]['starred'] = 1;
2478 $item[0]['starred'] = 0;
2481 throw new BadRequestException("Invalid action ".$action);
2484 $r = Item::update(['starred' => $item[0]['starred']], ['id' => $itemid]);
2487 throw new InternalServerErrorException("DB error");
2491 $user_info = api_get_user($a);
2492 $rets = api_format_items($item, $user_info, false, $type);
2495 $data = ['status' => $ret];
2499 $data = api_rss_extra($a, $data, $user_info);
2502 return api_format_data("status", $type, $data);
2505 /// @TODO move to top of file or somewhere better
2506 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2507 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2510 * Returns the most recent favorite statuses.
2512 * @param string $type Return type (atom, rss, xml, json)
2514 * @return string|array
2516 function api_favorites($type)
2521 $user_info = api_get_user($a);
2523 if (api_user() === false || $user_info === false) {
2524 throw new ForbiddenException();
2529 // in friendica starred item are private
2530 // return favorites only for self
2531 logger('api_favorites: self:' . $user_info['self']);
2533 if ($user_info['self'] == 0) {
2539 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2540 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2541 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2542 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2547 $start = $page*$count;
2550 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2554 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2555 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2556 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2557 `contact`.`id` AS `cid`
2558 FROM `item`, `contact`
2559 WHERE `item`.`uid` = %d
2560 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2561 AND `item`.`starred` = 1
2562 AND `contact`.`id` = `item`.`contact-id`
2563 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2566 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2573 $ret = api_format_items($r, $user_info, false, $type);
2576 $data = ['status' => $ret];
2580 $data = api_rss_extra($a, $data, $user_info);
2583 return api_format_data("statuses", $type, $data);
2586 /// @TODO move to top of file or somewhere better
2587 api_register_func('api/favorites', 'api_favorites', true);
2591 * @param array $item
2592 * @param array $recipient
2593 * @param array $sender
2597 function api_format_messages($item, $recipient, $sender)
2599 // standard meta information
2601 'id' => $item['id'],
2602 'sender_id' => $sender['id'] ,
2604 'recipient_id' => $recipient['id'],
2605 'created_at' => api_date($item['created']),
2606 'sender_screen_name' => $sender['screen_name'],
2607 'recipient_screen_name' => $recipient['screen_name'],
2608 'sender' => $sender,
2609 'recipient' => $recipient,
2611 'friendica_seen' => $item['seen'],
2612 'friendica_parent_uri' => $item['parent-uri'],
2615 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2616 unset($ret["sender"]["uid"]);
2617 unset($ret["sender"]["self"]);
2618 unset($ret["recipient"]["uid"]);
2619 unset($ret["recipient"]["self"]);
2621 //don't send title to regular StatusNET requests to avoid confusing these apps
2622 if (x($_GET, 'getText')) {
2623 $ret['title'] = $item['title'];
2624 if ($_GET['getText'] == 'html') {
2625 $ret['text'] = BBCode::convert($item['body'], false);
2626 } elseif ($_GET['getText'] == 'plain') {
2627 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2630 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2632 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2633 unset($ret['sender']);
2634 unset($ret['recipient']);
2642 * @param array $item
2646 function api_convert_item($item)
2648 $body = $item['body'];
2649 $attachments = api_get_attachments($body);
2651 // Workaround for ostatus messages where the title is identically to the body
2652 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2653 $statusbody = trim(HTML::toPlaintext($html, 0));
2655 // handle data: images
2656 $statusbody = api_format_items_embeded_images($item, $statusbody);
2658 $statustitle = trim($item['title']);
2660 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2661 $statustext = trim($statusbody);
2663 $statustext = trim($statustitle."\n\n".$statusbody);
2666 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2667 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2670 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2672 // Workaround for clients with limited HTML parser functionality
2673 $search = ["<br>", "<blockquote>", "</blockquote>",
2674 "<h1>", "</h1>", "<h2>", "</h2>",
2675 "<h3>", "</h3>", "<h4>", "</h4>",
2676 "<h5>", "</h5>", "<h6>", "</h6>"];
2677 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2678 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2679 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2680 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2681 $statushtml = str_replace($search, $replace, $statushtml);
2683 if ($item['title'] != "") {
2684 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2688 $oldtext = $statushtml;
2689 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2690 } while ($oldtext != $statushtml);
2692 if (substr($statushtml, 0, 4) == '<br>') {
2693 $statushtml = substr($statushtml, 4);
2696 if (substr($statushtml, 0, -4) == '<br>') {
2697 $statushtml = substr($statushtml, -4);
2700 // feeds without body should contain the link
2701 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2702 $statushtml .= BBCode::convert($item['plink']);
2705 $entities = api_get_entitities($statustext, $body);
2708 "text" => $statustext,
2709 "html" => $statushtml,
2710 "attachments" => $attachments,
2711 "entities" => $entities
2717 * @param string $body
2719 * @return array|false
2721 function api_get_attachments(&$body)
2724 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2726 $URLSearchString = "^\[\]";
2727 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2735 foreach ($images[1] as $image) {
2736 $imagedata = Image::getInfoFromURL($image);
2739 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2743 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2744 foreach ($images[0] as $orig) {
2745 $body = str_replace($orig, "", $body);
2749 return $attachments;
2754 * @param string $text
2755 * @param string $bbcode
2758 * @todo Links at the first character of the post
2760 function api_get_entitities(&$text, $bbcode)
2762 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2764 if ($include_entities != "true") {
2765 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2767 foreach ($images[1] as $image) {
2768 $replace = proxy_url($image);
2769 $text = str_replace($image, $replace, $text);
2774 $bbcode = BBCode::cleanPictureLinks($bbcode);
2776 // Change pure links in text to bbcode uris
2777 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2780 $entities["hashtags"] = [];
2781 $entities["symbols"] = [];
2782 $entities["urls"] = [];
2783 $entities["user_mentions"] = [];
2785 $URLSearchString = "^\[\]";
2787 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2789 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2790 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2791 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2793 $bbcode = preg_replace(
2794 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2795 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2798 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2800 $bbcode = preg_replace(
2801 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2802 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2805 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2807 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2809 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2810 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2813 foreach ($urls[1] as $id => $url) {
2814 //$start = strpos($text, $url, $offset);
2815 $start = iconv_strpos($text, $url, 0, "UTF-8");
2816 if (!($start === false)) {
2817 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2821 ksort($ordered_urls);
2824 //foreach ($urls[1] AS $id=>$url) {
2825 foreach ($ordered_urls as $url) {
2826 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2827 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2829 $display_url = $url["title"];
2831 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2832 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2834 if (strlen($display_url) > 26) {
2835 $display_url = substr($display_url, 0, 25)."…";
2839 //$start = strpos($text, $url, $offset);
2840 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2841 if (!($start === false)) {
2842 $entities["urls"][] = ["url" => $url["url"],
2843 "expanded_url" => $url["url"],
2844 "display_url" => $display_url,
2845 "indices" => [$start, $start+strlen($url["url"])]];
2846 $offset = $start + 1;
2850 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2851 $ordered_images = [];
2852 foreach ($images[1] as $image) {
2853 //$start = strpos($text, $url, $offset);
2854 $start = iconv_strpos($text, $image, 0, "UTF-8");
2855 if (!($start === false)) {
2856 $ordered_images[$start] = $image;
2859 //$entities["media"] = array();
2862 foreach ($ordered_images as $url) {
2863 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2864 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2866 if (strlen($display_url) > 26) {
2867 $display_url = substr($display_url, 0, 25)."…";
2870 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2871 if (!($start === false)) {
2872 $image = Image::getInfoFromURL($url);
2874 // If image cache is activated, then use the following sizes:
2875 // thumb (150), small (340), medium (600) and large (1024)
2876 if (!Config::get("system", "proxy_disabled")) {
2877 $media_url = proxy_url($url);
2880 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2881 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2883 if (($image[0] > 150) || ($image[1] > 150)) {
2884 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2885 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2888 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2889 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2891 if (($image[0] > 600) || ($image[1] > 600)) {
2892 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2893 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2897 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2900 $entities["media"][] = [
2902 "id_str" => (string)$start+1,
2903 "indices" => [$start, $start+strlen($url)],
2904 "media_url" => normalise_link($media_url),
2905 "media_url_https" => $media_url,
2907 "display_url" => $display_url,
2908 "expanded_url" => $url,
2912 $offset = $start + 1;
2921 * @param array $item
2922 * @param string $text
2926 function api_format_items_embeded_images($item, $text)
2928 $text = preg_replace_callback(
2929 '|data:image/([^;]+)[^=]+=*|m',
2930 function () use ($item) {
2931 return System::baseUrl() . '/display/' . $item['guid'];
2939 * @brief return <a href='url'>name</a> as array
2941 * @param string $txt text
2946 function api_contactlink_to_array($txt)
2949 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2950 if ($r && count($match)==3) {
2952 'name' => $match[2],
2966 * @brief return likes, dislikes and attend status for item
2968 * @param array $item array
2969 * @param string $type Return type (atom, rss, xml, json)
2972 * likes => int count,
2973 * dislikes => int count
2975 function api_format_items_activities(&$item, $type = "json")
2984 'attendmaybe' => [],
2989 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2990 intval($item['uid']),
2994 foreach ($items as $i) {
2995 // not used as result should be structured like other user data
2996 //builtin_activity_puller($i, $activities);
2998 // get user data and add it to the array of the activity
2999 $user = api_get_user($a, $i['author-link']);
3000 switch ($i['verb']) {
3002 $activities['like'][] = $user;
3004 case ACTIVITY_DISLIKE:
3005 $activities['dislike'][] = $user;
3007 case ACTIVITY_ATTEND:
3008 $activities['attendyes'][] = $user;
3010 case ACTIVITY_ATTENDNO:
3011 $activities['attendno'][] = $user;
3013 case ACTIVITY_ATTENDMAYBE:
3014 $activities['attendmaybe'][] = $user;
3021 if ($type == "xml") {
3022 $xml_activities = [];
3023 foreach ($activities as $k => $v) {
3024 // change xml element from "like" to "friendica:like"
3025 $xml_activities["friendica:".$k] = $v;
3026 // add user data into xml output
3028 foreach ($v as $user) {
3029 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
3032 $activities = $xml_activities;
3040 * @brief return data from profiles
3042 * @param array $profile_row array containing data from db table 'profile'
3045 function api_format_items_profiles($profile_row)
3048 'profile_id' => $profile_row['id'],
3049 'profile_name' => $profile_row['profile-name'],
3050 'is_default' => $profile_row['is-default'] ? true : false,
3051 'hide_friends' => $profile_row['hide-friends'] ? true : false,
3052 'profile_photo' => $profile_row['photo'],
3053 'profile_thumb' => $profile_row['thumb'],
3054 'publish' => $profile_row['publish'] ? true : false,
3055 'net_publish' => $profile_row['net-publish'] ? true : false,
3056 'description' => $profile_row['pdesc'],
3057 'date_of_birth' => $profile_row['dob'],
3058 'address' => $profile_row['address'],
3059 'city' => $profile_row['locality'],
3060 'region' => $profile_row['region'],
3061 'postal_code' => $profile_row['postal-code'],
3062 'country' => $profile_row['country-name'],
3063 'hometown' => $profile_row['hometown'],
3064 'gender' => $profile_row['gender'],
3065 'marital' => $profile_row['marital'],
3066 'marital_with' => $profile_row['with'],
3067 'marital_since' => $profile_row['howlong'],
3068 'sexual' => $profile_row['sexual'],
3069 'politic' => $profile_row['politic'],
3070 'religion' => $profile_row['religion'],
3071 'public_keywords' => $profile_row['pub_keywords'],
3072 'private_keywords' => $profile_row['prv_keywords'],
3073 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
3074 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
3075 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
3076 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
3077 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
3078 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
3079 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
3080 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
3081 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
3082 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
3083 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
3084 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
3085 'homepage' => $profile_row['homepage'],
3092 * @brief format items to be returned by api
3094 * @param array $r array of items
3095 * @param array $user_info
3096 * @param bool $filter_user filter items by $user_info
3097 * @param string $type Return type (atom, rss, xml, json)
3099 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
3105 foreach ($r as $item) {
3106 localize_item($item);
3107 list($status_user, $owner_user) = api_item_get_user($a, $item);
3109 // Look if the posts are matching if they should be filtered by user id
3110 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3114 $in_reply_to = api_in_reply_to($item);
3116 $converted = api_convert_item($item);
3118 if ($type == "xml") {
3119 $geo = "georss:point";
3125 'text' => $converted["text"],
3126 'truncated' => false,
3127 'created_at'=> api_date($item['created']),
3128 'in_reply_to_status_id' => $in_reply_to['status_id'],
3129 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3130 'source' => (($item['app']) ? $item['app'] : 'web'),
3131 'id' => intval($item['id']),
3132 'id_str' => (string) intval($item['id']),
3133 'in_reply_to_user_id' => $in_reply_to['user_id'],
3134 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3135 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3137 'favorited' => $item['starred'] ? true : false,
3138 'user' => $status_user ,
3139 'friendica_owner' => $owner_user,
3140 //'entities' => NULL,
3141 'statusnet_html' => $converted["html"],
3142 'statusnet_conversation_id' => $item['parent'],
3143 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3144 'friendica_activities' => api_format_items_activities($item, $type),
3147 if (count($converted["attachments"]) > 0) {
3148 $status["attachments"] = $converted["attachments"];
3151 if (count($converted["entities"]) > 0) {
3152 $status["entities"] = $converted["entities"];
3155 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
3156 $status["source"] = ContactSelector::networkToName($item['item_network'], $user_info['url']);
3157 } elseif (($item['item_network'] != "") && (ContactSelector::networkToName($item['item_network'], $user_info['url']) != $status["source"])) {
3158 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['item_network'], $user_info['url']).')');
3162 // Retweets are only valid for top postings
3163 // It doesn't work reliable with the link if its a feed
3164 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
3166 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
3169 if ($item["id"] == $item["parent"]) {
3170 $retweeted_item = api_share_as_retweet($item);
3171 if ($retweeted_item !== false) {
3172 $retweeted_status = $status;
3174 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
3175 } catch (BadRequestException $e) {
3176 // user not found. should be found?
3177 /// @todo check if the user should be always found
3178 $retweeted_status["user"] = [];
3181 $rt_converted = api_convert_item($retweeted_item);
3183 $retweeted_status['text'] = $rt_converted["text"];
3184 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3185 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3186 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3187 $status['retweeted_status'] = $retweeted_status;
3191 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3192 unset($status["user"]["uid"]);
3193 unset($status["user"]["self"]);
3195 if ($item["coord"] != "") {
3196 $coords = explode(' ', $item["coord"]);
3197 if (count($coords) == 2) {
3198 if ($type == "json") {
3199 $status["geo"] = ['type' => 'Point',
3200 'coordinates' => [(float) $coords[0],
3201 (float) $coords[1]]];
3202 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3203 $status["georss:point"] = $item["coord"];
3213 * Returns the remaining number of API requests available to the user before the API limit is reached.
3215 * @param string $type Return type (atom, rss, xml, json)
3217 * @return array|string
3219 function api_account_rate_limit_status($type)
3221 if ($type == "xml") {
3223 'remaining-hits' => '150',
3224 '@attributes' => ["type" => "integer"],
3225 'hourly-limit' => '150',
3226 '@attributes2' => ["type" => "integer"],
3227 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3228 '@attributes3' => ["type" => "datetime"],
3229 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3230 '@attributes4' => ["type" => "integer"],
3234 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3235 'remaining_hits' => '150',
3236 'hourly_limit' => '150',
3237 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3241 return api_format_data('hash', $type, ['hash' => $hash]);
3244 /// @TODO move to top of file or somewhere better
3245 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3248 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3250 * @param string $type Return type (atom, rss, xml, json)
3252 * @return array|string
3254 function api_help_test($type)
3256 if ($type == 'xml') {
3262 return api_format_data('ok', $type, ["ok" => $ok]);
3265 /// @TODO move to top of file or somewhere better
3266 api_register_func('api/help/test', 'api_help_test', false);
3269 * Returns all lists the user subscribes to.
3271 * @param string $type Return type (atom, rss, xml, json)
3273 * @return array|string
3274 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3276 function api_lists_list($type)
3279 /// @TODO $ret is not filled here?
3280 return api_format_data('lists', $type, ["lists_list" => $ret]);
3283 /// @TODO move to top of file or somewhere better
3284 api_register_func('api/lists/list', 'api_lists_list', true);
3285 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3288 * Returns all groups the user owns.
3290 * @param string $type Return type (atom, rss, xml, json)
3292 * @return array|string
3293 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3295 function api_lists_ownerships($type)
3299 if (api_user() === false) {
3300 throw new ForbiddenException();
3304 $user_info = api_get_user($a);
3305 $uid = $user_info['uid'];
3307 $groups = dba::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3309 // loop through all groups
3311 foreach ($groups as $group) {
3312 if ($group['visible']) {
3318 'name' => $group['name'],
3319 'id' => intval($group['id']),
3320 'id_str' => (string) $group['id'],
3321 'user' => $user_info,
3325 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3328 /// @TODO move to top of file or somewhere better
3329 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3332 * Returns recent statuses from users in the specified group.
3334 * @param string $type Return type (atom, rss, xml, json)
3336 * @return array|string
3337 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3339 function api_lists_statuses($type)
3343 $user_info = api_get_user($a);
3344 if (api_user() === false || $user_info === false) {
3345 throw new ForbiddenException();
3348 unset($_REQUEST["user_id"]);
3349 unset($_GET["user_id"]);
3351 unset($_REQUEST["screen_name"]);
3352 unset($_GET["screen_name"]);
3354 if (empty($_REQUEST['list_id'])) {
3355 throw new BadRequestException('list_id not specified');
3359 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
3360 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
3364 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3365 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3366 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
3367 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
3369 $start = $page * $count;
3373 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
3375 if ($exclude_replies > 0) {
3376 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
3378 if ($conversation_id > 0) {
3379 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
3383 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
3384 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
3385 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
3386 `contact`.`id` AS `cid`, `group_member`.`gid`
3388 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
3389 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
3390 STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = `item`.`contact-id`
3391 WHERE `item`.`uid` = ? AND `verb` = ?
3392 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
3395 AND `group_member`.`gid` = ?
3396 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count),
3400 $_REQUEST['list_id']
3403 $items = api_format_items(dba::inArray($statuses), $user_info, false, $type);
3405 $data = ['status' => $items];
3409 $data = api_rss_extra($a, $data, $user_info);
3413 return api_format_data("statuses", $type, $data);
3416 /// @TODO move to top of file or somewhere better
3417 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3420 * Considers friends and followers lists to be private and won't return
3421 * anything if any user_id parameter is passed.
3423 * @brief Returns either the friends of the follower list
3425 * @param string $qtype Either "friends" or "followers"
3426 * @return boolean|array
3427 * @throws ForbiddenException
3429 function api_statuses_f($qtype)
3433 if (api_user() === false) {
3434 throw new ForbiddenException();
3438 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3439 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3443 $start = ($page - 1) * $count;
3445 $user_info = api_get_user($a);
3447 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3448 /* this is to stop Hotot to load friends multiple times
3449 * I'm not sure if I'm missing return something or
3450 * is a bug in hotot. Workaround, meantime
3454 return array('$users' => $ret);*/
3459 if ($qtype == 'friends') {
3460 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3461 } elseif ($qtype == 'followers') {
3462 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3465 // friends and followers only for self
3466 if ($user_info['self'] == 0) {
3467 $sql_extra = " AND false ";
3470 if ($qtype == 'blocks') {
3471 $sql_filter = 'AND `blocked` AND NOT `pending`';
3472 } elseif ($qtype == 'incoming') {
3473 $sql_filter = 'AND `pending`';
3475 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3493 foreach ($r as $cid) {
3494 $user = api_get_user($a, $cid['nurl']);
3495 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3496 unset($user["uid"]);
3497 unset($user["self"]);
3504 return ['user' => $ret];
3509 * Returns the user's friends.
3511 * @brief Returns the list of friends of the provided user
3513 * @deprecated By Twitter API in favor of friends/list
3515 * @param string $type Either "json" or "xml"
3516 * @return boolean|string|array
3518 function api_statuses_friends($type)
3520 $data = api_statuses_f("friends");
3521 if ($data === false) {
3524 return api_format_data("users", $type, $data);
3528 * Returns the user's followers.
3530 * @brief Returns the list of followers of the provided user
3532 * @deprecated By Twitter API in favor of friends/list
3534 * @param string $type Either "json" or "xml"
3535 * @return boolean|string|array
3537 function api_statuses_followers($type)
3539 $data = api_statuses_f("followers");
3540 if ($data === false) {
3543 return api_format_data("users", $type, $data);
3546 /// @TODO move to top of file or somewhere better
3547 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3548 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3551 * Returns the list of blocked users
3553 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3555 * @param string $type Either "json" or "xml"
3557 * @return boolean|string|array
3559 function api_blocks_list($type)
3561 $data = api_statuses_f('blocks');
3562 if ($data === false) {
3565 return api_format_data("users", $type, $data);
3568 /// @TODO move to top of file or somewhere better
3569 api_register_func('api/blocks/list', 'api_blocks_list', true);
3572 * Returns the list of pending users IDs
3574 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3576 * @param string $type Either "json" or "xml"
3578 * @return boolean|string|array
3580 function api_friendships_incoming($type)
3582 $data = api_statuses_f('incoming');
3583 if ($data === false) {
3588 foreach ($data['user'] as $user) {
3589 $ids[] = $user['id'];
3592 return api_format_data("ids", $type, ['id' => $ids]);
3595 /// @TODO move to top of file or somewhere better
3596 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3599 * Returns the instance's configuration information.
3601 * @param string $type Return type (atom, rss, xml, json)
3603 * @return array|string
3605 function api_statusnet_config($type)
3609 $name = $a->config['sitename'];
3610 $server = $a->get_hostname();
3611 $logo = System::baseUrl() . '/images/friendica-64.png';
3612 $email = $a->config['admin_email'];
3613 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3614 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3615 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3616 if ($a->config['api_import_size']) {
3617 $textlimit = (string) $a->config['api_import_size'];
3619 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3620 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3623 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3624 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3625 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3626 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3627 'shorturllength' => '30',
3629 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3630 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3631 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3632 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3637 return api_format_data('config', $type, ['config' => $config]);
3640 /// @TODO move to top of file or somewhere better
3641 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3642 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3646 * @param string $type Return type (atom, rss, xml, json)
3648 * @return array|string
3650 function api_statusnet_version($type)
3653 $fake_statusnet_version = "0.9.7";
3655 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3658 /// @TODO move to top of file or somewhere better
3659 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3660 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3664 * @param string $type Return type (atom, rss, xml, json)
3666 * @todo use api_format_data() to return data
3668 function api_ff_ids($type)
3671 throw new ForbiddenException();
3678 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3681 "SELECT `pcontact`.`id` FROM `contact`
3682 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3683 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3686 if (!DBM::is_result($r)) {
3691 foreach ($r as $rr) {
3692 if ($stringify_ids) {
3695 $ids[] = intval($rr['id']);
3699 return api_format_data("ids", $type, ['id' => $ids]);
3703 * Returns the ID of every user the user is following.
3705 * @param string $type Return type (atom, rss, xml, json)
3707 * @return array|string
3708 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3710 function api_friends_ids($type)
3712 return api_ff_ids($type);
3716 * Returns the ID of every user following the user.
3718 * @param string $type Return type (atom, rss, xml, json)
3720 * @return array|string
3721 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3723 function api_followers_ids($type)
3725 return api_ff_ids($type);
3728 /// @TODO move to top of file or somewhere better
3729 api_register_func('api/friends/ids', 'api_friends_ids', true);
3730 api_register_func('api/followers/ids', 'api_followers_ids', true);
3733 * Sends a new direct message.
3735 * @param string $type Return type (atom, rss, xml, json)
3737 * @return array|string
3738 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3740 function api_direct_messages_new($type)
3745 if (api_user() === false) {
3746 throw new ForbiddenException();
3749 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3753 $sender = api_get_user($a);
3755 if ($_POST['screen_name']) {
3757 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3759 dbesc($_POST['screen_name'])
3762 // Selecting the id by priority, friendica first
3763 api_best_nickname($r);
3765 $recipient = api_get_user($a, $r[0]['nurl']);
3767 $recipient = api_get_user($a, $_POST['user_id']);
3772 if (x($_REQUEST, 'replyto')) {
3774 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3776 intval($_REQUEST['replyto'])
3778 $replyto = $r[0]['parent-uri'];
3779 $sub = $r[0]['title'];
3781 if (x($_REQUEST, 'title')) {
3782 $sub = $_REQUEST['title'];
3784 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3788 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3791 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3792 $ret = api_format_messages($r[0], $recipient, $sender);
3794 $ret = ["error"=>$id];
3797 $data = ['direct_message'=>$ret];
3802 $data = api_rss_extra($a, $data, $sender);
3805 return api_format_data("direct-messages", $type, $data);
3808 /// @TODO move to top of file or somewhere better
3809 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3812 * Destroys a direct message.
3814 * @brief delete a direct_message from mail table through api
3816 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3817 * @return string|array
3818 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3820 function api_direct_messages_destroy($type)
3824 if (api_user() === false) {
3825 throw new ForbiddenException();
3829 $user_info = api_get_user($a);
3831 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3833 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3834 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3835 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3837 $uid = $user_info['uid'];
3838 // error if no id or parenturi specified (for clients posting parent-uri as well)
3839 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3840 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3841 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3844 // BadRequestException if no id specified (for clients using Twitter API)
3846 throw new BadRequestException('Message id not specified');
3849 // add parent-uri to sql command if specified by calling app
3850 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3852 // get data of the specified message id
3854 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3859 // error message if specified id is not in database
3860 if (!DBM::is_result($r)) {
3861 if ($verbose == "true") {
3862 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3863 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3865 /// @todo BadRequestException ok for Twitter API clients?
3866 throw new BadRequestException('message id not in database');
3871 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3876 if ($verbose == "true") {
3879 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3880 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3882 $answer = ['result' => 'error', 'message' => 'unknown error'];
3883 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3886 /// @todo return JSON data like Twitter API not yet implemented
3889 /// @TODO move to top of file or somewhere better
3890 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3894 * @param string $type Return type (atom, rss, xml, json)
3895 * @param string $box
3896 * @param string $verbose
3898 * @return array|string
3900 function api_direct_messages_box($type, $box, $verbose)
3903 $user_info = api_get_user($a);
3905 if (api_user() === false || $user_info === false) {
3906 throw new ForbiddenException();
3910 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3911 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3916 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3917 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3919 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3920 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3923 unset($_REQUEST["user_id"]);
3924 unset($_GET["user_id"]);
3926 unset($_REQUEST["screen_name"]);
3927 unset($_GET["screen_name"]);
3929 $profile_url = $user_info["url"];
3932 $start = $page * $count;
3937 if ($box=="sentbox") {
3938 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3939 } elseif ($box == "conversation") {
3940 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3941 } elseif ($box == "all") {
3942 $sql_extra = "true";
3943 } elseif ($box == "inbox") {
3944 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3948 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3951 if ($user_id != "") {
3952 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3953 } elseif ($screen_name !="") {
3954 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3958 "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",
3964 if ($verbose == "true" && !DBM::is_result($r)) {
3965 $answer = ['result' => 'error', 'message' => 'no mails available'];
3966 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3970 foreach ($r as $item) {
3971 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3972 $recipient = $user_info;
3973 $sender = api_get_user($a, normalise_link($item['contact-url']));
3974 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3975 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3976 $sender = $user_info;
3979 if (isset($recipient) && isset($sender)) {
3980 $ret[] = api_format_messages($item, $recipient, $sender);
3985 $data = ['direct_message' => $ret];
3989 $data = api_rss_extra($a, $data, $user_info);
3992 return api_format_data("direct-messages", $type, $data);
3996 * Returns the most recent direct messages sent by the user.
3998 * @param string $type Return type (atom, rss, xml, json)
4000 * @return array|string
4001 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4003 function api_direct_messages_sentbox($type)
4005 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
4006 return api_direct_messages_box($type, "sentbox", $verbose);
4010 * Returns the most recent direct messages sent to the user.
4012 * @param string $type Return type (atom, rss, xml, json)
4014 * @return array|string
4015 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4017 function api_direct_messages_inbox($type)
4019 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
4020 return api_direct_messages_box($type, "inbox", $verbose);
4025 * @param string $type Return type (atom, rss, xml, json)
4027 * @return array|string
4029 function api_direct_messages_all($type)
4031 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
4032 return api_direct_messages_box($type, "all", $verbose);
4037 * @param string $type Return type (atom, rss, xml, json)
4039 * @return array|string
4041 function api_direct_messages_conversation($type)
4043 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
4044 return api_direct_messages_box($type, "conversation", $verbose);
4047 /// @TODO move to top of file or somewhere better
4048 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4049 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4050 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4051 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4054 * Returns an OAuth Request Token.
4056 * @see https://oauth.net/core/1.0/#auth_step1
4058 function api_oauth_request_token()
4060 $oauth1 = new FKOAuth1();
4062 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4063 } catch (Exception $e) {
4064 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4072 * Returns an OAuth Access Token.
4074 * @return array|string
4075 * @see https://oauth.net/core/1.0/#auth_step3
4077 function api_oauth_access_token()
4079 $oauth1 = new FKOAuth1();
4081 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4082 } catch (Exception $e) {
4083 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4090 /// @TODO move to top of file or somewhere better
4091 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4092 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4096 * @brief delete a complete photoalbum with all containing photos from database through api
4098 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4099 * @return string|array
4101 function api_fr_photoalbum_delete($type)
4103 if (api_user() === false) {
4104 throw new ForbiddenException();
4107 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
4109 // we do not allow calls without album string
4111 throw new BadRequestException("no albumname specified");
4113 // check if album is existing
4115 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4119 if (!DBM::is_result($r)) {
4120 throw new BadRequestException("album not available");
4123 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4124 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4125 foreach ($r as $rr) {
4127 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4128 intval(local_user()),
4129 dbesc($rr['resource-id'])
4132 if (!DBM::is_result($photo_item)) {
4133 throw new InternalServerErrorException("problem with deleting items occured");
4135 Item::deleteById($photo_item[0]['id']);
4138 // now let's delete all photos from the album
4139 $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
4141 // return success of deletion or error message
4143 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4144 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4146 throw new InternalServerErrorException("unknown error - deleting from database failed");
4151 * @brief update the name of the album for all photos of an album
4153 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4154 * @return string|array
4156 function api_fr_photoalbum_update($type)
4158 if (api_user() === false) {
4159 throw new ForbiddenException();
4162 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
4163 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
4165 // we do not allow calls without album string
4167 throw new BadRequestException("no albumname specified");
4169 if ($album_new == "") {
4170 throw new BadRequestException("no new albumname specified");
4172 // check if album is existing
4174 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4178 if (!DBM::is_result($r)) {
4179 throw new BadRequestException("album not available");
4181 // now let's update all photos to the albumname
4183 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
4189 // return success of updating or error message
4191 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4192 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4194 throw new InternalServerErrorException("unknown error - updating in database failed");
4200 * @brief list all photos of the authenticated user
4202 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4203 * @return string|array
4205 function api_fr_photos_list($type)
4207 if (api_user() === false) {
4208 throw new ForbiddenException();
4211 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4212 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4213 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4214 intval(local_user())
4217 'image/jpeg' => 'jpg',
4218 'image/png' => 'png',
4219 'image/gif' => 'gif'
4221 $data = ['photo'=>[]];
4222 if (DBM::is_result($r)) {
4223 foreach ($r as $rr) {
4225 $photo['id'] = $rr['resource-id'];
4226 $photo['album'] = $rr['album'];
4227 $photo['filename'] = $rr['filename'];
4228 $photo['type'] = $rr['type'];
4229 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4230 $photo['created'] = $rr['created'];
4231 $photo['edited'] = $rr['edited'];
4232 $photo['desc'] = $rr['desc'];
4234 if ($type == "xml") {
4235 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4237 $photo['thumb'] = $thumb;
4238 $data['photo'][] = $photo;
4242 return api_format_data("photos", $type, $data);
4246 * @brief upload a new photo or change an existing photo
4248 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4249 * @return string|array
4251 function api_fr_photo_create_update($type)
4253 if (api_user() === false) {
4254 throw new ForbiddenException();
4257 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4258 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4259 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4260 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4261 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4262 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4263 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4264 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4265 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4267 // do several checks on input parameters
4268 // we do not allow calls without album string
4269 if ($album == null) {
4270 throw new BadRequestException("no albumname specified");
4272 // if photo_id == null --> we are uploading a new photo
4273 if ($photo_id == null) {
4276 // error if no media posted in create-mode
4277 if (!x($_FILES, 'media')) {
4279 throw new BadRequestException("no media data submitted");
4282 // album_new will be ignored in create-mode
4287 // check if photo is existing in database
4289 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4294 if (!DBM::is_result($r)) {
4295 throw new BadRequestException("photo not available");
4299 // checks on acl strings provided by clients
4300 $acl_input_error = false;
4301 $acl_input_error |= check_acl_input($allow_cid);
4302 $acl_input_error |= check_acl_input($deny_cid);
4303 $acl_input_error |= check_acl_input($allow_gid);
4304 $acl_input_error |= check_acl_input($deny_gid);
4305 if ($acl_input_error) {
4306 throw new BadRequestException("acl data invalid");
4308 // now let's upload the new media in create-mode
4309 if ($mode == "create") {
4310 $media = $_FILES['media'];
4311 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4313 // return success of updating or error message
4314 if (!is_null($data)) {
4315 return api_format_data("photo_create", $type, $data);
4317 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4321 // now let's do the changes in update-mode
4322 if ($mode == "update") {
4325 if (!is_null($desc)) {
4326 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4329 if (!is_null($album_new)) {
4330 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4333 if (!is_null($allow_cid)) {
4334 $allow_cid = trim($allow_cid);
4335 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4338 if (!is_null($deny_cid)) {
4339 $deny_cid = trim($deny_cid);
4340 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4343 if (!is_null($allow_gid)) {
4344 $allow_gid = trim($allow_gid);
4345 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4348 if (!is_null($deny_gid)) {
4349 $deny_gid = trim($deny_gid);
4350 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4354 if ($sql_extra != "") {
4355 $nothingtodo = false;
4357 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4359 DateTimeFormat::utcNow(), // update edited timestamp
4365 $nothingtodo = true;
4368 if (x($_FILES, 'media')) {
4369 $nothingtodo = false;
4370 $media = $_FILES['media'];
4371 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4372 if (!is_null($data)) {
4373 return api_format_data("photo_update", $type, $data);
4377 // return success of updating or error message
4379 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4380 return api_format_data("photo_update", $type, ['$result' => $answer]);
4383 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4384 return api_format_data("photo_update", $type, ['$result' => $answer]);
4386 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4389 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4394 * @brief delete a single photo from the database through api
4396 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4397 * @return string|array
4399 function api_fr_photo_delete($type)
4401 if (api_user() === false) {
4402 throw new ForbiddenException();
4405 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4407 // do several checks on input parameters
4408 // we do not allow calls without photo id
4409 if ($photo_id == null) {
4410 throw new BadRequestException("no photo_id specified");
4412 // check if photo is existing in database
4414 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4418 if (!DBM::is_result($r)) {
4419 throw new BadRequestException("photo not available");
4421 // now we can perform on the deletion of the photo
4422 $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4424 // return success of deletion or error message
4426 // retrieve the id of the parent element (the photo element)
4428 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4429 intval(local_user()),
4433 if (!DBM::is_result($photo_item)) {
4434 throw new InternalServerErrorException("problem with deleting items occured");
4436 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4437 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4438 Item::deleteById($photo_item[0]['id']);
4440 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4441 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4443 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4449 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4451 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4452 * @return string|array
4454 function api_fr_photo_detail($type)
4456 if (api_user() === false) {
4457 throw new ForbiddenException();
4459 if (!x($_REQUEST, 'photo_id')) {
4460 throw new BadRequestException("No photo id.");
4463 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4464 $photo_id = $_REQUEST['photo_id'];
4466 // prepare json/xml output with data from database for the requested photo
4467 $data = prepare_photo_data($type, $scale, $photo_id);
4469 return api_format_data("photo_detail", $type, $data);
4474 * Updates the user’s profile image.
4476 * @brief updates the profile image for the user (either a specified profile or the default profile)
4478 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4480 * @return string|array
4481 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4483 function api_account_update_profile_image($type)
4485 if (api_user() === false) {
4486 throw new ForbiddenException();
4489 $profileid = defaults($_REQUEST, 'profile_id', 0);
4491 // error if image data is missing
4492 if (!x($_FILES, 'image')) {
4493 throw new BadRequestException("no media data submitted");
4496 // check if specified profile id is valid
4497 if ($profileid != 0) {
4499 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4503 // error message if specified profile id is not in database
4504 if (!DBM::is_result($r)) {
4505 throw new BadRequestException("profile_id not available");
4507 $is_default_profile = $r['profile'];
4509 $is_default_profile = 1;
4512 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4514 if (x($_FILES, 'image')) {
4515 $media = $_FILES['image'];
4516 } elseif (x($_FILES, 'media')) {
4517 $media = $_FILES['media'];
4519 // save new profile image
4520 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4523 if (is_array($media['type'])) {
4524 $filetype = $media['type'][0];
4526 $filetype = $media['type'];
4528 if ($filetype == "image/jpeg") {
4530 } elseif ($filetype == "image/png") {
4533 throw new InternalServerErrorException('Unsupported filetype');
4535 // change specified profile or all profiles to the new resource-id
4536 if ($is_default_profile) {
4538 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4539 dbesc($data['photo']['id']),
4540 intval(local_user())
4544 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
4545 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4546 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4547 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4548 intval(local_user())
4552 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4553 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4554 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4555 intval($_REQUEST['profile']),
4556 intval(local_user())
4560 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4561 // so that browsers will do a cache update unconditionally
4564 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4565 dbesc(DateTimeFormat::utcNow()),
4566 intval(local_user())
4569 // Update global directory in background
4570 //$user = api_get_user(get_app());
4571 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4572 if ($url && strlen(Config::get('system', 'directory'))) {
4573 Worker::add(PRIORITY_LOW, "Directory", $url);
4576 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4578 // output for client
4580 return api_account_verify_credentials($type);
4582 // SaveMediaToDatabase failed for some reason
4583 throw new InternalServerErrorException("image upload failed");
4587 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4588 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4589 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4590 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4591 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4592 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4593 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4594 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4595 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4598 * Update user profile
4600 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4602 * @return array|string
4604 function api_account_update_profile($type)
4606 $local_user = api_user();
4607 $api_user = api_get_user(get_app());
4609 if (!empty($_POST['name'])) {
4610 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4611 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4612 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4613 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4616 if (isset($_POST['description'])) {
4617 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4618 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4619 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4622 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4623 // Update global directory in background
4624 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4625 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4628 return api_account_verify_credentials($type);
4631 /// @TODO move to top of file or somewhere better
4632 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4636 * @param string $acl_string
4638 function check_acl_input($acl_string)
4640 if ($acl_string == null || $acl_string == " ") {
4643 $contact_not_found = false;
4645 // split <x><y><z> into array of cid's
4646 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4648 // check for each cid if it is available on server
4649 $cid_array = $array[0];
4650 foreach ($cid_array as $cid) {
4651 $cid = str_replace("<", "", $cid);
4652 $cid = str_replace(">", "", $cid);
4654 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4658 $contact_not_found |= !DBM::is_result($contact);
4660 return $contact_not_found;
4665 * @param string $mediatype
4666 * @param array $media
4667 * @param string $type
4668 * @param string $album
4669 * @param string $allow_cid
4670 * @param string $deny_cid
4671 * @param string $allow_gid
4672 * @param string $deny_gid
4673 * @param string $desc
4674 * @param integer $profile
4675 * @param boolean $visibility
4676 * @param string $photo_id
4678 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)
4686 if (is_array($media)) {
4687 if (is_array($media['tmp_name'])) {
4688 $src = $media['tmp_name'][0];
4690 $src = $media['tmp_name'];
4692 if (is_array($media['name'])) {
4693 $filename = basename($media['name'][0]);
4695 $filename = basename($media['name']);
4697 if (is_array($media['size'])) {
4698 $filesize = intval($media['size'][0]);
4700 $filesize = intval($media['size']);
4702 if (is_array($media['type'])) {
4703 $filetype = $media['type'][0];
4705 $filetype = $media['type'];
4709 if ($filetype == "") {
4710 $filetype=Image::guessType($filename);
4712 $imagedata = getimagesize($src);
4714 $filetype = $imagedata['mime'];
4717 "File upload src: " . $src . " - filename: " . $filename .
4718 " - size: " . $filesize . " - type: " . $filetype,
4722 // check if there was a php upload error
4723 if ($filesize == 0 && $media['error'] == 1) {
4724 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4726 // check against max upload size within Friendica instance
4727 $maximagesize = Config::get('system', 'maximagesize');
4728 if ($maximagesize && ($filesize > $maximagesize)) {
4729 $formattedBytes = formatBytes($maximagesize);
4730 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4733 // create Photo instance with the data of the image
4734 $imagedata = @file_get_contents($src);
4735 $Image = new Image($imagedata, $filetype);
4736 if (! $Image->isValid()) {
4737 throw new InternalServerErrorException("unable to process image data");
4740 // check orientation of image
4741 $Image->orient($src);
4744 // check max length of images on server
4745 $max_length = Config::get('system', 'max_image_length');
4746 if (! $max_length) {
4747 $max_length = MAX_IMAGE_LENGTH;
4749 if ($max_length > 0) {
4750 $Image->scaleDown($max_length);
4751 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4753 $width = $Image->getWidth();
4754 $height = $Image->getHeight();
4756 // create a new resource-id if not already provided
4757 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4759 if ($mediatype == "photo") {
4760 // upload normal image (scales 0, 1, 2)
4761 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4763 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4765 logger("photo upload: image upload with scale 0 (original size) failed");
4767 if ($width > 640 || $height > 640) {
4768 $Image->scaleDown(640);
4769 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4771 logger("photo upload: image upload with scale 1 (640x640) failed");
4775 if ($width > 320 || $height > 320) {
4776 $Image->scaleDown(320);
4777 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4779 logger("photo upload: image upload with scale 2 (320x320) failed");
4782 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4783 } elseif ($mediatype == "profileimage") {
4784 // upload profile image (scales 4, 5, 6)
4785 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4787 if ($width > 175 || $height > 175) {
4788 $Image->scaleDown(175);
4789 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4791 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4795 if ($width > 80 || $height > 80) {
4796 $Image->scaleDown(80);
4797 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4799 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4803 if ($width > 48 || $height > 48) {
4804 $Image->scaleDown(48);
4805 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4807 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4810 $Image->__destruct();
4811 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4814 if (isset($r) && $r) {
4815 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4816 if ($photo_id == null && $mediatype == "photo") {
4817 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4819 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4820 return prepare_photo_data($type, false, $hash);
4822 throw new InternalServerErrorException("image upload failed");
4828 * @param string $hash
4829 * @param string $allow_cid
4830 * @param string $deny_cid
4831 * @param string $allow_gid
4832 * @param string $deny_gid
4833 * @param string $filetype
4834 * @param boolean $visibility
4836 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4838 // get data about the api authenticated user
4839 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4840 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4843 $arr['guid'] = get_guid(32);
4844 $arr['uid'] = intval(api_user());
4846 $arr['parent-uri'] = $uri;
4847 $arr['type'] = 'photo';
4849 $arr['resource-id'] = $hash;
4850 $arr['contact-id'] = $owner_record[0]['id'];
4851 $arr['owner-name'] = $owner_record[0]['name'];
4852 $arr['owner-link'] = $owner_record[0]['url'];
4853 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4854 $arr['author-name'] = $owner_record[0]['name'];
4855 $arr['author-link'] = $owner_record[0]['url'];
4856 $arr['author-avatar'] = $owner_record[0]['thumb'];
4858 $arr['allow_cid'] = $allow_cid;
4859 $arr['allow_gid'] = $allow_gid;
4860 $arr['deny_cid'] = $deny_cid;
4861 $arr['deny_gid'] = $deny_gid;
4862 $arr['visible'] = $visibility;
4866 'image/jpeg' => 'jpg',
4867 'image/png' => 'png',
4868 'image/gif' => 'gif'
4871 // adds link to the thumbnail scale photo
4872 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4873 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4876 // do the magic for storing the item in the database and trigger the federation to other contacts
4882 * @param string $type
4884 * @param string $photo_id
4888 function prepare_photo_data($type, $scale, $photo_id)
4891 $user_info = api_get_user($a);
4893 if ($user_info === false) {
4894 throw new ForbiddenException();
4897 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4898 $data_sql = ($scale === false ? "" : "data, ");
4900 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4901 // clients needs to convert this in their way for further processing
4903 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4904 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4905 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4906 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4908 intval(local_user()),
4914 'image/jpeg' => 'jpg',
4915 'image/png' => 'png',
4916 'image/gif' => 'gif'
4919 // prepare output data for photo
4920 if (DBM::is_result($r)) {
4921 $data = ['photo' => $r[0]];
4922 $data['photo']['id'] = $data['photo']['resource-id'];
4923 if ($scale !== false) {
4924 $data['photo']['data'] = base64_encode($data['photo']['data']);
4926 unset($data['photo']['datasize']); //needed only with scale param
4928 if ($type == "xml") {
4929 $data['photo']['links'] = [];
4930 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4931 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4933 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4936 $data['photo']['link'] = [];
4937 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4939 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4940 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4944 unset($data['photo']['resource-id']);
4945 unset($data['photo']['minscale']);
4946 unset($data['photo']['maxscale']);
4948 throw new NotFoundException();
4951 // retrieve item element for getting activities (like, dislike etc.) related to photo
4953 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4954 intval(local_user()),
4957 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4959 // retrieve comments on photo
4961 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4962 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4963 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4964 `contact`.`id` AS `cid`
4966 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4967 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4968 WHERE `item`.`parent` = %d AND `item`.`visible`
4969 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4970 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4971 intval($item[0]['parent']),
4973 dbesc(ACTIVITY_POST)
4976 // prepare output of comments
4977 $commentData = api_format_items($r, $user_info, false, $type);
4979 if ($type == "xml") {
4981 foreach ($commentData as $comment) {
4982 $comments[$k++ . ":comment"] = $comment;
4985 foreach ($commentData as $comment) {
4986 $comments[] = $comment;
4989 $data['photo']['friendica_comments'] = $comments;
4991 // include info if rights on photo and rights on item are mismatching
4992 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4993 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4994 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4995 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4996 $data['photo']['rights_mismatch'] = $rights_mismatch;
5003 * Similar as /mod/redir.php
5004 * redirect to 'url' after dfrn auth
5006 * Why this when there is mod/redir.php already?
5007 * This use api_user() and api_login()
5010 * c_url: url of remote contact to auth to
5011 * url: string, url to redirect after auth
5013 function api_friendica_remoteauth()
5015 $url = (x($_GET, 'url') ? $_GET['url'] : '');
5016 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
5018 if ($url === '' || $c_url === '') {
5019 throw new BadRequestException("Wrong parameters.");
5022 $c_url = normalise_link($c_url);
5026 $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5028 if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
5029 throw new BadRequestException("Unknown contact");
5032 $cid = $contact['id'];
5034 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
5036 if ($contact['duplex'] && $contact['issued-id']) {
5037 $orig_id = $contact['issued-id'];
5038 $dfrn_id = '1:' . $orig_id;
5040 if ($contact['duplex'] && $contact['dfrn-id']) {
5041 $orig_id = $contact['dfrn-id'];
5042 $dfrn_id = '0:' . $orig_id;
5045 $sec = random_string();
5048 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
5049 VALUES( %d, %s, '%s', '%s', %d )",
5057 logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
5058 $dest = ($url ? '&destination_url=' . $url : '');
5060 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5061 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5062 . '&type=profile&sec=' . $sec . $dest
5065 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5068 * @brief Return the item shared, if the item contains only the [share] tag
5070 * @param array $item Sharer item
5071 * @return array|false Shared item or false if not a reshare
5073 function api_share_as_retweet(&$item)
5075 $body = trim($item["body"]);
5077 if (Diaspora::isReshare($body, false)===false) {
5081 /// @TODO "$1" should maybe mean '$1' ?
5082 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
5084 * Skip if there is no shared message in there
5085 * we already checked this in diaspora::isReshare()
5086 * but better one more than one less...
5088 if ($body == $attributes) {
5093 // build the fake reshared item
5094 $reshared_item = $item;
5097 preg_match("/author='(.*?)'/ism", $attributes, $matches);
5098 if ($matches[1] != "") {
5099 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
5102 preg_match('/author="(.*?)"/ism', $attributes, $matches);
5103 if ($matches[1] != "") {
5104 $author = $matches[1];
5108 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
5109 if ($matches[1] != "") {
5110 $profile = $matches[1];
5113 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
5114 if ($matches[1] != "") {
5115 $profile = $matches[1];
5119 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
5120 if ($matches[1] != "") {
5121 $avatar = $matches[1];
5124 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
5125 if ($matches[1] != "") {
5126 $avatar = $matches[1];
5130 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5131 if ($matches[1] != "") {
5132 $link = $matches[1];
5135 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5136 if ($matches[1] != "") {
5137 $link = $matches[1];
5141 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5142 if ($matches[1] != "") {
5143 $posted = $matches[1];
5146 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5147 if ($matches[1] != "") {
5148 $posted = $matches[1];
5151 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5153 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5157 $reshared_item["body"] = $shared_body;
5158 $reshared_item["author-name"] = $author;
5159 $reshared_item["author-link"] = $profile;
5160 $reshared_item["author-avatar"] = $avatar;
5161 $reshared_item["plink"] = $link;
5162 $reshared_item["created"] = $posted;
5163 $reshared_item["edited"] = $posted;
5165 return $reshared_item;
5170 * @param string $profile
5172 * @return string|false
5173 * @todo remove trailing junk from profile url
5174 * @todo pump.io check has to check the website
5176 function api_get_nick($profile)
5181 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5182 dbesc(normalise_link($profile))
5185 if (DBM::is_result($r)) {
5186 $nick = $r[0]["nick"];
5191 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5192 dbesc(normalise_link($profile))
5195 if (DBM::is_result($r)) {
5196 $nick = $r[0]["nick"];
5201 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5202 if ($friendica != $profile) {
5208 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5209 if ($diaspora != $profile) {
5215 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5216 if ($twitter != $profile) {
5223 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5224 if ($StatusnetHost != $profile) {
5225 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5226 if ($StatusnetUser != $profile) {
5227 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5228 $user = json_decode($UserData);
5230 $nick = $user->screen_name;
5236 // To-Do: look at the page if its really a pumpio site
5237 //if (!$nick == "") {
5238 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5239 // if ($pumpio != $profile)
5241 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5254 * @param array $item
5258 function api_in_reply_to($item)
5262 $in_reply_to['status_id'] = null;
5263 $in_reply_to['user_id'] = null;
5264 $in_reply_to['status_id_str'] = null;
5265 $in_reply_to['user_id_str'] = null;
5266 $in_reply_to['screen_name'] = null;
5268 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5270 "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
5271 intval($item['uid']),
5272 dbesc($item['thr-parent'])
5275 if (DBM::is_result($r)) {
5276 $in_reply_to['status_id'] = intval($r[0]['id']);
5278 $in_reply_to['status_id'] = intval($item['parent']);
5281 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5284 "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
5285 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
5286 WHERE `item`.`id` = %d LIMIT 1",
5287 intval($in_reply_to['status_id'])
5290 if (DBM::is_result($r)) {
5291 if ($r[0]['nick'] == "") {
5292 $r[0]['nick'] = api_get_nick($r[0]["url"]);
5295 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
5296 $in_reply_to['user_id'] = intval($r[0]['id']);
5297 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
5300 // There seems to be situation, where both fields are identical:
5301 // https://github.com/friendica/friendica/issues/1010
5302 // This is a bugfix for that.
5303 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5304 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
5305 $in_reply_to['status_id'] = null;
5306 $in_reply_to['user_id'] = null;
5307 $in_reply_to['status_id_str'] = null;
5308 $in_reply_to['user_id_str'] = null;
5309 $in_reply_to['screen_name'] = null;
5313 return $in_reply_to;
5318 * @param string $Text
5322 function api_clean_plain_items($Text)
5324 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5326 $Text = BBCode::cleanPictureLinks($Text);
5327 $URLSearchString = "^\[\]";
5329 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
5331 if ($include_entities == "true") {
5332 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
5335 // Simplify "attachment" element
5336 $Text = api_clean_attachments($Text);
5342 * @brief Removes most sharing information for API text export
5344 * @param string $body The original body
5346 * @return string Cleaned body
5348 function api_clean_attachments($body)
5350 $data = BBCode::getAttachmentData($body);
5357 if (isset($data["text"])) {
5358 $body = $data["text"];
5360 if (($body == "") && isset($data["title"])) {
5361 $body = $data["title"];
5363 if (isset($data["url"])) {
5364 $body .= "\n".$data["url"];
5366 $body .= $data["after"];
5373 * @param array $contacts
5377 function api_best_nickname(&$contacts)
5381 if (count($contacts) == 0) {
5385 foreach ($contacts as $contact) {
5386 if ($contact["network"] == "") {
5387 $contact["network"] = "dfrn";
5388 $best_contact = [$contact];
5392 if (sizeof($best_contact) == 0) {
5393 foreach ($contacts as $contact) {
5394 if ($contact["network"] == "dfrn") {
5395 $best_contact = [$contact];
5400 if (sizeof($best_contact) == 0) {
5401 foreach ($contacts as $contact) {
5402 if ($contact["network"] == "dspr") {
5403 $best_contact = [$contact];
5408 if (sizeof($best_contact) == 0) {
5409 foreach ($contacts as $contact) {
5410 if ($contact["network"] == "stat") {
5411 $best_contact = [$contact];
5416 if (sizeof($best_contact) == 0) {
5417 foreach ($contacts as $contact) {
5418 if ($contact["network"] == "pump") {
5419 $best_contact = [$contact];
5424 if (sizeof($best_contact) == 0) {
5425 foreach ($contacts as $contact) {
5426 if ($contact["network"] == "twit") {
5427 $best_contact = [$contact];
5432 if (sizeof($best_contact) == 1) {
5433 $contacts = $best_contact;
5435 $contacts = [$contacts[0]];
5440 * Return all or a specified group of the user with the containing contacts.
5442 * @param string $type Return type (atom, rss, xml, json)
5444 * @return array|string
5446 function api_friendica_group_show($type)
5450 if (api_user() === false) {
5451 throw new ForbiddenException();
5455 $user_info = api_get_user($a);
5456 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5457 $uid = $user_info['uid'];
5459 // get data of the specified group id or all groups if not specified
5462 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5466 // error message if specified gid is not in database
5467 if (!DBM::is_result($r)) {
5468 throw new BadRequestException("gid not available");
5472 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5477 // loop through all groups and retrieve all members for adding data in the user array
5479 foreach ($r as $rr) {
5480 $members = Contact::getByGroupId($rr['id']);
5483 if ($type == "xml") {
5484 $user_element = "users";
5486 foreach ($members as $member) {
5487 $user = api_get_user($a, $member['nurl']);
5488 $users[$k++.":user"] = $user;
5491 $user_element = "user";
5492 foreach ($members as $member) {
5493 $user = api_get_user($a, $member['nurl']);
5497 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5499 return api_format_data("groups", $type, ['group' => $grps]);
5501 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5505 * Delete the specified group of the user.
5507 * @param string $type Return type (atom, rss, xml, json)
5509 * @return array|string
5511 function api_friendica_group_delete($type)
5515 if (api_user() === false) {
5516 throw new ForbiddenException();
5520 $user_info = api_get_user($a);
5521 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5522 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5523 $uid = $user_info['uid'];
5525 // error if no gid specified
5526 if ($gid == 0 || $name == "") {
5527 throw new BadRequestException('gid or name not specified');
5530 // get data of the specified group id
5532 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5536 // error message if specified gid is not in database
5537 if (!DBM::is_result($r)) {
5538 throw new BadRequestException('gid not available');
5541 // get data of the specified group id and group name
5543 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5548 // error message if specified gid is not in database
5549 if (!DBM::is_result($rname)) {
5550 throw new BadRequestException('wrong group name');
5554 $ret = Group::removeByName($uid, $name);
5557 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5558 return api_format_data("group_delete", $type, ['result' => $success]);
5560 throw new BadRequestException('other API error');
5563 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5568 * @param string $type Return type (atom, rss, xml, json)
5570 * @return array|string
5571 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5573 function api_lists_destroy($type)
5577 if (api_user() === false) {
5578 throw new ForbiddenException();
5582 $user_info = api_get_user($a);
5583 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
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::remove($gid)) {
5600 'name' => $group['name'],
5601 'id' => intval($gid),
5602 'id_str' => (string) $gid,
5603 'user' => $user_info
5606 return api_format_data("lists", $type, ['lists' => $list]);
5609 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5612 * Add a new group to the database.
5614 * @param string $name Group name
5615 * @param int $uid User ID
5616 * @param array $users List of users to add to the group
5620 function group_create($name, $uid, $users = [])
5622 // error if no name specified
5624 throw new BadRequestException('group name not specified');
5627 // get data of the specified group name
5629 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5633 // error message if specified group name already exists
5634 if (DBM::is_result($rname)) {
5635 throw new BadRequestException('group name already exists');
5638 // check if specified group name is a deleted group
5640 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5644 // error message if specified group name already exists
5645 if (DBM::is_result($rname)) {
5646 $reactivate_group = true;
5650 $ret = Group::create($uid, $name);
5652 $gid = Group::getIdByName($uid, $name);
5654 throw new BadRequestException('other API error');
5658 $erroraddinguser = false;
5660 foreach ($users as $user) {
5661 $cid = $user['cid'];
5662 // check if user really exists as contact
5664 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5668 if (count($contact)) {
5669 Group::addMember($gid, $cid);
5671 $erroraddinguser = true;
5672 $errorusers[] = $cid;
5676 // return success message incl. missing users in array
5677 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5679 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5683 * Create the specified group with the posted array of contacts.
5685 * @param string $type Return type (atom, rss, xml, json)
5687 * @return array|string
5689 function api_friendica_group_create($type)
5693 if (api_user() === false) {
5694 throw new ForbiddenException();
5698 $user_info = api_get_user($a);
5699 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5700 $uid = $user_info['uid'];
5701 $json = json_decode($_POST['json'], true);
5702 $users = $json['user'];
5704 $success = group_create($name, $uid, $users);
5706 return api_format_data("group_create", $type, ['result' => $success]);
5708 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5711 * Create a new group.
5713 * @param string $type Return type (atom, rss, xml, json)
5715 * @return array|string
5716 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5718 function api_lists_create($type)
5722 if (api_user() === false) {
5723 throw new ForbiddenException();
5727 $user_info = api_get_user($a);
5728 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5729 $uid = $user_info['uid'];
5731 $success = group_create($name, $uid);
5732 if ($success['success']) {
5734 'name' => $success['name'],
5735 'id' => intval($success['gid']),
5736 'id_str' => (string) $success['gid'],
5737 'user' => $user_info
5740 return api_format_data("lists", $type, ['lists'=>$grp]);
5743 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5746 * Update the specified group with the posted array of contacts.
5748 * @param string $type Return type (atom, rss, xml, json)
5750 * @return array|string
5752 function api_friendica_group_update($type)
5756 if (api_user() === false) {
5757 throw new ForbiddenException();
5761 $user_info = api_get_user($a);
5762 $uid = $user_info['uid'];
5763 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5764 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5765 $json = json_decode($_POST['json'], true);
5766 $users = $json['user'];
5768 // error if no name specified
5770 throw new BadRequestException('group name not specified');
5773 // error if no gid specified
5775 throw new BadRequestException('gid not specified');
5779 $members = Contact::getByGroupId($gid);
5780 foreach ($members as $member) {
5781 $cid = $member['id'];
5782 foreach ($users as $user) {
5783 $found = ($user['cid'] == $cid ? true : false);
5785 if (!isset($found) || !$found) {
5786 Group::removeMemberByName($uid, $name, $cid);
5791 $erroraddinguser = false;
5793 foreach ($users as $user) {
5794 $cid = $user['cid'];
5795 // check if user really exists as contact
5797 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5802 if (count($contact)) {
5803 Group::addMember($gid, $cid);
5805 $erroraddinguser = true;
5806 $errorusers[] = $cid;
5810 // return success message incl. missing users in array
5811 $status = ($erroraddinguser ? "missing user" : "ok");
5812 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5813 return api_format_data("group_update", $type, ['result' => $success]);
5816 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5819 * Update information about a group.
5821 * @param string $type Return type (atom, rss, xml, json)
5823 * @return array|string
5824 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5826 function api_lists_update($type)
5830 if (api_user() === false) {
5831 throw new ForbiddenException();
5835 $user_info = api_get_user($a);
5836 $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5837 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5838 $uid = $user_info['uid'];
5840 // error if no gid specified
5842 throw new BadRequestException('gid not specified');
5845 // get data of the specified group id
5846 $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5847 // error message if specified gid is not in database
5849 throw new BadRequestException('gid not available');
5852 if (Group::update($gid, $name)) {
5855 'id' => intval($gid),
5856 'id_str' => (string) $gid,
5857 'user' => $user_info
5860 return api_format_data("lists", $type, ['lists' => $list]);
5864 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5868 * @param string $type Return type (atom, rss, xml, json)
5870 * @return array|string
5872 function api_friendica_activity($type)
5876 if (api_user() === false) {
5877 throw new ForbiddenException();
5879 $verb = strtolower($a->argv[3]);
5880 $verb = preg_replace("|\..*$|", "", $verb);
5882 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5884 $res = Item::performLike($id, $verb);
5887 if ($type == "xml") {
5892 return api_format_data('ok', $type, ['ok' => $ok]);
5894 throw new BadRequestException('Error adding activity');
5898 /// @TODO move to top of file or somewhere better
5899 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5900 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5901 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5902 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5903 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5904 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5905 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5906 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5907 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5908 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5911 * @brief Returns notifications
5913 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5914 * @return string|array
5916 function api_friendica_notification($type)
5920 if (api_user() === false) {
5921 throw new ForbiddenException();
5924 throw new BadRequestException("Invalid argument count");
5926 $nm = new NotificationsManager();
5928 $notes = $nm->getAll([], "+seen -date", 50);
5930 if ($type == "xml") {
5932 foreach ($notes as $note) {
5933 $xmlnotes[] = ["@attributes" => $note];
5939 return api_format_data("notes", $type, ['note' => $notes]);
5943 * POST request with 'id' param as notification id
5945 * @brief Set notification as seen and returns associated item (if possible)
5947 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5948 * @return string|array
5950 function api_friendica_notification_seen($type)
5953 $user_info = api_get_user($a);
5955 if (api_user() === false || $user_info === false) {
5956 throw new ForbiddenException();
5959 throw new BadRequestException("Invalid argument count");
5962 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5964 $nm = new NotificationsManager();
5965 $note = $nm->getByID($id);
5966 if (is_null($note)) {
5967 throw new BadRequestException("Invalid argument");
5970 $nm->setSeen($note);
5971 if ($note['otype']=='item') {
5972 // would be really better with an ItemsManager and $im->getByID() :-P
5974 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5975 intval($note['iid']),
5976 intval(local_user())
5979 // we found the item, return it to the user
5980 $ret = api_format_items($r, $user_info, false, $type);
5981 $data = ['status' => $ret];
5982 return api_format_data("status", $type, $data);
5984 // the item can't be found, but we set the note as seen, so we count this as a success
5986 return api_format_data('result', $type, ['result' => "success"]);
5989 /// @TODO move to top of file or somewhere better
5990 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5991 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5994 * @brief update a direct_message to seen state
5996 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5997 * @return string|array (success result=ok, error result=error with error message)
5999 function api_friendica_direct_messages_setseen($type)
6002 if (api_user() === false) {
6003 throw new ForbiddenException();
6007 $user_info = api_get_user($a);
6008 $uid = $user_info['uid'];
6009 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
6011 // return error if id is zero
6013 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6014 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6017 // get data of the specified message id
6019 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
6024 // error message if specified id is not in database
6025 if (!DBM::is_result($r)) {
6026 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6027 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6030 // update seen indicator
6032 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
6039 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6040 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6042 $answer = ['result' => 'error', 'message' => 'unknown error'];
6043 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6047 /// @TODO move to top of file or somewhere better
6048 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6051 * @brief search for direct_messages containing a searchstring through api
6053 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6054 * @param string $box
6055 * @return string|array (success: success=true if found and search_result contains found messages,
6056 * success=false if nothing was found, search_result='nothing found',
6057 * error: result=error with error message)
6059 function api_friendica_direct_messages_search($type, $box = "")
6063 if (api_user() === false) {
6064 throw new ForbiddenException();
6068 $user_info = api_get_user($a);
6069 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
6070 $uid = $user_info['uid'];
6072 // error if no searchstring specified
6073 if ($searchstring == "") {
6074 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6075 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6078 // get data for the specified searchstring
6080 "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",
6082 dbesc('%'.$searchstring.'%')
6085 $profile_url = $user_info["url"];
6087 // message if nothing was found
6088 if (!DBM::is_result($r)) {
6089 $success = ['success' => false, 'search_results' => 'problem with query'];
6090 } elseif (count($r) == 0) {
6091 $success = ['success' => false, 'search_results' => 'nothing found'];
6094 foreach ($r as $item) {
6095 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6096 $recipient = $user_info;
6097 $sender = api_get_user($a, normalise_link($item['contact-url']));
6098 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6099 $recipient = api_get_user($a, normalise_link($item['contact-url']));
6100 $sender = $user_info;
6103 if (isset($recipient) && isset($sender)) {
6104 $ret[] = api_format_messages($item, $recipient, $sender);
6107 $success = ['success' => true, 'search_results' => $ret];
6110 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6113 /// @TODO move to top of file or somewhere better
6114 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6117 * @brief return data of all the profiles a user has to the client
6119 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6120 * @return string|array
6122 function api_friendica_profile_show($type)
6126 if (api_user() === false) {
6127 throw new ForbiddenException();
6131 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
6133 // retrieve general information about profiles for user
6134 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6135 $directory = Config::get('system', 'directory');
6137 // get data of the specified profile id or all profiles of the user if not specified
6138 if ($profileid != 0) {
6140 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
6145 // error message if specified gid is not in database
6146 if (!DBM::is_result($r)) {
6147 throw new BadRequestException("profile_id not available");
6151 "SELECT * FROM `profile` WHERE `uid` = %d",
6155 // loop through all returned profiles and retrieve data and users
6158 foreach ($r as $rr) {
6159 $profile = api_format_items_profiles($rr);
6161 // select all users from contact table, loop and prepare standard return for user data
6164 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
6166 intval($rr['profile_id'])
6169 foreach ($nurls as $nurl) {
6170 $user = api_get_user($a, $nurl['nurl']);
6171 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6173 $profile['users'] = $users;
6175 // add prepared profile data to array for final return
6176 if ($type == "xml") {
6177 $profiles[$k++ . ":profile"] = $profile;
6179 $profiles[] = $profile;
6183 // return settings, authenticated user and profiles data
6184 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
6186 $result = ['multi_profiles' => $multi_profiles ? true : false,
6187 'global_dir' => $directory,
6188 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
6189 'profiles' => $profiles];
6190 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6192 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6195 * Returns a list of saved searches.
6197 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6199 * @param string $type Return format: json or xml
6201 * @return string|array
6203 function api_saved_searches_list($type)
6205 $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
6208 while ($term = $terms->fetch()) {
6210 'created_at' => api_date(time()),
6211 'id' => intval($term['id']),
6212 'id_str' => $term['id'],
6213 'name' => $term['term'],
6215 'query' => $term['term']
6221 return api_format_data("terms", $type, ['terms' => $result]);
6224 /// @TODO move to top of file or somewhere better
6225 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6228 @TODO Maybe open to implement?
6230 [pagename] => api/1.1/statuses/lookup.json
6231 [id] => 605138389168451584
6232 [include_cards] => true
6233 [cards_platform] => Android-12
6234 [include_entities] => true
6235 [include_my_retweet] => 1
6237 [include_reply_count] => true
6238 [include_descendent_reply_count] => true
6242 Not implemented by now:
6243 statuses/retweets_of_me
6248 account/update_location
6249 account/update_profile_background_image
6252 friendica/profile/update
6253 friendica/profile/create
6254 friendica/profile/delete
6256 Not implemented in status.net:
6257 statuses/retweeted_to_me
6258 statuses/retweeted_by_me
6259 direct_messages/destroy
6261 account/update_delivery_device
6262 notifications/follow