3 * @file include/api.php
4 * Friendica implementation of statusnet/twitter API
6 * @todo Automatically detect if incoming data is HTML or BBCode
9 use Friendica\Content\Feature;
10 use Friendica\Core\System;
11 use Friendica\Core\Config;
12 use Friendica\Core\NotificationsManager;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\Worker;
15 use Friendica\Database\DBM;
16 use Friendica\Model\Contact;
17 use Friendica\Model\Group;
18 use Friendica\Model\Photo;
19 use Friendica\Model\User;
20 use Friendica\Network\FKOAuth1;
21 use Friendica\Network\HTTPException;
22 use Friendica\Network\HTTPException\BadRequestException;
23 use Friendica\Network\HTTPException\ForbiddenException;
24 use Friendica\Network\HTTPException\InternalServerErrorException;
25 use Friendica\Network\HTTPException\MethodNotAllowedException;
26 use Friendica\Network\HTTPException\NotFoundException;
27 use Friendica\Network\HTTPException\NotImplementedException;
28 use Friendica\Network\HTTPException\UnauthorizedException;
29 use Friendica\Network\HTTPException\TooManyRequestsException;
30 use Friendica\Object\Image;
31 use Friendica\Protocol\Diaspora;
32 use Friendica\Util\XML;
34 require_once 'include/bbcode.php';
35 require_once 'include/datetime.php';
36 require_once 'include/conversation.php';
37 require_once 'include/html2plain.php';
38 require_once 'mod/share.php';
39 require_once 'mod/item.php';
40 require_once 'include/security.php';
41 require_once 'include/contact_selectors.php';
42 require_once 'include/html2bbcode.php';
43 require_once 'mod/wall_upload.php';
44 require_once 'mod/proxy.php';
45 require_once 'include/message.php';
46 require_once 'include/like.php';
47 require_once 'include/plaintext.php';
49 define('API_METHOD_ANY', '*');
50 define('API_METHOD_GET', 'GET');
51 define('API_METHOD_POST', 'POST,PUT');
52 define('API_METHOD_DELETE', 'POST,DELETE');
58 * @brief Auth API user
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).
66 if (x($_SESSION, 'allow_api')) {
74 * @brief Get source name from API client
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
82 * Client source name, default to "api" if unset/unknown
86 if (requestdata('source')) {
87 return requestdata('source');
90 // Support for known clients that doesn't send a source name
91 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
95 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
101 * @brief Format date for API
103 * @param string $str Source date, as UTC
104 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
106 function api_date($str)
108 // Wed May 23 06:01:13 +0000 2007
109 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y");
113 * @brief Register API endpoint
115 * Register a function to be the endpont for defined API path.
117 * @param string $path API URL path, relative to System::baseUrl()
118 * @param string $func Function name to call on path request
119 * @param bool $auth API need logged user
120 * @param string $method HTTP method reqiured to call this endpoint.
121 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
122 * Default to API_METHOD_ANY
124 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
134 // Workaround for hotot
135 $path = str_replace("api/", "api/1.1/", $path);
145 * @brief Login API user
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 * @param object $a App
151 * @hook 'authenticate'
153 * 'username' => username from login form
154 * 'password' => password from login form
155 * 'authenticated' => return status,
156 * 'user_record' => return authenticated user record
158 * array $user logged user record
160 function api_login(App $a)
162 $oauth1 = new FKOAuth1();
165 list($consumer, $token) = $oauth1->verify_request(OAuthRequest::from_request());
166 if (!is_null($token)) {
167 $oauth1->loginUser($token->uid);
168 call_hooks('logged_in', $a->user);
171 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
172 var_dump($consumer, $token);
174 } catch (Exception $e) {
178 // workaround for HTTP-auth in CGI mode
179 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
180 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
181 if (strlen($userpass)) {
182 list($name, $password) = explode(':', $userpass);
183 $_SERVER['PHP_AUTH_USER'] = $name;
184 $_SERVER['PHP_AUTH_PW'] = $password;
188 if (!x($_SERVER, 'PHP_AUTH_USER')) {
189 logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
190 header('WWW-Authenticate: Basic realm="Friendica"');
191 throw new UnauthorizedException("This API requires login");
194 $user = $_SERVER['PHP_AUTH_USER'];
195 $password = $_SERVER['PHP_AUTH_PW'];
197 // allow "user@server" login (but ignore 'server' part)
198 $at = strstr($user, "@", true);
203 // next code from mod/auth.php. needs better solution
207 'username' => trim($user),
208 'password' => trim($password),
209 'authenticated' => 0,
210 'user_record' => null,
214 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
215 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
216 * and later plugins should not interfere with an earlier one that succeeded.
218 call_hooks('authenticate', $addon_auth);
220 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
221 $record = $addon_auth['user_record'];
223 $user_id = User::authenticate(trim($user), trim($password));
225 $record = dba::select('user', [], ['uid' => $user_id], ['limit' => 1]);
229 if (!$record || !count($record)) {
230 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
231 header('WWW-Authenticate: Basic realm="Friendica"');
232 //header('HTTP/1.0 401 Unauthorized');
233 //die('This api requires login');
234 throw new UnauthorizedException("This API requires login");
237 authenticate_success($record);
239 $_SESSION["allow_api"] = true;
241 call_hooks('logged_in', $a->user);
245 * @brief Check HTTP method of called API
247 * API endpoints can define which HTTP method to accept when called.
248 * This function check the current HTTP method agains endpoint
251 * @param string $method Required methods, uppercase, separated by comma
254 function api_check_method($method)
256 if ($method == "*") {
259 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
263 * @brief Main API entry point
265 * Authenticate user, call registered API function, set HTTP headers
267 * @param object $a App
268 * @return string API call result
270 function api_call(App $a)
272 global $API, $called_api;
275 if (strpos($a->query_string, ".xml") > 0) {
278 if (strpos($a->query_string, ".json") > 0) {
281 if (strpos($a->query_string, ".rss") > 0) {
284 if (strpos($a->query_string, ".atom") > 0) {
289 foreach ($API as $p => $info) {
290 if (strpos($a->query_string, $p) === 0) {
291 if (!api_check_method($info['method'])) {
292 throw new MethodNotAllowedException();
295 $called_api = explode("/", $p);
296 //unset($_SERVER['PHP_AUTH_USER']);
298 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
299 if ($info['auth'] === true && api_user() === false) {
303 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
304 logger('API parameters: ' . print_r($_REQUEST, true));
306 $stamp = microtime(true);
307 $r = call_user_func($info['func'], $type);
308 $duration = (float) (microtime(true) - $stamp);
309 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
311 if (Config::get("system", "profiler")) {
312 $duration = microtime(true)-$a->performance["start"];
314 /// @TODO round() really everywhere?
316 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
317 "Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
318 round($a->performance["database"] - $a->performance["database_write"], 3),
319 round($a->performance["database_write"], 3),
320 round($a->performance["network"], 2),
321 round($a->performance["file"], 2),
322 round($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
328 if (Config::get("rendertime", "callstack")) {
329 $o = "Database Read:\n";
330 foreach ($a->callstack["database"] as $func => $time) {
331 $time = round($time, 3);
333 $o .= $func . ": " . $time . "\n";
336 $o .= "\nDatabase Write:\n";
337 foreach ($a->callstack["database_write"] as $func => $time) {
338 $time = round($time, 3);
340 $o .= $func . ": " . $time . "\n";
344 $o .= "\nNetwork:\n";
345 foreach ($a->callstack["network"] as $func => $time) {
346 $time = round($time, 3);
348 $o .= $func . ": " . $time . "\n";
351 logger($o, LOGGER_DEBUG);
357 * api function returned false withour throw an
358 * exception. This should not happend, throw a 500
360 throw new InternalServerErrorException();
365 header("Content-Type: text/xml");
369 header("Content-Type: application/json");
370 foreach ($r as $rr) {
371 $json = json_encode($rr);
373 if (x($_GET, 'callback')) {
374 $json = $_GET['callback'] . "(" . $json . ")";
379 header("Content-Type: application/rss+xml");
380 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
383 header("Content-Type: application/atom+xml");
384 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
390 logger('API call not implemented: ' . $a->query_string);
391 throw new NotImplementedException();
392 } catch (HTTPException $e) {
393 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
394 return api_error($type, $e);
399 * @brief Format API error string
401 * @param string $type Return type (xml, json, rss, as)
402 * @param object $e HTTPException Error object
403 * @return string error message formatted as $type
405 function api_error($type, $e)
409 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
410 /// @TODO: https://dev.twitter.com/overview/api/response-codes
412 $error = array("error" => $error,
413 "code" => $e->httpcode . " " . $e->httpdesc,
414 "request" => $a->query_string);
416 $ret = api_format_data('status', $type, array('status' => $error));
420 header("Content-Type: text/xml");
424 header("Content-Type: application/json");
425 return json_encode($ret);
428 header("Content-Type: application/rss+xml");
432 header("Content-Type: application/atom+xml");
439 * @brief Set values for RSS template
442 * @param array $arr Array to be passed to template
443 * @param array $user_info User info
445 * @todo find proper type-hints
447 function api_rss_extra(App $a, $arr, $user_info)
449 if (is_null($user_info)) {
450 $user_info = api_get_user($a);
453 $arr['$user'] = $user_info;
454 $arr['$rss'] = array(
455 'alternate' => $user_info['url'],
456 'self' => System::baseUrl() . "/" . $a->query_string,
457 'base' => System::baseUrl(),
458 'updated' => api_date(null),
459 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
460 'language' => $user_info['language'],
461 'logo' => System::baseUrl() . "/images/friendica-32.png",
469 * @brief Unique contact to contact url.
471 * @param int $id Contact id
472 * @return bool|string
473 * Contact url or False if contact id is unknown
475 function api_unique_id_to_nurl($id)
477 $r = dba::select('contact', array('nurl'), array('uid' => 0, 'id' => $id), array('limit' => 1));
479 if (DBM::is_result($r)) {
487 * @brief Get user info array.
489 * @param object $a App
490 * @param int|string $contact_id Contact ID or URL
492 function api_get_user(App $a, $contact_id = null)
501 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
503 // Searching for contact URL
504 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
505 $user = dbesc(normalise_link($contact_id));
507 $extra_query = "AND `contact`.`nurl` = '%s' ";
508 if (api_user() !== false) {
509 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
513 // Searching for contact id with uid = 0
514 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
515 $user = dbesc(api_unique_id_to_nurl($contact_id));
518 throw new BadRequestException("User not found.");
522 $extra_query = "AND `contact`.`nurl` = '%s' ";
523 if (api_user() !== false) {
524 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
528 if (is_null($user) && x($_GET, 'user_id')) {
529 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
532 throw new BadRequestException("User not found.");
536 $extra_query = "AND `contact`.`nurl` = '%s' ";
537 if (api_user() !== false) {
538 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
541 if (is_null($user) && x($_GET, 'screen_name')) {
542 $user = dbesc($_GET['screen_name']);
544 $extra_query = "AND `contact`.`nick` = '%s' ";
545 if (api_user() !== false) {
546 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
550 if (is_null($user) && x($_GET, 'profileurl')) {
551 $user = dbesc(normalise_link($_GET['profileurl']));
553 $extra_query = "AND `contact`.`nurl` = '%s' ";
554 if (api_user() !== false) {
555 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
559 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
560 $argid = count($called_api);
561 list($user, $null) = explode(".", $a->argv[$argid]);
562 if (is_numeric($user)) {
563 $user = dbesc(api_unique_id_to_nurl($user));
570 $extra_query = "AND `contact`.`nurl` = '%s' ";
571 if (api_user() !== false) {
572 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
575 $user = dbesc($user);
577 $extra_query = "AND `contact`.`nick` = '%s' ";
578 if (api_user() !== false) {
579 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
584 logger("api_get_user: user ".$user, LOGGER_DEBUG);
587 if (api_user() === false) {
591 $user = $_SESSION['uid'];
592 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
596 logger('api_user: ' . $extra_query . ', user: ' . $user);
600 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
606 // Selecting the id by priority, friendica first
607 api_best_nickname($uinfo);
609 // if the contact wasn't found, fetch it from the contacts with uid = 0
610 if (!DBM::is_result($uinfo)) {
614 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
617 if (DBM::is_result($r)) {
618 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
620 // If no nick where given, extract it from the address
621 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
622 $r[0]['nick'] = api_get_nick($r[0]["url"]);
627 'id_str' => (string) $r[0]["id"],
628 'name' => $r[0]["name"],
629 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
630 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
631 'description' => $r[0]["about"],
632 'profile_image_url' => $r[0]["micro"],
633 'profile_image_url_https' => $r[0]["micro"],
634 'url' => $r[0]["url"],
635 'protected' => false,
636 'followers_count' => 0,
637 'friends_count' => 0,
639 'created_at' => api_date($r[0]["created"]),
640 'favourites_count' => 0,
642 'time_zone' => 'UTC',
643 'geo_enabled' => false,
645 'statuses_count' => 0,
647 'contributors_enabled' => false,
648 'is_translator' => false,
649 'is_translation_enabled' => false,
650 'following' => false,
651 'follow_request_sent' => false,
652 'statusnet_blocking' => false,
653 'notifications' => false,
654 'statusnet_profile_url' => $r[0]["url"],
656 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
658 'network' => $r[0]["network"],
663 throw new BadRequestException("User not found.");
667 if ($uinfo[0]['self']) {
668 if ($uinfo[0]['network'] == "") {
669 $uinfo[0]['network'] = NETWORK_DFRN;
673 "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
677 "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
681 /// @TODO old-lost code? (twice)
682 // Counting is deactivated by now, due to performance issues
683 // count public wall messages
684 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
685 // intval($uinfo[0]['uid'])
687 //$countitms = $r[0]['count'];
690 // Counting is deactivated by now, due to performance issues
691 //$r = q("SELECT count(*) as `count` FROM `item`
692 // WHERE `contact-id` = %d",
693 // intval($uinfo[0]['id'])
695 //$countitms = $r[0]['count'];
699 /// @TODO old-lost code? (twice)
701 // Counting is deactivated by now, due to performance issues
703 $r = q("SELECT count(*) as `count` FROM `contact`
704 WHERE `uid` = %d AND `rel` IN ( %d, %d )
705 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
706 intval($uinfo[0]['uid']),
707 intval(CONTACT_IS_SHARING),
708 intval(CONTACT_IS_FRIEND)
710 $countfriends = $r[0]['count'];
712 $r = q("SELECT count(*) as `count` FROM `contact`
713 WHERE `uid` = %d AND `rel` IN ( %d, %d )
714 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
715 intval($uinfo[0]['uid']),
716 intval(CONTACT_IS_FOLLOWER),
717 intval(CONTACT_IS_FRIEND)
719 $countfollowers = $r[0]['count'];
721 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
722 intval($uinfo[0]['uid'])
724 $starred = $r[0]['count'];
727 if (! $uinfo[0]['self']) {
737 // Add a nick if it isn't present there
738 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
739 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
742 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
744 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
746 if (!empty($profile[0]['pdesc'])) {
747 $description = $profile[0]['pdesc'];
749 $description = $uinfo[0]["about"];
752 if (!empty($usr[0]['default-location'])) {
753 $location = $usr[0]['default-location'];
754 } elseif (!empty($uinfo[0]["location"])) {
755 $location = $uinfo[0]["location"];
757 $location = network_name;
761 'id' => intval($pcontact_id),
762 'id_str' => (string) intval($pcontact_id),
763 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
764 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
765 'location' => $location,
766 'description' => $description,
767 'profile_image_url' => $uinfo[0]['micro'],
768 'profile_image_url_https' => $uinfo[0]['micro'],
769 'url' => $uinfo[0]['url'],
770 'protected' => false,
771 'followers_count' => intval($countfollowers),
772 'friends_count' => intval($countfriends),
774 'created_at' => api_date($uinfo[0]['created']),
775 'favourites_count' => intval($starred),
777 'time_zone' => 'UTC',
778 'geo_enabled' => false,
780 'statuses_count' => intval($countitms),
782 'contributors_enabled' => false,
783 'is_translator' => false,
784 'is_translation_enabled' => false,
785 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
786 'follow_request_sent' => false,
787 'statusnet_blocking' => false,
788 'notifications' => false,
790 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
791 'statusnet_profile_url' => $uinfo[0]['url'],
792 'uid' => intval($uinfo[0]['uid']),
793 'cid' => intval($uinfo[0]['cid']),
794 'self' => $uinfo[0]['self'],
795 'network' => $uinfo[0]['network'],
798 // If this is a local user and it uses Frio, we can get its color preferences.
800 $theme_info = dba::select('user', ['theme'], ['uid' => $ret['uid']], ['limit' => 1]);
801 if ($theme_info['theme'] === 'frio') {
802 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
803 if ($schema && ($schema != '---')) {
804 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
805 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
806 require_once $schemefile;
809 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
810 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
811 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
817 $link_color = "#6fdbe8";
820 $bgcolor = "#ededed";
823 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
824 $ret['profile_link_color'] = str_replace('#', '', $link_color);
825 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
833 * @brief return api-formatted array for item's author and owner
835 * @param object $a App
836 * @param array $item item from db
837 * @return array(array:author, array:owner)
839 function api_item_get_user(App $a, $item)
841 $status_user = api_get_user($a, $item["author-link"]);
843 $status_user["protected"] = (($item["allow_cid"] != "") ||
844 ($item["allow_gid"] != "") ||
845 ($item["deny_cid"] != "") ||
846 ($item["deny_gid"] != "") ||
849 if ($item['thr-parent'] == $item['uri']) {
850 $owner_user = api_get_user($a, $item["owner-link"]);
852 $owner_user = $status_user;
855 return (array($status_user, $owner_user));
859 * @brief walks recursively through an array with the possibility to change value and key
861 * @param array $array The array to walk through
862 * @param string $callback The callback function
864 * @return array the transformed array
866 function api_walk_recursive(array &$array, callable $callback)
868 $new_array = array();
870 foreach ($array as $k => $v) {
872 if ($callback($v, $k)) {
873 $new_array[$k] = api_walk_recursive($v, $callback);
876 if ($callback($v, $k)) {
887 * @brief Callback function to transform the array in an array that can be transformed in a XML file
889 * @param mixed $item Array item value
890 * @param string $key Array key
892 * @return boolean Should the array item be deleted?
894 function api_reformat_xml(&$item, &$key)
896 if (is_bool($item)) {
897 $item = ($item ? "true" : "false");
900 if (substr($key, 0, 10) == "statusnet_") {
901 $key = "statusnet:".substr($key, 10);
902 } elseif (substr($key, 0, 10) == "friendica_") {
903 $key = "friendica:".substr($key, 10);
905 /// @TODO old-lost code?
907 // $key = "default:".$key;
913 * @brief Creates the XML from a JSON style array
915 * @param array $data JSON style array
916 * @param string $root_element Name of the root element
918 * @return string The XML data
920 function api_create_xml($data, $root_element)
922 $childname = key($data);
923 $data2 = array_pop($data);
926 $namespaces = array("" => "http://api.twitter.com",
927 "statusnet" => "http://status.net/schema/api/1/",
928 "friendica" => "http://friendi.ca/schema/api/1/",
929 "georss" => "http://www.georss.org/georss");
931 /// @todo Auto detection of needed namespaces
932 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
933 $namespaces = array();
936 if (is_array($data2)) {
937 api_walk_recursive($data2, "api_reformat_xml");
944 foreach ($data2 as $item) {
945 $data4[$i++.":".$childname] = $item;
951 $data3 = array($root_element => $data2);
953 $ret = XML::fromArray($data3, $xml, false, $namespaces);
958 * @brief Formats the data according to the data type
960 * @param string $root_element Name of the root element
961 * @param string $type Return type (atom, rss, xml, json)
962 * @param array $data JSON style array
964 * @return (string|object|array) XML data or JSON data
966 function api_format_data($root_element, $type, $data)
972 $ret = api_create_xml($data, $root_element);
987 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
988 * returns a 401 status code and an error message if not.
989 * http://developer.twitter.com/doc/get/account/verify_credentials
991 function api_account_verify_credentials($type)
996 if (api_user() === false) {
997 throw new ForbiddenException();
1000 unset($_REQUEST["user_id"]);
1001 unset($_GET["user_id"]);
1003 unset($_REQUEST["screen_name"]);
1004 unset($_GET["screen_name"]);
1006 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
1008 $user_info = api_get_user($a);
1010 // "verified" isn't used here in the standard
1011 unset($user_info["verified"]);
1013 // - Adding last status
1014 if (!$skip_status) {
1015 $user_info["status"] = api_status_show("raw");
1016 if (!count($user_info["status"])) {
1017 unset($user_info["status"]);
1019 unset($user_info["status"]["user"]);
1023 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1024 unset($user_info["uid"]);
1025 unset($user_info["self"]);
1027 return api_format_data("user", $type, array('user' => $user_info));
1030 /// @TODO move to top of file or somwhere better
1031 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1034 * Get data from $_POST or $_GET
1036 function requestdata($k)
1038 if (x($_POST, $k)) {
1047 /*Waitman Gobble Mod*/
1048 function api_statuses_mediap($type)
1052 if (api_user() === false) {
1053 logger('api_statuses_update: no user');
1054 throw new ForbiddenException();
1056 $user_info = api_get_user($a);
1058 $_REQUEST['type'] = 'wall';
1059 $_REQUEST['profile_uid'] = api_user();
1060 $_REQUEST['api_source'] = true;
1061 $txt = requestdata('status');
1062 /// @TODO old-lost code?
1063 //$txt = urldecode(requestdata('status'));
1065 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1066 $txt = html2bb_video($txt);
1067 $config = HTMLPurifier_Config::createDefault();
1068 $config->set('Cache.DefinitionImpl', null);
1069 $purifier = new HTMLPurifier($config);
1070 $txt = $purifier->purify($txt);
1072 $txt = html2bbcode($txt);
1074 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1076 // tell wall_upload function to return img info instead of echo
1077 $_REQUEST['hush'] = 'yeah';
1078 $bebop = wall_upload_post($a);
1080 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1081 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1084 // this should output the last post (the one we just posted).
1085 return api_status_show($type);
1088 /// @TODO move this to top of file or somewhere better!
1089 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1091 function api_statuses_update($type)
1096 if (api_user() === false) {
1097 logger('api_statuses_update: no user');
1098 throw new ForbiddenException();
1101 $user_info = api_get_user($a);
1103 // convert $_POST array items to the form we use for web posts.
1105 // logger('api_post: ' . print_r($_POST,true));
1107 if (requestdata('htmlstatus')) {
1108 $txt = requestdata('htmlstatus');
1109 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1110 $txt = html2bb_video($txt);
1112 $config = HTMLPurifier_Config::createDefault();
1113 $config->set('Cache.DefinitionImpl', null);
1115 $purifier = new HTMLPurifier($config);
1116 $txt = $purifier->purify($txt);
1118 $_REQUEST['body'] = html2bbcode($txt);
1121 $_REQUEST['body'] = requestdata('status');
1124 $_REQUEST['title'] = requestdata('title');
1126 $parent = requestdata('in_reply_to_status_id');
1128 // Twidere sends "-1" if it is no reply ...
1129 if ($parent == -1) {
1133 if (ctype_digit($parent)) {
1134 $_REQUEST['parent'] = $parent;
1136 $_REQUEST['parent_uri'] = $parent;
1139 if (requestdata('lat') && requestdata('long')) {
1140 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1142 $_REQUEST['profile_uid'] = api_user();
1145 $_REQUEST['type'] = 'net-comment';
1147 // Check for throttling (maximum posts per day, week and month)
1148 $throttle_day = Config::get('system', 'throttle_limit_day');
1149 if ($throttle_day > 0) {
1150 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1153 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1154 AND `created` > '%s' AND `id` = `parent`",
1159 if (DBM::is_result($r)) {
1160 $posts_day = $r[0]["posts_day"];
1165 if ($posts_day > $throttle_day) {
1166 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1167 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1168 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1172 $throttle_week = Config::get('system', 'throttle_limit_week');
1173 if ($throttle_week > 0) {
1174 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1177 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1178 AND `created` > '%s' AND `id` = `parent`",
1183 if (DBM::is_result($r)) {
1184 $posts_week = $r[0]["posts_week"];
1189 if ($posts_week > $throttle_week) {
1190 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1191 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1192 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1196 $throttle_month = Config::get('system', 'throttle_limit_month');
1197 if ($throttle_month > 0) {
1198 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1201 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1202 AND `created` > '%s' AND `id` = `parent`",
1207 if (DBM::is_result($r)) {
1208 $posts_month = $r[0]["posts_month"];
1213 if ($posts_month > $throttle_month) {
1214 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1215 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1216 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1220 $_REQUEST['type'] = 'wall';
1223 if (x($_FILES, 'media')) {
1224 // upload the image if we have one
1225 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1226 $media = wall_upload_post($a);
1227 if (strlen($media) > 0) {
1228 $_REQUEST['body'] .= "\n\n" . $media;
1232 // To-Do: Multiple IDs
1233 if (requestdata('media_ids')) {
1235 "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",
1236 intval(requestdata('media_ids')),
1239 if (DBM::is_result($r)) {
1240 $phototypes = Image::supportedTypes();
1241 $ext = $phototypes[$r[0]['type']];
1242 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1243 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1247 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1249 $_REQUEST['api_source'] = true;
1251 if (!x($_REQUEST, "source")) {
1252 $_REQUEST["source"] = api_source();
1255 // call out normal post function
1258 // this should output the last post (the one we just posted).
1259 return api_status_show($type);
1262 /// @TODO move to top of file or somwhere better
1263 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1264 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1266 function api_media_upload($type)
1270 if (api_user() === false) {
1272 throw new ForbiddenException();
1275 $user_info = api_get_user($a);
1277 if (!x($_FILES, 'media')) {
1279 throw new BadRequestException("No media.");
1282 $media = wall_upload_post($a, false);
1285 throw new InternalServerErrorException();
1288 $returndata = array();
1289 $returndata["media_id"] = $media["id"];
1290 $returndata["media_id_string"] = (string)$media["id"];
1291 $returndata["size"] = $media["size"];
1292 $returndata["image"] = array("w" => $media["width"],
1293 "h" => $media["height"],
1294 "image_type" => $media["type"]);
1296 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1298 return array("media" => $returndata);
1301 /// @TODO move to top of file or somwhere better
1302 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1304 function api_status_show($type)
1308 $user_info = api_get_user($a);
1310 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1312 if ($type == "raw") {
1313 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1318 // get last public wall message
1322 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1323 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1324 AND `item`.`type` != 'activity' $privacy_sql
1325 ORDER BY `item`.`id` DESC
1327 intval($user_info['cid']),
1329 dbesc($user_info['url']),
1330 dbesc(normalise_link($user_info['url'])),
1331 dbesc($user_info['url']),
1332 dbesc(normalise_link($user_info['url']))
1335 if (DBM::is_result($lastwall)) {
1336 $lastwall = $lastwall[0];
1338 $in_reply_to = api_in_reply_to($lastwall);
1340 $converted = api_convert_item($lastwall);
1342 if ($type == "xml") {
1343 $geo = "georss:point";
1348 $status_info = array(
1349 'created_at' => api_date($lastwall['created']),
1350 'id' => intval($lastwall['id']),
1351 'id_str' => (string) $lastwall['id'],
1352 'text' => $converted["text"],
1353 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1354 'truncated' => false,
1355 'in_reply_to_status_id' => $in_reply_to['status_id'],
1356 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1357 'in_reply_to_user_id' => $in_reply_to['user_id'],
1358 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1359 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1360 'user' => $user_info,
1362 'coordinates' => "",
1364 'contributors' => "",
1365 'is_quote_status' => false,
1366 'retweet_count' => 0,
1367 'favorite_count' => 0,
1368 'favorited' => $lastwall['starred'] ? true : false,
1369 'retweeted' => false,
1370 'possibly_sensitive' => false,
1372 'statusnet_html' => $converted["html"],
1373 'statusnet_conversation_id' => $lastwall['parent'],
1374 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1377 if (count($converted["attachments"]) > 0) {
1378 $status_info["attachments"] = $converted["attachments"];
1381 if (count($converted["entities"]) > 0) {
1382 $status_info["entities"] = $converted["entities"];
1385 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1386 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1387 } elseif (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1388 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1391 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1392 unset($status_info["user"]["uid"]);
1393 unset($status_info["user"]["self"]);
1396 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1398 if ($type == "raw") {
1399 return $status_info;
1402 return api_format_data("statuses", $type, array('status' => $status_info));
1406 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1407 * The author's most recent status will be returned inline.
1408 * http://developer.twitter.com/doc/get/users/show
1410 function api_users_show($type)
1414 $user_info = api_get_user($a);
1418 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1419 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1420 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1421 AND `type`!='activity'
1422 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1426 dbesc(ACTIVITY_POST),
1427 intval($user_info['cid']),
1428 dbesc($user_info['url']),
1429 dbesc(normalise_link($user_info['url'])),
1430 dbesc($user_info['url']),
1431 dbesc(normalise_link($user_info['url']))
1434 if (DBM::is_result($lastwall)) {
1435 $lastwall = $lastwall[0];
1437 $in_reply_to = api_in_reply_to($lastwall);
1439 $converted = api_convert_item($lastwall);
1441 if ($type == "xml") {
1442 $geo = "georss:point";
1447 $user_info['status'] = array(
1448 'text' => $converted["text"],
1449 'truncated' => false,
1450 'created_at' => api_date($lastwall['created']),
1451 'in_reply_to_status_id' => $in_reply_to['status_id'],
1452 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1453 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1454 'id' => intval($lastwall['contact-id']),
1455 'id_str' => (string) $lastwall['contact-id'],
1456 'in_reply_to_user_id' => $in_reply_to['user_id'],
1457 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1458 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1460 'favorited' => $lastwall['starred'] ? true : false,
1461 'statusnet_html' => $converted["html"],
1462 'statusnet_conversation_id' => $lastwall['parent'],
1463 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1466 if (count($converted["attachments"]) > 0) {
1467 $user_info["status"]["attachments"] = $converted["attachments"];
1470 if (count($converted["entities"]) > 0) {
1471 $user_info["status"]["entities"] = $converted["entities"];
1474 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1475 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1478 if (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1479 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
1483 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1484 unset($user_info["uid"]);
1485 unset($user_info["self"]);
1487 return api_format_data("user", $type, array('user' => $user_info));
1490 /// @TODO move to top of file or somewhere better
1491 api_register_func('api/users/show', 'api_users_show');
1492 api_register_func('api/externalprofile/show', 'api_users_show');
1494 function api_users_search($type)
1498 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1500 $userlist = array();
1502 if (x($_GET, 'q')) {
1503 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1505 if (!DBM::is_result($r)) {
1506 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1509 if (DBM::is_result($r)) {
1511 foreach ($r as $user) {
1512 $user_info = api_get_user($a, $user["id"]);
1514 if ($type == "xml") {
1515 $userlist[$k++.":user"] = $user_info;
1517 $userlist[] = $user_info;
1520 $userlist = array("users" => $userlist);
1522 throw new BadRequestException("User not found.");
1525 throw new BadRequestException("User not found.");
1527 return api_format_data("users", $type, $userlist);
1530 /// @TODO move to top of file or somewhere better
1531 api_register_func('api/users/search', 'api_users_search');
1534 * Return user objects
1536 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1538 * @param string $type Return format: json or xml
1540 * @return array|string
1541 * @throws NotFoundException if the results are empty.
1543 function api_users_lookup($type)
1547 if (x($_REQUEST['user_id'])) {
1548 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1550 $users[] = api_get_user(get_app(), $id);
1555 if (empty($users)) {
1556 throw new NotFoundException;
1559 return api_format_data("users", $type, array('users' => $users));
1562 /// @TODO move to top of file or somewhere better
1563 api_register_func('api/users/lookup', 'api_users_lookup', true);
1566 * Returns statuses that match a specified query.
1568 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1570 * @param string $type Return format: json, xml, atom, rss
1572 * @return array|string
1573 * @throws BadRequestException if the "q" parameter is missing.
1575 function api_search($type)
1579 if (!x($_REQUEST, 'q')) {
1580 throw new BadRequestException("q parameter is required.");
1583 if (x($_REQUEST, 'rpp')) {
1584 $count = $_REQUEST['rpp'];
1585 } elseif (x($_REQUEST, 'count')) {
1586 $count = $_REQUEST['count'];
1591 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1592 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1593 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1595 $start = $page * $count;
1598 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1602 "SELECT ".item_fieldlists()."
1603 FROM `item` ".item_joins()."
1604 WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1605 AND `item`.`body` LIKE CONCAT('%',?,'%')
1608 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
1614 $data['status'] = api_format_items(dba::inArray($r), api_get_user(get_app()));
1616 return api_format_data("statuses", $type, $data);
1619 /// @TODO move to top of file or somewhere better
1620 api_register_func('api/search/tweets', 'api_search', true);
1621 api_register_func('api/search', 'api_search', true);
1625 * http://developer.twitter.com/doc/get/statuses/home_timeline
1627 * TODO: Optional parameters
1628 * TODO: Add reply info
1630 function api_statuses_home_timeline($type)
1634 if (api_user() === false) {
1635 throw new ForbiddenException();
1638 unset($_REQUEST["user_id"]);
1639 unset($_GET["user_id"]);
1641 unset($_REQUEST["screen_name"]);
1642 unset($_GET["screen_name"]);
1644 $user_info = api_get_user($a);
1645 // get last newtork messages
1648 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1649 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1653 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1654 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1655 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1656 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1657 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1659 $start = $page * $count;
1663 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1665 if ($exclude_replies > 0) {
1666 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1668 if ($conversation_id > 0) {
1669 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1673 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1674 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1675 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1676 `contact`.`id` AS `cid`
1678 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1679 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1680 WHERE `item`.`uid` = %d AND `verb` = '%s'
1681 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1684 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1686 dbesc(ACTIVITY_POST),
1692 $ret = api_format_items($r, $user_info, false, $type);
1694 // Set all posts from the query above to seen
1696 foreach ($r as $item) {
1697 $idarray[] = intval($item["id"]);
1700 $idlist = implode(",", $idarray);
1702 if ($idlist != "") {
1703 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1706 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1710 $data = array('status' => $ret);
1714 $data = api_rss_extra($a, $data, $user_info);
1718 return api_format_data("statuses", $type, $data);
1721 /// @TODO move to top of file or somewhere better
1722 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1723 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1725 function api_statuses_public_timeline($type)
1729 if (api_user() === false) {
1730 throw new ForbiddenException();
1733 $user_info = api_get_user($a);
1734 // get last newtork messages
1737 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1738 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1742 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1743 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1744 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1745 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1746 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1748 $start = $page * $count;
1750 if ($exclude_replies && !$conversation_id) {
1752 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1756 "SELECT " . item_fieldlists() . "
1758 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1759 " . item_joins() . "
1760 STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1761 AND NOT `user`.`hidewall`
1763 AND NOT `thread`.`private`
1765 AND `thread`.`visible`
1766 AND NOT `thread`.`deleted`
1767 AND NOT `thread`.`moderated`
1768 AND `thread`.`iid` > ?
1770 ORDER BY `thread`.`iid` DESC
1771 LIMIT " . intval($start) . ", " . intval($count),
1776 $r = dba::inArray($r);
1779 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1781 if ($conversation_id > 0) {
1782 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1786 "SELECT " . item_fieldlists() . "
1788 " . item_joins() . "
1789 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1790 AND NOT `user`.`hidewall`
1792 AND NOT `item`.`private`
1794 AND `item`.`visible`
1795 AND NOT `item`.`deleted`
1796 AND NOT `item`.`moderated`
1799 ORDER BY `item`.`id` DESC
1800 LIMIT " . intval($start) . ", " . intval($count),
1805 $r = dba::inArray($r);
1808 $ret = api_format_items($r, $user_info, false, $type);
1810 $data = array('status' => $ret);
1814 $data = api_rss_extra($a, $data, $user_info);
1818 return api_format_data("statuses", $type, $data);
1821 /// @TODO move to top of file or somewhere better
1822 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1825 * @brief Returns the list of public federated posts this node knows about
1827 * @param string $type Return format: json, xml, atom, rss
1828 * @return array|string
1829 * @throws ForbiddenException
1831 function api_statuses_networkpublic_timeline($type)
1835 if (api_user() === false) {
1836 throw new ForbiddenException();
1839 $user_info = api_get_user($a);
1841 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1842 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1845 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1846 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1850 $start = ($page - 1) * $count;
1854 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1858 "SELECT " . item_fieldlists() . "
1860 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1861 " . item_joins() . "
1862 WHERE `thread`.`uid` = 0
1864 AND NOT `thread`.`private`
1865 AND `thread`.`visible`
1866 AND NOT `thread`.`deleted`
1867 AND NOT `thread`.`moderated`
1868 AND `thread`.`iid` > ?
1870 ORDER BY `thread`.`iid` DESC
1871 LIMIT " . intval($start) . ", " . intval($count),
1876 $r = dba::inArray($r);
1878 $ret = api_format_items($r, $user_info, false, $type);
1880 $data = array('status' => $ret);
1884 $data = api_rss_extra($a, $data, $user_info);
1888 return api_format_data("statuses", $type, $data);
1891 /// @TODO move to top of file or somewhere better
1892 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1895 * @TODO nothing to say?
1897 function api_statuses_show($type)
1901 if (api_user() === false) {
1902 throw new ForbiddenException();
1905 $user_info = api_get_user($a);
1908 $id = intval($a->argv[3]);
1911 $id = intval($_REQUEST["id"]);
1916 $id = intval($a->argv[4]);
1919 logger('API: api_statuses_show: ' . $id);
1921 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1924 if ($conversation) {
1925 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1927 $sql_extra .= " AND `item`.`id` = %d";
1931 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1932 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1933 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1934 `contact`.`id` AS `cid`
1936 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1937 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1938 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1939 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1942 dbesc(ACTIVITY_POST),
1946 /// @TODO How about copying this to above methods which don't check $r ?
1947 if (!DBM::is_result($r)) {
1948 throw new BadRequestException("There is no status with this id.");
1951 $ret = api_format_items($r, $user_info, false, $type);
1953 if ($conversation) {
1954 $data = array('status' => $ret);
1955 return api_format_data("statuses", $type, $data);
1957 $data = array('status' => $ret[0]);
1958 return api_format_data("status", $type, $data);
1962 /// @TODO move to top of file or somewhere better
1963 api_register_func('api/statuses/show', 'api_statuses_show', true);
1966 * @TODO nothing to say?
1968 function api_conversation_show($type)
1972 if (api_user() === false) {
1973 throw new ForbiddenException();
1976 $user_info = api_get_user($a);
1979 $id = intval($a->argv[3]);
1980 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1981 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1985 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1986 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1988 $start = $page*$count;
1991 $id = intval($_REQUEST["id"]);
1996 $id = intval($a->argv[4]);
1999 logger('API: api_conversation_show: '.$id);
2001 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
2002 if (DBM::is_result($r)) {
2003 $id = $r[0]["parent"];
2009 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2012 // Not sure why this query was so complicated. We should keep it here for a while,
2013 // just to make sure that we really don't need it.
2014 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
2015 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
2018 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2019 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2020 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2021 `contact`.`id` AS `cid`
2023 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2024 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2025 WHERE `item`.`parent` = %d AND `item`.`visible`
2026 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2027 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2028 AND `item`.`id`>%d $sql_extra
2029 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2032 dbesc(ACTIVITY_POST),
2038 if (!DBM::is_result($r)) {
2039 throw new BadRequestException("There is no status with this id.");
2042 $ret = api_format_items($r, $user_info, false, $type);
2044 $data = array('status' => $ret);
2045 return api_format_data("statuses", $type, $data);
2048 /// @TODO move to top of file or somewhere better
2049 api_register_func('api/conversation/show', 'api_conversation_show', true);
2050 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2053 * @TODO nothing to say?
2055 function api_statuses_repeat($type)
2061 if (api_user() === false) {
2062 throw new ForbiddenException();
2065 $user_info = api_get_user($a);
2068 $id = intval($a->argv[3]);
2071 $id = intval($_REQUEST["id"]);
2076 $id = intval($a->argv[4]);
2079 logger('API: api_statuses_repeat: '.$id);
2082 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2083 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2084 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2085 `contact`.`id` AS `cid`
2087 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2088 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2089 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2090 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2091 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2093 AND `item`.`id`=%d",
2097 /// @TODO other style than above functions!
2098 if (DBM::is_result($r) && $r[0]['body'] != "") {
2099 if (strpos($r[0]['body'], "[/share]") !== false) {
2100 $pos = strpos($r[0]['body'], "[share");
2101 $post = substr($r[0]['body'], $pos);
2103 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2105 $post .= $r[0]['body'];
2106 $post .= "[/share]";
2108 $_REQUEST['body'] = $post;
2109 $_REQUEST['profile_uid'] = api_user();
2110 $_REQUEST['type'] = 'wall';
2111 $_REQUEST['api_source'] = true;
2113 if (!x($_REQUEST, "source")) {
2114 $_REQUEST["source"] = api_source();
2119 throw new ForbiddenException();
2122 // this should output the last post (the one we just posted).
2124 return api_status_show($type);
2127 /// @TODO move to top of file or somewhere better
2128 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2131 * @TODO nothing to say?
2133 function api_statuses_destroy($type)
2137 if (api_user() === false) {
2138 throw new ForbiddenException();
2141 $user_info = api_get_user($a);
2144 $id = intval($a->argv[3]);
2147 $id = intval($_REQUEST["id"]);
2152 $id = intval($a->argv[4]);
2155 logger('API: api_statuses_destroy: '.$id);
2157 $ret = api_statuses_show($type);
2159 drop_item($id, false);
2164 /// @TODO move to top of file or somewhere better
2165 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2168 * @TODO Nothing more than an URL to say?
2169 * http://developer.twitter.com/doc/get/statuses/mentions
2171 function api_statuses_mentions($type)
2175 if (api_user() === false) {
2176 throw new ForbiddenException();
2179 unset($_REQUEST["user_id"]);
2180 unset($_GET["user_id"]);
2182 unset($_REQUEST["screen_name"]);
2183 unset($_GET["screen_name"]);
2185 $user_info = api_get_user($a);
2186 // get last newtork messages
2190 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2191 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2195 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2196 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2197 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2199 $start = $page * $count;
2201 // Ugly code - should be changed
2202 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2203 $myurl = substr($myurl, strpos($myurl, '://') + 3);
2204 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
2205 $myurl = str_replace('www.', '', $myurl);
2206 $diasp_url = str_replace('/profile/', '/u/', $myurl);
2209 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2213 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2214 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2215 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2216 `contact`.`id` AS `cid`
2217 FROM `item` FORCE INDEX (`uid_id`)
2218 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2219 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2220 WHERE `item`.`uid` = %d AND `verb` = '%s'
2221 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2222 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2223 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2226 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2228 dbesc(ACTIVITY_POST),
2229 dbesc(protect_sprintf($myurl)),
2230 dbesc(protect_sprintf($myurl)),
2237 $ret = api_format_items($r, $user_info, false, $type);
2239 $data = array('status' => $ret);
2243 $data = api_rss_extra($a, $data, $user_info);
2247 return api_format_data("statuses", $type, $data);
2250 /// @TODO move to top of file or somewhere better
2251 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2252 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2255 * @brief Returns a user's public timeline
2257 * @param string $type Either "json" or "xml"
2258 * @return string|array
2259 * @throws ForbiddenException
2261 function api_statuses_user_timeline($type)
2265 if (api_user() === false) {
2266 throw new ForbiddenException();
2269 $user_info = api_get_user($a);
2272 "api_statuses_user_timeline: api_user: ". api_user() .
2273 "\nuser_info: ".print_r($user_info, true) .
2274 "\n_REQUEST: ".print_r($_REQUEST, true),
2278 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2279 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2280 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2281 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2284 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2285 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2289 $start = ($page - 1) * $count;
2292 if ($user_info['self'] == 1) {
2293 $sql_extra .= " AND `item`.`wall` = 1 ";
2296 if ($exclude_replies > 0) {
2297 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2300 if ($conversation_id > 0) {
2301 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2305 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2309 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2310 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2311 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2312 `contact`.`id` AS `cid`
2313 FROM `item` FORCE INDEX (`uid_contactid_id`)
2314 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2315 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2316 WHERE `item`.`uid` = %d AND `verb` = '%s'
2317 AND `item`.`contact-id` = %d
2318 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2320 AND `item`.`id` > %d
2321 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2323 dbesc(ACTIVITY_POST),
2324 intval($user_info['cid']),
2330 $ret = api_format_items($r, $user_info, true, $type);
2332 $data = array('status' => $ret);
2336 $data = api_rss_extra($a, $data, $user_info);
2340 return api_format_data("statuses", $type, $data);
2343 /// @TODO move to top of file or somwhere better
2344 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2347 * Star/unstar an item
2348 * param: id : id of the item
2350 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2352 function api_favorites_create_destroy($type)
2356 if (api_user() === false) {
2357 throw new ForbiddenException();
2360 // for versioned api.
2361 /// @TODO We need a better global soluton
2362 $action_argv_id = 2;
2363 if ($a->argv[1] == "1.1") {
2364 $action_argv_id = 3;
2367 if ($a->argc <= $action_argv_id) {
2368 throw new BadRequestException("Invalid request.");
2370 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2371 if ($a->argc == $action_argv_id + 2) {
2372 $itemid = intval($a->argv[$action_argv_id + 1]);
2374 /// @TODO use x() to check if _REQUEST contains 'id'
2375 $itemid = intval($_REQUEST['id']);
2378 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2380 if (!DBM::is_result($item) || count($item) == 0) {
2381 throw new BadRequestException("Invalid item.");
2386 $item[0]['starred'] = 1;
2389 $item[0]['starred'] = 0;
2392 throw new BadRequestException("Invalid action ".$action);
2395 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2397 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2400 throw new InternalServerErrorException("DB error");
2404 $user_info = api_get_user($a);
2405 $rets = api_format_items($item, $user_info, false, $type);
2408 $data = array('status' => $ret);
2412 $data = api_rss_extra($a, $data, $user_info);
2415 return api_format_data("status", $type, $data);
2418 /// @TODO move to top of file or somwhere better
2419 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2420 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2422 function api_favorites($type)
2428 if (api_user() === false) {
2429 throw new ForbiddenException();
2432 $called_api = array();
2434 $user_info = api_get_user($a);
2436 // in friendica starred item are private
2437 // return favorites only for self
2438 logger('api_favorites: self:' . $user_info['self']);
2440 if ($user_info['self'] == 0) {
2446 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2447 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2448 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2449 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2454 $start = $page*$count;
2457 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2461 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2462 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2463 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2464 `contact`.`id` AS `cid`
2465 FROM `item`, `contact`
2466 WHERE `item`.`uid` = %d
2467 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2468 AND `item`.`starred` = 1
2469 AND `contact`.`id` = `item`.`contact-id`
2470 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2473 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2480 $ret = api_format_items($r, $user_info, false, $type);
2483 $data = array('status' => $ret);
2487 $data = api_rss_extra($a, $data, $user_info);
2490 return api_format_data("statuses", $type, $data);
2493 /// @TODO move to top of file or somwhere better
2494 api_register_func('api/favorites', 'api_favorites', true);
2496 function api_format_messages($item, $recipient, $sender)
2498 // standard meta information
2500 'id' => $item['id'],
2501 'sender_id' => $sender['id'] ,
2503 'recipient_id' => $recipient['id'],
2504 'created_at' => api_date($item['created']),
2505 'sender_screen_name' => $sender['screen_name'],
2506 'recipient_screen_name' => $recipient['screen_name'],
2507 'sender' => $sender,
2508 'recipient' => $recipient,
2510 'friendica_seen' => $item['seen'],
2511 'friendica_parent_uri' => $item['parent-uri'],
2514 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2515 unset($ret["sender"]["uid"]);
2516 unset($ret["sender"]["self"]);
2517 unset($ret["recipient"]["uid"]);
2518 unset($ret["recipient"]["self"]);
2520 //don't send title to regular StatusNET requests to avoid confusing these apps
2521 if (x($_GET, 'getText')) {
2522 $ret['title'] = $item['title'];
2523 if ($_GET['getText'] == 'html') {
2524 $ret['text'] = bbcode($item['body'], false, false);
2525 } elseif ($_GET['getText'] == 'plain') {
2526 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2527 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2530 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2532 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2533 unset($ret['sender']);
2534 unset($ret['recipient']);
2540 function api_convert_item($item)
2542 $body = $item['body'];
2543 $attachments = api_get_attachments($body);
2545 // Workaround for ostatus messages where the title is identically to the body
2546 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2547 $statusbody = trim(html2plain($html, 0));
2549 // handle data: images
2550 $statusbody = api_format_items_embeded_images($item, $statusbody);
2552 $statustitle = trim($item['title']);
2554 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2555 $statustext = trim($statusbody);
2557 $statustext = trim($statustitle."\n\n".$statusbody);
2560 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2561 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2564 $statushtml = trim(bbcode($body, false, false));
2566 // Workaround for clients with limited HTML parser functionality
2567 $search = array("<br>", "<blockquote>", "</blockquote>",
2568 "<h1>", "</h1>", "<h2>", "</h2>",
2569 "<h3>", "</h3>", "<h4>", "</h4>",
2570 "<h5>", "</h5>", "<h6>", "</h6>");
2571 $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2572 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2573 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2574 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2575 $statushtml = str_replace($search, $replace, $statushtml);
2577 if ($item['title'] != "") {
2578 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2582 $oldtext = $statushtml;
2583 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2584 } while ($oldtext != $statushtml);
2586 if (substr($statushtml, 0, 4) == '<br>') {
2587 $statushtml = substr($statushtml, 4);
2590 if (substr($statushtml, 0, -4) == '<br>') {
2591 $statushtml = substr($statushtml, -4);
2594 // feeds without body should contain the link
2595 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2596 $statushtml .= bbcode($item['plink']);
2599 $entities = api_get_entitities($statustext, $body);
2602 "text" => $statustext,
2603 "html" => $statushtml,
2604 "attachments" => $attachments,
2605 "entities" => $entities
2609 function api_get_attachments(&$body)
2612 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2614 $URLSearchString = "^\[\]";
2615 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2621 $attachments = array();
2623 foreach ($images[1] as $image) {
2624 $imagedata = Image::getInfoFromURL($image);
2627 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2631 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2632 foreach ($images[0] as $orig) {
2633 $body = str_replace($orig, "", $body);
2637 return $attachments;
2640 function api_get_entitities(&$text, $bbcode)
2644 * Links at the first character of the post
2649 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2651 if ($include_entities != "true") {
2652 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2654 foreach ($images[1] as $image) {
2655 $replace = proxy_url($image);
2656 $text = str_replace($image, $replace, $text);
2661 $bbcode = bb_CleanPictureLinks($bbcode);
2663 // Change pure links in text to bbcode uris
2664 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2666 $entities = array();
2667 $entities["hashtags"] = array();
2668 $entities["symbols"] = array();
2669 $entities["urls"] = array();
2670 $entities["user_mentions"] = array();
2672 $URLSearchString = "^\[\]";
2674 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2676 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2677 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2678 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2680 $bbcode = preg_replace(
2681 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2682 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2685 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2687 $bbcode = preg_replace(
2688 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2689 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2692 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2694 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2696 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2697 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2699 $ordered_urls = array();
2700 foreach ($urls[1] as $id => $url) {
2701 //$start = strpos($text, $url, $offset);
2702 $start = iconv_strpos($text, $url, 0, "UTF-8");
2703 if (!($start === false)) {
2704 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2708 ksort($ordered_urls);
2711 //foreach ($urls[1] AS $id=>$url) {
2712 foreach ($ordered_urls as $url) {
2713 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2714 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2716 $display_url = $url["title"];
2718 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2719 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2721 if (strlen($display_url) > 26) {
2722 $display_url = substr($display_url, 0, 25)."…";
2726 //$start = strpos($text, $url, $offset);
2727 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2728 if (!($start === false)) {
2729 $entities["urls"][] = array("url" => $url["url"],
2730 "expanded_url" => $url["url"],
2731 "display_url" => $display_url,
2732 "indices" => array($start, $start+strlen($url["url"])));
2733 $offset = $start + 1;
2737 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2738 $ordered_images = array();
2739 foreach ($images[1] as $image) {
2740 //$start = strpos($text, $url, $offset);
2741 $start = iconv_strpos($text, $image, 0, "UTF-8");
2742 if (!($start === false)) {
2743 $ordered_images[$start] = $image;
2746 //$entities["media"] = array();
2749 foreach ($ordered_images as $url) {
2750 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2751 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2753 if (strlen($display_url) > 26) {
2754 $display_url = substr($display_url, 0, 25)."…";
2757 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2758 if (!($start === false)) {
2759 $image = Image::getInfoFromURL($url);
2761 // If image cache is activated, then use the following sizes:
2762 // thumb (150), small (340), medium (600) and large (1024)
2763 if (!Config::get("system", "proxy_disabled")) {
2764 $media_url = proxy_url($url);
2767 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2768 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2770 if (($image[0] > 150) || ($image[1] > 150)) {
2771 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2772 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2775 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2776 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2778 if (($image[0] > 600) || ($image[1] > 600)) {
2779 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2780 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2784 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2787 $entities["media"][] = array(
2789 "id_str" => (string)$start+1,
2790 "indices" => array($start, $start+strlen($url)),
2791 "media_url" => normalise_link($media_url),
2792 "media_url_https" => $media_url,
2794 "display_url" => $display_url,
2795 "expanded_url" => $url,
2799 $offset = $start + 1;
2805 function api_format_items_embeded_images(&$item, $text)
2807 $text = preg_replace_callback(
2808 "|data:image/([^;]+)[^=]+=*|m",
2809 function ($match) use ($item) {
2810 return System::baseUrl()."/display/".$item['guid'];
2819 * @brief return <a href='url'>name</a> as array
2821 * @param string $txt text
2826 function api_contactlink_to_array($txt)
2829 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2830 if ($r && count($match)==3) {
2832 'name' => $match[2],
2846 * @brief return likes, dislikes and attend status for item
2848 * @param array $item array
2850 * likes => int count
2851 * dislikes => int count
2853 function api_format_items_activities(&$item, $type = "json")
2857 $activities = array(
2859 'dislike' => array(),
2860 'attendyes' => array(),
2861 'attendno' => array(),
2862 'attendmaybe' => array(),
2867 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2868 intval($item['uid']),
2872 foreach ($items as $i) {
2873 // not used as result should be structured like other user data
2874 //builtin_activity_puller($i, $activities);
2876 // get user data and add it to the array of the activity
2877 $user = api_get_user($a, $i['author-link']);
2878 switch ($i['verb']) {
2880 $activities['like'][] = $user;
2882 case ACTIVITY_DISLIKE:
2883 $activities['dislike'][] = $user;
2885 case ACTIVITY_ATTEND:
2886 $activities['attendyes'][] = $user;
2888 case ACTIVITY_ATTENDNO:
2889 $activities['attendno'][] = $user;
2891 case ACTIVITY_ATTENDMAYBE:
2892 $activities['attendmaybe'][] = $user;
2899 if ($type == "xml") {
2900 $xml_activities = array();
2901 foreach ($activities as $k => $v) {
2902 // change xml element from "like" to "friendica:like"
2903 $xml_activities["friendica:".$k] = $v;
2904 // add user data into xml output
2906 foreach ($v as $user) {
2907 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2910 $activities = $xml_activities;
2918 * @brief return data from profiles
2920 * @param array $profile array containing data from db table 'profile'
2921 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2924 function api_format_items_profiles(&$profile = null, $type = "json")
2926 if ($profile != null) {
2927 $profile = array('profile_id' => $profile['id'],
2928 'profile_name' => $profile['profile-name'],
2929 'is_default' => $profile['is-default'] ? true : false,
2930 'hide_friends'=> $profile['hide-friends'] ? true : false,
2931 'profile_photo' => $profile['photo'],
2932 'profile_thumb' => $profile['thumb'],
2933 'publish' => $profile['publish'] ? true : false,
2934 'net_publish' => $profile['net-publish'] ? true : false,
2935 'description' => $profile['pdesc'],
2936 'date_of_birth' => $profile['dob'],
2937 'address' => $profile['address'],
2938 'city' => $profile['locality'],
2939 'region' => $profile['region'],
2940 'postal_code' => $profile['postal-code'],
2941 'country' => $profile['country-name'],
2942 'hometown' => $profile['hometown'],
2943 'gender' => $profile['gender'],
2944 'marital' => $profile['marital'],
2945 'marital_with' => $profile['with'],
2946 'marital_since' => $profile['howlong'],
2947 'sexual' => $profile['sexual'],
2948 'politic' => $profile['politic'],
2949 'religion' => $profile['religion'],
2950 'public_keywords' => $profile['pub_keywords'],
2951 'private_keywords' => $profile['prv_keywords'],
2952 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2953 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2954 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2955 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2956 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2957 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2958 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2959 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2960 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2961 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2962 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2963 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2964 'homepage' => $profile['homepage'],
2971 * @brief format items to be returned by api
2973 * @param array $r array of items
2974 * @param array $user_info
2975 * @param bool $filter_user filter items by $user_info
2977 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2983 foreach ($r as $item) {
2984 localize_item($item);
2985 list($status_user, $owner_user) = api_item_get_user($a, $item);
2987 // Look if the posts are matching if they should be filtered by user id
2988 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2992 $in_reply_to = api_in_reply_to($item);
2994 $converted = api_convert_item($item);
2996 if ($type == "xml") {
2997 $geo = "georss:point";
3003 'text' => $converted["text"],
3004 'truncated' => false,
3005 'created_at'=> api_date($item['created']),
3006 'in_reply_to_status_id' => $in_reply_to['status_id'],
3007 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3008 'source' => (($item['app']) ? $item['app'] : 'web'),
3009 'id' => intval($item['id']),
3010 'id_str' => (string) intval($item['id']),
3011 'in_reply_to_user_id' => $in_reply_to['user_id'],
3012 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3013 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3015 'favorited' => $item['starred'] ? true : false,
3016 'user' => $status_user ,
3017 'friendica_owner' => $owner_user,
3018 //'entities' => NULL,
3019 'statusnet_html' => $converted["html"],
3020 'statusnet_conversation_id' => $item['parent'],
3021 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3022 'friendica_activities' => api_format_items_activities($item, $type),
3025 if (count($converted["attachments"]) > 0) {
3026 $status["attachments"] = $converted["attachments"];
3029 if (count($converted["entities"]) > 0) {
3030 $status["entities"] = $converted["entities"];
3033 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
3034 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
3035 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
3036 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
3040 // Retweets are only valid for top postings
3041 // It doesn't work reliable with the link if its a feed
3042 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
3044 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
3047 if ($item["id"] == $item["parent"]) {
3048 $retweeted_item = api_share_as_retweet($item);
3049 if ($retweeted_item !== false) {
3050 $retweeted_status = $status;
3052 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
3053 } catch (BadRequestException $e) {
3054 // user not found. should be found?
3055 /// @todo check if the user should be always found
3056 $retweeted_status["user"] = array();
3059 $rt_converted = api_convert_item($retweeted_item);
3061 $retweeted_status['text'] = $rt_converted["text"];
3062 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3063 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3064 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3065 $status['retweeted_status'] = $retweeted_status;
3069 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3070 unset($status["user"]["uid"]);
3071 unset($status["user"]["self"]);
3073 if ($item["coord"] != "") {
3074 $coords = explode(' ', $item["coord"]);
3075 if (count($coords) == 2) {
3076 if ($type == "json") {
3077 $status["geo"] = array('type' => 'Point',
3078 'coordinates' => array((float) $coords[0],
3079 (float) $coords[1]));
3080 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3081 $status["georss:point"] = $item["coord"];
3090 function api_account_rate_limit_status($type)
3092 if ($type == "xml") {
3094 'remaining-hits' => '150',
3095 '@attributes' => array("type" => "integer"),
3096 'hourly-limit' => '150',
3097 '@attributes2' => array("type" => "integer"),
3098 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
3099 '@attributes3' => array("type" => "datetime"),
3100 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3101 '@attributes4' => array("type" => "integer"),
3105 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3106 'remaining_hits' => '150',
3107 'hourly_limit' => '150',
3108 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
3112 return api_format_data('hash', $type, array('hash' => $hash));
3115 /// @TODO move to top of file or somwhere better
3116 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3118 function api_help_test($type)
3120 if ($type == 'xml') {
3126 return api_format_data('ok', $type, array("ok" => $ok));
3129 /// @TODO move to top of file or somwhere better
3130 api_register_func('api/help/test', 'api_help_test', false);
3132 function api_lists($type)
3135 /// @TODO $ret is not filled here?
3136 return api_format_data('lists', $type, array("lists_list" => $ret));
3139 /// @TODO move to top of file or somwhere better
3140 api_register_func('api/lists', 'api_lists', true);
3142 function api_lists_list($type)
3145 /// @TODO $ret is not filled here?
3146 return api_format_data('lists', $type, array("lists_list" => $ret));
3149 /// @TODO move to top of file or somwhere better
3150 api_register_func('api/lists/list', 'api_lists_list', true);
3153 * @brief Returns either the friends of the follower list
3155 * Note: Considers friends and followers lists to be private and won't return
3156 * anything if any user_id parameter is passed.
3158 * @param string $qtype Either "friends" or "followers"
3159 * @return boolean|array
3160 * @throws ForbiddenException
3162 function api_statuses_f($qtype)
3166 if (api_user() === false) {
3167 throw new ForbiddenException();
3171 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3172 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3176 $start = ($page - 1) * $count;
3178 $user_info = api_get_user($a);
3180 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3181 /* this is to stop Hotot to load friends multiple times
3182 * I'm not sure if I'm missing return something or
3183 * is a bug in hotot. Workaround, meantime
3187 return array('$users' => $ret);*/
3192 if ($qtype == 'friends') {
3193 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3194 } elseif ($qtype == 'followers') {
3195 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3198 // friends and followers only for self
3199 if ($user_info['self'] == 0) {
3200 $sql_extra = " AND false ";
3203 if ($qtype == 'blocks') {
3204 $sql_filter = 'AND `blocked` AND NOT `pending`';
3205 } elseif ($qtype == 'incoming') {
3206 $sql_filter = 'AND `pending`';
3208 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3226 foreach ($r as $cid) {
3227 $user = api_get_user($a, $cid['nurl']);
3228 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3229 unset($user["uid"]);
3230 unset($user["self"]);
3237 return array('user' => $ret);
3242 * @brief Returns the list of friends of the provided user
3244 * @deprecated By Twitter API in favor of friends/list
3246 * @param string $type Either "json" or "xml"
3247 * @return boolean|string|array
3249 function api_statuses_friends($type)
3251 $data = api_statuses_f("friends");
3252 if ($data === false) {
3255 return api_format_data("users", $type, $data);
3259 * @brief Returns the list of friends of the provided user
3261 * @deprecated By Twitter API in favor of friends/list
3263 * @param string $type Either "json" or "xml"
3264 * @return boolean|string|array
3266 function api_statuses_followers($type)
3268 $data = api_statuses_f("followers");
3269 if ($data === false) {
3272 return api_format_data("users", $type, $data);
3275 /// @TODO move to top of file or somewhere better
3276 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3277 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3280 * Returns the list of blocked users
3282 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3284 * @param string $type Either "json" or "xml"
3286 * @return boolean|string|array
3288 function api_blocks_list($type)
3290 $data = api_statuses_f('blocks');
3291 if ($data === false) {
3294 return api_format_data("users", $type, $data);
3297 /// @TODO move to top of file or somewhere better
3298 api_register_func('api/blocks/list', 'api_blocks_list', true);
3301 * Returns the list of pending users IDs
3303 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3305 * @param string $type Either "json" or "xml"
3307 * @return boolean|string|array
3309 function api_friendships_incoming($type)
3311 $data = api_statuses_f('incoming');
3312 if ($data === false) {
3317 foreach ($data['user'] as $user) {
3318 $ids[] = $user['id'];
3321 return api_format_data("ids", $type, array('id' => $ids));
3324 /// @TODO move to top of file or somewhere better
3325 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3327 function api_statusnet_config($type)
3331 $name = $a->config['sitename'];
3332 $server = $a->get_hostname();
3333 $logo = System::baseUrl() . '/images/friendica-64.png';
3334 $email = $a->config['admin_email'];
3335 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3336 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3337 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3338 if ($a->config['api_import_size']) {
3339 $textlimit = (string) $a->config['api_import_size'];
3341 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3342 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3345 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3346 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3347 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3348 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3349 'shorturllength' => '30',
3350 'friendica' => array(
3351 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3352 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3353 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3354 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3359 return api_format_data('config', $type, array('config' => $config));
3362 /// @TODO move to top of file or somewhere better
3363 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3364 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3366 function api_statusnet_version($type)
3369 $fake_statusnet_version = "0.9.7";
3371 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
3374 /// @TODO move to top of file or somewhere better
3375 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3376 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3379 * @todo use api_format_data() to return data
3381 function api_ff_ids($type, $qtype)
3386 throw new ForbiddenException();
3389 $user_info = api_get_user($a);
3391 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3394 "SELECT `pcontact`.`id` FROM `contact`
3395 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3396 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3400 if (!DBM::is_result($r)) {
3405 foreach ($r as $rr) {
3406 if ($stringify_ids) {
3409 $ids[] = intval($rr['id']);
3413 return api_format_data("ids", $type, array('id' => $ids));
3416 function api_friends_ids($type)
3418 return api_ff_ids($type, 'friends');
3421 function api_followers_ids($type)
3423 return api_ff_ids($type, 'followers');
3426 /// @TODO move to top of file or somewhere better
3427 api_register_func('api/friends/ids', 'api_friends_ids', true);
3428 api_register_func('api/followers/ids', 'api_followers_ids', true);
3430 function api_direct_messages_new($type)
3435 if (api_user() === false) {
3436 throw new ForbiddenException();
3439 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3443 $sender = api_get_user($a);
3445 if ($_POST['screen_name']) {
3447 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3449 dbesc($_POST['screen_name'])
3452 // Selecting the id by priority, friendica first
3453 api_best_nickname($r);
3455 $recipient = api_get_user($a, $r[0]['nurl']);
3457 $recipient = api_get_user($a, $_POST['user_id']);
3462 if (x($_REQUEST, 'replyto')) {
3464 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3466 intval($_REQUEST['replyto'])
3468 $replyto = $r[0]['parent-uri'];
3469 $sub = $r[0]['title'];
3471 if (x($_REQUEST, 'title')) {
3472 $sub = $_REQUEST['title'];
3474 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3478 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3481 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3482 $ret = api_format_messages($r[0], $recipient, $sender);
3484 $ret = array("error"=>$id);
3487 $data = array('direct_message'=>$ret);
3492 $data = api_rss_extra($a, $data, $user_info);
3495 return api_format_data("direct-messages", $type, $data);
3498 /// @TODO move to top of file or somewhere better
3499 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3502 * @brief delete a direct_message from mail table through api
3504 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3507 function api_direct_messages_destroy($type)
3511 if (api_user() === false) {
3512 throw new ForbiddenException();
3516 $user_info = api_get_user($a);
3518 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3520 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3521 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3522 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3524 $uid = $user_info['uid'];
3525 // error if no id or parenturi specified (for clients posting parent-uri as well)
3526 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3527 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3528 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3531 // BadRequestException if no id specified (for clients using Twitter API)
3533 throw new BadRequestException('Message id not specified');
3536 // add parent-uri to sql command if specified by calling app
3537 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3539 // get data of the specified message id
3541 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3546 // error message if specified id is not in database
3547 if (!DBM::is_result($r)) {
3548 if ($verbose == "true") {
3549 $answer = array('result' => 'error', 'message' => 'message id not in database');
3550 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3552 /// @todo BadRequestException ok for Twitter API clients?
3553 throw new BadRequestException('message id not in database');
3558 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3563 if ($verbose == "true") {
3566 $answer = array('result' => 'ok', 'message' => 'message deleted');
3567 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3569 $answer = array('result' => 'error', 'message' => 'unknown error');
3570 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3573 /// @todo return JSON data like Twitter API not yet implemented
3576 /// @TODO move to top of file or somewhere better
3577 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3579 function api_direct_messages_box($type, $box, $verbose)
3583 if (api_user() === false) {
3584 throw new ForbiddenException();
3588 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3589 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3594 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3595 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3597 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3598 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3601 unset($_REQUEST["user_id"]);
3602 unset($_GET["user_id"]);
3604 unset($_REQUEST["screen_name"]);
3605 unset($_GET["screen_name"]);
3607 $user_info = api_get_user($a);
3608 $profile_url = $user_info["url"];
3611 $start = $page * $count;
3614 if ($box=="sentbox") {
3615 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3616 } elseif ($box == "conversation") {
3617 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3618 } elseif ($box == "all") {
3619 $sql_extra = "true";
3620 } elseif ($box == "inbox") {
3621 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3625 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3628 if ($user_id != "") {
3629 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3630 } elseif ($screen_name !="") {
3631 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3635 "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",
3641 if ($verbose == "true" && !DBM::is_result($r)) {
3642 $answer = array('result' => 'error', 'message' => 'no mails available');
3643 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3647 foreach ($r as $item) {
3648 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3649 $recipient = $user_info;
3650 $sender = api_get_user($a, normalise_link($item['contact-url']));
3651 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3652 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3653 $sender = $user_info;
3656 $ret[] = api_format_messages($item, $recipient, $sender);
3660 $data = array('direct_message' => $ret);
3664 $data = api_rss_extra($a, $data, $user_info);
3667 return api_format_data("direct-messages", $type, $data);
3670 function api_direct_messages_sentbox($type)
3672 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3673 return api_direct_messages_box($type, "sentbox", $verbose);
3676 function api_direct_messages_inbox($type)
3678 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3679 return api_direct_messages_box($type, "inbox", $verbose);
3682 function api_direct_messages_all($type)
3684 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3685 return api_direct_messages_box($type, "all", $verbose);
3688 function api_direct_messages_conversation($type)
3690 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3691 return api_direct_messages_box($type, "conversation", $verbose);
3694 /// @TODO move to top of file or somewhere better
3695 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3696 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3697 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3698 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3700 function api_oauth_request_token($type)
3702 $oauth1 = new FKOAuth1();
3704 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3705 } catch (Exception $e) {
3706 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3713 function api_oauth_access_token($type)
3715 $oauth1 = new FKOAuth1();
3717 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3718 } catch (Exception $e) {
3719 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3726 /// @TODO move to top of file or somewhere better
3727 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3728 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3732 * @brief delete a complete photoalbum with all containing photos from database through api
3734 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3737 function api_fr_photoalbum_delete($type)
3739 if (api_user() === false) {
3740 throw new ForbiddenException();
3743 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3745 // we do not allow calls without album string
3747 throw new BadRequestException("no albumname specified");
3749 // check if album is existing
3751 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3755 if (!DBM::is_result($r)) {
3756 throw new BadRequestException("album not available");
3759 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3760 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3761 foreach ($r as $rr) {
3763 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3764 intval(local_user()),
3765 dbesc($rr['resource-id'])
3768 if (!DBM::is_result($photo_item)) {
3769 throw new InternalServerErrorException("problem with deleting items occured");
3771 drop_item($photo_item[0]['id'], false);
3774 // now let's delete all photos from the album
3775 $result = dba::delete('photo', array('uid' => api_user(), 'album' => $album));
3777 // return success of deletion or error message
3779 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3780 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3782 throw new InternalServerErrorException("unknown error - deleting from database failed");
3787 * @brief update the name of the album for all photos of an album
3789 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3792 function api_fr_photoalbum_update($type)
3794 if (api_user() === false) {
3795 throw new ForbiddenException();
3798 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3799 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3801 // we do not allow calls without album string
3803 throw new BadRequestException("no albumname specified");
3805 if ($album_new == "") {
3806 throw new BadRequestException("no new albumname specified");
3808 // check if album is existing
3810 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3814 if (!DBM::is_result($r)) {
3815 throw new BadRequestException("album not available");
3817 // now let's update all photos to the albumname
3819 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3825 // return success of updating or error message
3827 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3828 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3830 throw new InternalServerErrorException("unknown error - updating in database failed");
3836 * @brief list all photos of the authenticated user
3838 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3841 function api_fr_photos_list($type)
3843 if (api_user() === false) {
3844 throw new ForbiddenException();
3847 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3848 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3849 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3850 intval(local_user())
3853 'image/jpeg' => 'jpg',
3854 'image/png' => 'png',
3855 'image/gif' => 'gif'
3857 $data = array('photo'=>array());
3858 if (DBM::is_result($r)) {
3859 foreach ($r as $rr) {
3861 $photo['id'] = $rr['resource-id'];
3862 $photo['album'] = $rr['album'];
3863 $photo['filename'] = $rr['filename'];
3864 $photo['type'] = $rr['type'];
3865 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3866 $photo['created'] = $rr['created'];
3867 $photo['edited'] = $rr['edited'];
3868 $photo['desc'] = $rr['desc'];
3870 if ($type == "xml") {
3871 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3873 $photo['thumb'] = $thumb;
3874 $data['photo'][] = $photo;
3878 return api_format_data("photos", $type, $data);
3882 * @brief upload a new photo or change an existing photo
3884 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3887 function api_fr_photo_create_update($type)
3889 if (api_user() === false) {
3890 throw new ForbiddenException();
3893 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3894 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3895 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3896 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3897 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3898 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3899 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3900 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3901 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3903 // do several checks on input parameters
3904 // we do not allow calls without album string
3905 if ($album == null) {
3906 throw new BadRequestException("no albumname specified");
3908 // if photo_id == null --> we are uploading a new photo
3909 if ($photo_id == null) {
3912 // error if no media posted in create-mode
3913 if (!x($_FILES, 'media')) {
3915 throw new BadRequestException("no media data submitted");
3918 // album_new will be ignored in create-mode
3923 // check if photo is existing in database
3925 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3930 if (!DBM::is_result($r)) {
3931 throw new BadRequestException("photo not available");
3935 // checks on acl strings provided by clients
3936 $acl_input_error = false;
3937 $acl_input_error |= check_acl_input($allow_cid);
3938 $acl_input_error |= check_acl_input($deny_cid);
3939 $acl_input_error |= check_acl_input($allow_gid);
3940 $acl_input_error |= check_acl_input($deny_gid);
3941 if ($acl_input_error) {
3942 throw new BadRequestException("acl data invalid");
3944 // now let's upload the new media in create-mode
3945 if ($mode == "create") {
3946 $media = $_FILES['media'];
3947 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3949 // return success of updating or error message
3950 if (!is_null($data)) {
3951 return api_format_data("photo_create", $type, $data);
3953 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3957 // now let's do the changes in update-mode
3958 if ($mode == "update") {
3961 if (!is_null($desc)) {
3962 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3965 if (!is_null($album_new)) {
3966 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3969 if (!is_null($allow_cid)) {
3970 $allow_cid = trim($allow_cid);
3971 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3974 if (!is_null($deny_cid)) {
3975 $deny_cid = trim($deny_cid);
3976 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3979 if (!is_null($allow_gid)) {
3980 $allow_gid = trim($allow_gid);
3981 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3984 if (!is_null($deny_gid)) {
3985 $deny_gid = trim($deny_gid);
3986 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3990 if ($sql_extra != "") {
3991 $nothingtodo = false;
3993 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3995 datetime_convert(), // update edited timestamp
4001 $nothingtodo = true;
4004 if (x($_FILES, 'media')) {
4005 $nothingtodo = false;
4006 $media = $_FILES['media'];
4007 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4008 if (!is_null($data)) {
4009 return api_format_data("photo_update", $type, $data);
4013 // return success of updating or error message
4015 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
4016 return api_format_data("photo_update", $type, array('$result' => $answer));
4019 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
4020 return api_format_data("photo_update", $type, array('$result' => $answer));
4022 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4025 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4030 * @brief delete a single photo from the database through api
4032 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4035 function api_fr_photo_delete($type)
4037 if (api_user() === false) {
4038 throw new ForbiddenException();
4041 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4043 // do several checks on input parameters
4044 // we do not allow calls without photo id
4045 if ($photo_id == null) {
4046 throw new BadRequestException("no photo_id specified");
4048 // check if photo is existing in database
4050 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4054 if (!DBM::is_result($r)) {
4055 throw new BadRequestException("photo not available");
4057 // now we can perform on the deletion of the photo
4058 $result = dba::delete('photo', array('uid' => api_user(), 'resource-id' => $photo_id));
4060 // return success of deletion or error message
4062 // retrieve the id of the parent element (the photo element)
4064 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4065 intval(local_user()),
4069 if (!DBM::is_result($photo_item)) {
4070 throw new InternalServerErrorException("problem with deleting items occured");
4072 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4073 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4074 drop_item($photo_item[0]['id'], false);
4076 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
4077 return api_format_data("photo_delete", $type, array('$result' => $answer));
4079 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4085 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4087 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4090 function api_fr_photo_detail($type)
4092 if (api_user() === false) {
4093 throw new ForbiddenException();
4095 if (!x($_REQUEST, 'photo_id')) {
4096 throw new BadRequestException("No photo id.");
4099 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4100 $photo_id = $_REQUEST['photo_id'];
4102 // prepare json/xml output with data from database for the requested photo
4103 $data = prepare_photo_data($type, $scale, $photo_id);
4105 return api_format_data("photo_detail", $type, $data);
4110 * @brief updates the profile image for the user (either a specified profile or the default profile)
4112 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4115 function api_account_update_profile_image($type)
4117 if (api_user() === false) {
4118 throw new ForbiddenException();
4121 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
4123 // error if image data is missing
4124 if (!x($_FILES, 'image')) {
4125 throw new BadRequestException("no media data submitted");
4128 // check if specified profile id is valid
4129 if ($profileid != 0) {
4131 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4135 // error message if specified profile id is not in database
4136 if (!DBM::is_result($r)) {
4137 throw new BadRequestException("profile_id not available");
4139 $is_default_profile = $r['profile'];
4141 $is_default_profile = 1;
4144 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4146 if (x($_FILES, 'image')) {
4147 $media = $_FILES['image'];
4148 } elseif (x($_FILES, 'media')) {
4149 $media = $_FILES['media'];
4151 // save new profile image
4152 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4155 if (is_array($media['type'])) {
4156 $filetype = $media['type'][0];
4158 $filetype = $media['type'];
4160 if ($filetype == "image/jpeg") {
4162 } elseif ($filetype == "image/png") {
4165 // change specified profile or all profiles to the new resource-id
4166 if ($is_default_profile) {
4168 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4169 dbesc($data['photo']['id']),
4170 intval(local_user())
4174 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
4175 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4176 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4177 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4178 intval(local_user())
4182 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4183 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4184 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4185 intval($_REQUEST['profile']),
4186 intval(local_user())
4190 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4191 // so that browsers will do a cache update unconditionally
4194 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4195 dbesc(datetime_convert()),
4196 intval(local_user())
4199 // Update global directory in background
4200 //$user = api_get_user(get_app());
4201 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4202 if ($url && strlen(Config::get('system', 'directory'))) {
4203 Worker::add(PRIORITY_LOW, "Directory", $url);
4206 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4208 // output for client
4210 return api_account_verify_credentials($type);
4212 // SaveMediaToDatabase failed for some reason
4213 throw new InternalServerErrorException("image upload failed");
4217 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4218 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4219 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4220 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4221 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4222 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4223 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4224 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4225 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4228 function check_acl_input($acl_string)
4230 if ($acl_string == null || $acl_string == " ") {
4233 $contact_not_found = false;
4235 // split <x><y><z> into array of cid's
4236 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4238 // check for each cid if it is available on server
4239 $cid_array = $array[0];
4240 foreach ($cid_array as $cid) {
4241 $cid = str_replace("<", "", $cid);
4242 $cid = str_replace(">", "", $cid);
4244 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4248 $contact_not_found |= !DBM::is_result($contact);
4250 return $contact_not_found;
4253 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)
4261 if (is_array($media)) {
4262 if (is_array($media['tmp_name'])) {
4263 $src = $media['tmp_name'][0];
4265 $src = $media['tmp_name'];
4267 if (is_array($media['name'])) {
4268 $filename = basename($media['name'][0]);
4270 $filename = basename($media['name']);
4272 if (is_array($media['size'])) {
4273 $filesize = intval($media['size'][0]);
4275 $filesize = intval($media['size']);
4277 if (is_array($media['type'])) {
4278 $filetype = $media['type'][0];
4280 $filetype = $media['type'];
4284 if ($filetype == "") {
4285 $filetype=Image::guessType($filename);
4287 $imagedata = getimagesize($src);
4289 $filetype = $imagedata['mime'];
4292 "File upload src: " . $src . " - filename: " . $filename .
4293 " - size: " . $filesize . " - type: " . $filetype,
4297 // check if there was a php upload error
4298 if ($filesize == 0 && $media['error'] == 1) {
4299 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4301 // check against max upload size within Friendica instance
4302 $maximagesize = Config::get('system', 'maximagesize');
4303 if ($maximagesize && ($filesize > $maximagesize)) {
4304 $formattedBytes = formatBytes($maximagesize);
4305 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4308 // create Photo instance with the data of the image
4309 $imagedata = @file_get_contents($src);
4310 $Image = new Image($imagedata, $filetype);
4311 if (! $Image->isValid()) {
4312 throw new InternalServerErrorException("unable to process image data");
4315 // check orientation of image
4316 $Image->orient($src);
4319 // check max length of images on server
4320 $max_length = Config::get('system', 'max_image_length');
4321 if (! $max_length) {
4322 $max_length = MAX_IMAGE_LENGTH;
4324 if ($max_length > 0) {
4325 $Image->scaleDown($max_length);
4326 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4328 $width = $Image->getWidth();
4329 $height = $Image->getHeight();
4331 // create a new resource-id if not already provided
4332 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
4334 if ($mediatype == "photo") {
4335 // upload normal image (scales 0, 1, 2)
4336 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4338 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4340 logger("photo upload: image upload with scale 0 (original size) failed");
4342 if ($width > 640 || $height > 640) {
4343 $Image->scaleDown(640);
4344 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4346 logger("photo upload: image upload with scale 1 (640x640) failed");
4350 if ($width > 320 || $height > 320) {
4351 $Image->scaleDown(320);
4352 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4354 logger("photo upload: image upload with scale 2 (320x320) failed");
4357 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4358 } elseif ($mediatype == "profileimage") {
4359 // upload profile image (scales 4, 5, 6)
4360 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4362 if ($width > 175 || $height > 175) {
4363 $Image->scaleDown(175);
4364 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4366 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4370 if ($width > 80 || $height > 80) {
4371 $Image->scaleDown(80);
4372 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4374 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4378 if ($width > 48 || $height > 48) {
4379 $Image->scaleDown(48);
4380 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4382 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4385 $Image->__destruct();
4386 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4390 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4391 if ($photo_id == null && $mediatype == "photo") {
4392 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4394 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4395 return prepare_photo_data($type, false, $hash);
4397 throw new InternalServerErrorException("image upload failed");
4401 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4403 // get data about the api authenticated user
4404 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4405 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4408 $arr['guid'] = get_guid(32);
4409 $arr['uid'] = intval(api_user());
4411 $arr['parent-uri'] = $uri;
4412 $arr['type'] = 'photo';
4414 $arr['resource-id'] = $hash;
4415 $arr['contact-id'] = $owner_record[0]['id'];
4416 $arr['owner-name'] = $owner_record[0]['name'];
4417 $arr['owner-link'] = $owner_record[0]['url'];
4418 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4419 $arr['author-name'] = $owner_record[0]['name'];
4420 $arr['author-link'] = $owner_record[0]['url'];
4421 $arr['author-avatar'] = $owner_record[0]['thumb'];
4423 $arr['allow_cid'] = $allow_cid;
4424 $arr['allow_gid'] = $allow_gid;
4425 $arr['deny_cid'] = $deny_cid;
4426 $arr['deny_gid'] = $deny_gid;
4427 $arr['last-child'] = 1;
4428 $arr['visible'] = $visibility;
4432 'image/jpeg' => 'jpg',
4433 'image/png' => 'png',
4434 'image/gif' => 'gif'
4437 // adds link to the thumbnail scale photo
4438 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4439 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4442 // do the magic for storing the item in the database and trigger the federation to other contacts
4446 function prepare_photo_data($type, $scale, $photo_id)
4448 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4449 $data_sql = ($scale === false ? "" : "data, ");
4451 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4452 // clients needs to convert this in their way for further processing
4454 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4455 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4456 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4457 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4459 intval(local_user()),
4465 'image/jpeg' => 'jpg',
4466 'image/png' => 'png',
4467 'image/gif' => 'gif'
4470 // prepare output data for photo
4471 if (DBM::is_result($r)) {
4472 $data = array('photo' => $r[0]);
4473 $data['photo']['id'] = $data['photo']['resource-id'];
4474 if ($scale !== false) {
4475 $data['photo']['data'] = base64_encode($data['photo']['data']);
4477 unset($data['photo']['datasize']); //needed only with scale param
4479 if ($type == "xml") {
4480 $data['photo']['links'] = array();
4481 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4482 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4484 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4487 $data['photo']['link'] = array();
4488 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4490 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4491 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4495 unset($data['photo']['resource-id']);
4496 unset($data['photo']['minscale']);
4497 unset($data['photo']['maxscale']);
4499 throw new NotFoundException();
4502 // retrieve item element for getting activities (like, dislike etc.) related to photo
4504 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4505 intval(local_user()),
4508 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4510 // retrieve comments on photo
4512 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4513 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4514 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4515 `contact`.`id` AS `cid`
4517 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4518 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4519 WHERE `item`.`parent` = %d AND `item`.`visible`
4520 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4521 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4522 intval($item[0]['parent']),
4524 dbesc(ACTIVITY_POST)
4527 // prepare output of comments
4528 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4529 $comments = array();
4530 if ($type == "xml") {
4532 foreach ($commentData as $comment) {
4533 $comments[$k++ . ":comment"] = $comment;
4536 foreach ($commentData as $comment) {
4537 $comments[] = $comment;
4540 $data['photo']['friendica_comments'] = $comments;
4542 // include info if rights on photo and rights on item are mismatching
4543 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4544 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4545 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4546 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4547 $data['photo']['rights_mismatch'] = $rights_mismatch;
4554 * Similar as /mod/redir.php
4555 * redirect to 'url' after dfrn auth
4557 * Why this when there is mod/redir.php already?
4558 * This use api_user() and api_login()
4561 * c_url: url of remote contact to auth to
4562 * url: string, url to redirect after auth
4564 function api_friendica_remoteauth()
4566 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4567 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4569 if ($url === '' || $c_url === '') {
4570 throw new BadRequestException("Wrong parameters.");
4573 $c_url = normalise_link($c_url);
4577 $r = dba::select('contact', [], ['uid' => api_user(), 'nurl' => $c_url], ['limit' => 1]);
4579 if (!DBM::is_result($r) || ($r['network'] !== NETWORK_DFRN)) {
4580 throw new BadRequestException("Unknown contact");
4585 $dfrn_id = $orig_id = (($r['issued-id']) ? $r['issued-id'] : $r['dfrn-id']);
4587 if ($r['duplex'] && $r['issued-id']) {
4588 $orig_id = $r['issued-id'];
4589 $dfrn_id = '1:' . $orig_id;
4591 if ($r['duplex'] && $r['dfrn-id']) {
4592 $orig_id = $r['dfrn-id'];
4593 $dfrn_id = '0:' . $orig_id;
4596 $sec = random_string();
4599 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4600 VALUES( %d, %s, '%s', '%s', %d )",
4608 logger($r['name'] . ' ' . $sec, LOGGER_DEBUG);
4609 $dest = ($url ? '&destination_url=' . $url : '');
4611 $r['poll'] . '?dfrn_id=' . $dfrn_id
4612 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4613 . '&type=profile&sec=' . $sec . $dest . $quiet
4616 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4619 * @brief Return the item shared, if the item contains only the [share] tag
4621 * @param array $item Sharer item
4622 * @return array|false Shared item or false if not a reshare
4624 function api_share_as_retweet(&$item)
4626 $body = trim($item["body"]);
4628 if (Diaspora::isReshare($body, false)===false) {
4632 /// @TODO "$1" should maybe mean '$1' ?
4633 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4635 * Skip if there is no shared message in there
4636 * we already checked this in diaspora::isReshare()
4637 * but better one more than one less...
4639 if ($body == $attributes) {
4644 // build the fake reshared item
4645 $reshared_item = $item;
4648 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4649 if ($matches[1] != "") {
4650 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4653 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4654 if ($matches[1] != "") {
4655 $author = $matches[1];
4659 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4660 if ($matches[1] != "") {
4661 $profile = $matches[1];
4664 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4665 if ($matches[1] != "") {
4666 $profile = $matches[1];
4670 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4671 if ($matches[1] != "") {
4672 $avatar = $matches[1];
4675 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4676 if ($matches[1] != "") {
4677 $avatar = $matches[1];
4681 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4682 if ($matches[1] != "") {
4683 $link = $matches[1];
4686 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4687 if ($matches[1] != "") {
4688 $link = $matches[1];
4692 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4693 if ($matches[1] != "") {
4694 $posted = $matches[1];
4697 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4698 if ($matches[1] != "") {
4699 $posted = $matches[1];
4702 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4704 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4708 $reshared_item["body"] = $shared_body;
4709 $reshared_item["author-name"] = $author;
4710 $reshared_item["author-link"] = $profile;
4711 $reshared_item["author-avatar"] = $avatar;
4712 $reshared_item["plink"] = $link;
4713 $reshared_item["created"] = $posted;
4714 $reshared_item["edited"] = $posted;
4716 return $reshared_item;
4719 function api_get_nick($profile)
4722 - remove trailing junk from profile url
4723 - pump.io check has to check the website
4729 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4730 dbesc(normalise_link($profile))
4733 if (DBM::is_result($r)) {
4734 $nick = $r[0]["nick"];
4739 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4740 dbesc(normalise_link($profile))
4743 if (DBM::is_result($r)) {
4744 $nick = $r[0]["nick"];
4749 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4750 if ($friendica != $profile) {
4756 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4757 if ($diaspora != $profile) {
4763 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4764 if ($twitter != $profile) {
4771 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4772 if ($StatusnetHost != $profile) {
4773 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4774 if ($StatusnetUser != $profile) {
4775 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4776 $user = json_decode($UserData);
4778 $nick = $user->screen_name;
4784 // To-Do: look at the page if its really a pumpio site
4785 //if (!$nick == "") {
4786 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4787 // if ($pumpio != $profile)
4789 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4800 function api_in_reply_to($item)
4802 $in_reply_to = array();
4804 $in_reply_to['status_id'] = null;
4805 $in_reply_to['user_id'] = null;
4806 $in_reply_to['status_id_str'] = null;
4807 $in_reply_to['user_id_str'] = null;
4808 $in_reply_to['screen_name'] = null;
4810 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4812 "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4813 intval($item['uid']),
4814 dbesc($item['thr-parent'])
4817 if (DBM::is_result($r)) {
4818 $in_reply_to['status_id'] = intval($r[0]['id']);
4820 $in_reply_to['status_id'] = intval($item['parent']);
4823 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4826 "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4827 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4828 WHERE `item`.`id` = %d LIMIT 1",
4829 intval($in_reply_to['status_id'])
4832 if (DBM::is_result($r)) {
4833 if ($r[0]['nick'] == "") {
4834 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4837 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4838 $in_reply_to['user_id'] = intval($r[0]['id']);
4839 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4842 // There seems to be situation, where both fields are identical:
4843 // https://github.com/friendica/friendica/issues/1010
4844 // This is a bugfix for that.
4845 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4846 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4847 $in_reply_to['status_id'] = null;
4848 $in_reply_to['user_id'] = null;
4849 $in_reply_to['status_id_str'] = null;
4850 $in_reply_to['user_id_str'] = null;
4851 $in_reply_to['screen_name'] = null;
4855 return $in_reply_to;
4858 function api_clean_plain_items($Text)
4860 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4862 $Text = bb_CleanPictureLinks($Text);
4863 $URLSearchString = "^\[\]";
4865 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
4867 if ($include_entities == "true") {
4868 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
4871 // Simplify "attachment" element
4872 $Text = api_clean_attachments($Text);
4878 * @brief Removes most sharing information for API text export
4880 * @param string $body The original body
4882 * @return string Cleaned body
4884 function api_clean_attachments($body)
4886 $data = get_attachment_data($body);
4893 if (isset($data["text"])) {
4894 $body = $data["text"];
4896 if (($body == "") && isset($data["title"])) {
4897 $body = $data["title"];
4899 if (isset($data["url"])) {
4900 $body .= "\n".$data["url"];
4902 $body .= $data["after"];
4907 function api_best_nickname(&$contacts)
4909 $best_contact = array();
4911 if (count($contact) == 0) {
4915 foreach ($contacts as $contact) {
4916 if ($contact["network"] == "") {
4917 $contact["network"] = "dfrn";
4918 $best_contact = array($contact);
4922 if (sizeof($best_contact) == 0) {
4923 foreach ($contacts as $contact) {
4924 if ($contact["network"] == "dfrn") {
4925 $best_contact = array($contact);
4930 if (sizeof($best_contact) == 0) {
4931 foreach ($contacts as $contact) {
4932 if ($contact["network"] == "dspr") {
4933 $best_contact = array($contact);
4938 if (sizeof($best_contact) == 0) {
4939 foreach ($contacts as $contact) {
4940 if ($contact["network"] == "stat") {
4941 $best_contact = array($contact);
4946 if (sizeof($best_contact) == 0) {
4947 foreach ($contacts as $contact) {
4948 if ($contact["network"] == "pump") {
4949 $best_contact = array($contact);
4954 if (sizeof($best_contact) == 0) {
4955 foreach ($contacts as $contact) {
4956 if ($contact["network"] == "twit") {
4957 $best_contact = array($contact);
4962 if (sizeof($best_contact) == 1) {
4963 $contacts = $best_contact;
4965 $contacts = array($contacts[0]);
4969 // return all or a specified group of the user with the containing contacts
4970 function api_friendica_group_show($type)
4974 if (api_user() === false) {
4975 throw new ForbiddenException();
4979 $user_info = api_get_user($a);
4980 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4981 $uid = $user_info['uid'];
4983 // get data of the specified group id or all groups if not specified
4986 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4990 // error message if specified gid is not in database
4991 if (!DBM::is_result($r)) {
4992 throw new BadRequestException("gid not available");
4996 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5001 // loop through all groups and retrieve all members for adding data in the user array
5002 foreach ($r as $rr) {
5003 $members = Contact::getByGroupId($rr['id']);
5006 if ($type == "xml") {
5007 $user_element = "users";
5009 foreach ($members as $member) {
5010 $user = api_get_user($a, $member['nurl']);
5011 $users[$k++.":user"] = $user;
5014 $user_element = "user";
5015 foreach ($members as $member) {
5016 $user = api_get_user($a, $member['nurl']);
5020 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
5022 return api_format_data("groups", $type, array('group' => $grps));
5024 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5027 // delete the specified group of the user
5028 function api_friendica_group_delete($type)
5032 if (api_user() === false) {
5033 throw new ForbiddenException();
5037 $user_info = api_get_user($a);
5038 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5039 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5040 $uid = $user_info['uid'];
5042 // error if no gid specified
5043 if ($gid == 0 || $name == "") {
5044 throw new BadRequestException('gid or name not specified');
5047 // get data of the specified group id
5049 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5053 // error message if specified gid is not in database
5054 if (!DBM::is_result($r)) {
5055 throw new BadRequestException('gid not available');
5058 // get data of the specified group id and group name
5060 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5065 // error message if specified gid is not in database
5066 if (!DBM::is_result($rname)) {
5067 throw new BadRequestException('wrong group name');
5071 $ret = Group::removeByName($uid, $name);
5074 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
5075 return api_format_data("group_delete", $type, array('result' => $success));
5077 throw new BadRequestException('other API error');
5080 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5083 // create the specified group with the posted array of contacts
5084 function api_friendica_group_create($type)
5088 if (api_user() === false) {
5089 throw new ForbiddenException();
5093 $user_info = api_get_user($a);
5094 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5095 $uid = $user_info['uid'];
5096 $json = json_decode($_POST['json'], true);
5097 $users = $json['user'];
5099 // error if no name specified
5101 throw new BadRequestException('group name not specified');
5104 // get data of the specified group name
5106 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5110 // error message if specified group name already exists
5111 if (DBM::is_result($rname)) {
5112 throw new BadRequestException('group name already exists');
5115 // check if specified group name is a deleted group
5117 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5121 // error message if specified group name already exists
5122 if (DBM::is_result($rname)) {
5123 $reactivate_group = true;
5127 $ret = Group::create($uid, $name);
5129 $gid = Group::getIdByName($uid, $name);
5131 throw new BadRequestException('other API error');
5135 $erroraddinguser = false;
5136 $errorusers = array();
5137 foreach ($users as $user) {
5138 $cid = $user['cid'];
5139 // check if user really exists as contact
5141 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5145 if (count($contact)) {
5146 $result = Group::addMember($gid, $cid);
5148 $erroraddinguser = true;
5149 $errorusers[] = $cid;
5153 // return success message incl. missing users in array
5154 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
5155 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
5156 return api_format_data("group_create", $type, array('result' => $success));
5158 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5161 // update the specified group with the posted array of contacts
5162 function api_friendica_group_update($type)
5166 if (api_user() === false) {
5167 throw new ForbiddenException();
5171 $user_info = api_get_user($a);
5172 $uid = $user_info['uid'];
5173 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5174 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5175 $json = json_decode($_POST['json'], true);
5176 $users = $json['user'];
5178 // error if no name specified
5180 throw new BadRequestException('group name not specified');
5183 // error if no gid specified
5185 throw new BadRequestException('gid not specified');
5189 $members = Contact::getByGroupId($gid);
5190 foreach ($members as $member) {
5191 $cid = $member['id'];
5192 foreach ($users as $user) {
5193 $found = ($user['cid'] == $cid ? true : false);
5196 $ret = Group::removeMemberByName($uid, $name, $cid);
5201 $erroraddinguser = false;
5202 $errorusers = array();
5203 foreach ($users as $user) {
5204 $cid = $user['cid'];
5205 // check if user really exists as contact
5207 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5212 if (count($contact)) {
5213 $result = Group::addMember($gid, $cid);
5215 $erroraddinguser = true;
5216 $errorusers[] = $cid;
5220 // return success message incl. missing users in array
5221 $status = ($erroraddinguser ? "missing user" : "ok");
5222 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
5223 return api_format_data("group_update", $type, array('result' => $success));
5226 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5228 function api_friendica_activity($type)
5232 if (api_user() === false) {
5233 throw new ForbiddenException();
5235 $verb = strtolower($a->argv[3]);
5236 $verb = preg_replace("|\..*$|", "", $verb);
5238 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5240 $res = do_like($id, $verb);
5243 if ($type == "xml") {
5248 return api_format_data('ok', $type, array('ok' => $ok));
5250 throw new BadRequestException('Error adding activity');
5254 /// @TODO move to top of file or somwhere better
5255 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5256 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5257 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5258 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5259 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5260 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5261 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5262 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5263 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5264 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5267 * @brief Returns notifications
5269 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5272 function api_friendica_notification($type)
5276 if (api_user() === false) {
5277 throw new ForbiddenException();
5280 throw new BadRequestException("Invalid argument count");
5282 $nm = new NotificationsManager();
5284 $notes = $nm->getAll(array(), "+seen -date", 50);
5286 if ($type == "xml") {
5287 $xmlnotes = array();
5288 foreach ($notes as $note) {
5289 $xmlnotes[] = array("@attributes" => $note);
5295 return api_format_data("notes", $type, array('note' => $notes));
5299 * @brief Set notification as seen and returns associated item (if possible)
5301 * POST request with 'id' param as notification id
5303 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5306 function api_friendica_notification_seen($type)
5310 if (api_user() === false) {
5311 throw new ForbiddenException();
5314 throw new BadRequestException("Invalid argument count");
5317 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5319 $nm = new NotificationsManager();
5320 $note = $nm->getByID($id);
5321 if (is_null($note)) {
5322 throw new BadRequestException("Invalid argument");
5325 $nm->setSeen($note);
5326 if ($note['otype']=='item') {
5327 // would be really better with an ItemsManager and $im->getByID() :-P
5329 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5330 intval($note['iid']),
5331 intval(local_user())
5334 // we found the item, return it to the user
5335 $user_info = api_get_user($a);
5336 $ret = api_format_items($r, $user_info, false, $type);
5337 $data = array('status' => $ret);
5338 return api_format_data("status", $type, $data);
5340 // the item can't be found, but we set the note as seen, so we count this as a success
5342 return api_format_data('result', $type, array('result' => "success"));
5345 /// @TODO move to top of file or somwhere better
5346 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5347 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5350 * @brief update a direct_message to seen state
5352 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5353 * @return string (success result=ok, error result=error with error message)
5355 function api_friendica_direct_messages_setseen($type)
5358 if (api_user() === false) {
5359 throw new ForbiddenException();
5363 $user_info = api_get_user($a);
5364 $uid = $user_info['uid'];
5365 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5367 // return error if id is zero
5369 $answer = array('result' => 'error', 'message' => 'message id not specified');
5370 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5373 // get data of the specified message id
5375 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5380 // error message if specified id is not in database
5381 if (!DBM::is_result($r)) {
5382 $answer = array('result' => 'error', 'message' => 'message id not in database');
5383 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5386 // update seen indicator
5388 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5395 $answer = array('result' => 'ok', 'message' => 'message set to seen');
5396 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
5398 $answer = array('result' => 'error', 'message' => 'unknown error');
5399 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5403 /// @TODO move to top of file or somwhere better
5404 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5407 * @brief search for direct_messages containing a searchstring through api
5409 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5410 * @return string (success: success=true if found and search_result contains found messages
5411 * success=false if nothing was found, search_result='nothing found',
5412 * error: result=error with error message)
5414 function api_friendica_direct_messages_search($type)
5418 if (api_user() === false) {
5419 throw new ForbiddenException();
5423 $user_info = api_get_user($a);
5424 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5425 $uid = $user_info['uid'];
5427 // error if no searchstring specified
5428 if ($searchstring == "") {
5429 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
5430 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
5433 // get data for the specified searchstring
5435 "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",
5437 dbesc('%'.$searchstring.'%')
5440 $profile_url = $user_info["url"];
5442 // message if nothing was found
5443 if (!DBM::is_result($r)) {
5444 $success = array('success' => false, 'search_results' => 'problem with query');
5445 } elseif (count($r) == 0) {
5446 $success = array('success' => false, 'search_results' => 'nothing found');
5449 foreach ($r as $item) {
5450 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5451 $recipient = $user_info;
5452 $sender = api_get_user($a, normalise_link($item['contact-url']));
5453 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5454 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5455 $sender = $user_info;
5458 $ret[] = api_format_messages($item, $recipient, $sender);
5460 $success = array('success' => true, 'search_results' => $ret);
5463 return api_format_data("direct_message_search", $type, array('$result' => $success));
5466 /// @TODO move to top of file or somwhere better
5467 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5470 * @brief return data of all the profiles a user has to the client
5472 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5475 function api_friendica_profile_show($type)
5479 if (api_user() === false) {
5480 throw new ForbiddenException();
5484 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5486 // retrieve general information about profiles for user
5487 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5488 $directory = Config::get('system', 'directory');
5490 // get data of the specified profile id or all profiles of the user if not specified
5491 if ($profileid != 0) {
5493 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5498 // error message if specified gid is not in database
5499 if (!DBM::is_result($r)) {
5500 throw new BadRequestException("profile_id not available");
5504 "SELECT * FROM `profile` WHERE `uid` = %d",
5508 // loop through all returned profiles and retrieve data and users
5510 foreach ($r as $rr) {
5511 $profile = api_format_items_profiles($rr, $type);
5513 // select all users from contact table, loop and prepare standard return for user data
5516 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5518 intval($rr['profile_id'])
5521 foreach ($r as $rr) {
5522 $user = api_get_user($a, $rr['nurl']);
5523 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5525 $profile['users'] = $users;
5527 // add prepared profile data to array for final return
5528 if ($type == "xml") {
5529 $profiles[$k++ . ":profile"] = $profile;
5531 $profiles[] = $profile;
5535 // return settings, authenticated user and profiles data
5536 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5538 $result = array('multi_profiles' => $multi_profiles ? true : false,
5539 'global_dir' => $directory,
5540 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5541 'profiles' => $profiles);
5542 return api_format_data("friendica_profiles", $type, array('$result' => $result));
5544 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5547 * Returns a list of saved searches.
5549 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5551 * @param string $type Return format: json or xml
5553 * @return string|array
5555 function api_saved_searches_list($type)
5557 $terms = dba::select('search', array('id', 'term'), array('uid' => local_user()));
5560 while ($term = $terms->fetch()) {
5562 'name' => $term['term'],
5563 'query' => $term['term'],
5564 'id_str' => $term['id'],
5565 'id' => intval($term['id'])
5571 return api_format_data("terms", $type, array('terms' => $result));
5574 /// @TODO move to top of file or somwhere better
5575 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5578 @TODO Maybe open to implement?
5580 [pagename] => api/1.1/statuses/lookup.json
5581 [id] => 605138389168451584
5582 [include_cards] => true
5583 [cards_platform] => Android-12
5584 [include_entities] => true
5585 [include_my_retweet] => 1
5587 [include_reply_count] => true
5588 [include_descendent_reply_count] => true
5592 Not implemented by now:
5593 statuses/retweets_of_me
5598 account/update_location
5599 account/update_profile_background_image
5602 friendica/profile/update
5603 friendica/profile/create
5604 friendica/profile/delete
5606 Not implemented in status.net:
5607 statuses/retweeted_to_me
5608 statuses/retweeted_by_me
5609 direct_messages/destroy
5611 account/update_delivery_device
5612 notifications/follow