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");
371 $json = json_encode($rr);
372 if (x($_GET, 'callback')) {
373 $json = $_GET['callback'] . "(" . $json . ")";
378 header("Content-Type: application/rss+xml");
379 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
382 header("Content-Type: application/atom+xml");
383 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
389 logger('API call not implemented: ' . $a->query_string);
390 throw new NotImplementedException();
391 } catch (HTTPException $e) {
392 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
393 return api_error($type, $e);
398 * @brief Format API error string
400 * @param string $type Return type (xml, json, rss, as)
401 * @param object $e HTTPException Error object
402 * @return strin error message formatted as $type
404 function api_error($type, $e)
408 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
409 /// @TODO: https://dev.twitter.com/overview/api/response-codes
411 $error = array("error" => $error,
412 "code" => $e->httpcode . " " . $e->httpdesc,
413 "request" => $a->query_string);
415 $ret = api_format_data('status', $type, array('status' => $error));
419 header("Content-Type: text/xml");
423 header("Content-Type: application/json");
424 return json_encode($ret);
427 header("Content-Type: application/rss+xml");
431 header("Content-Type: application/atom+xml");
438 * @brief Set values for RSS template
441 * @param array $arr Array to be passed to template
442 * @param array $user_info User info
444 * @todo find proper type-hints
446 function api_rss_extra(App $a, $arr, $user_info)
448 if (is_null($user_info)) {
449 $user_info = api_get_user($a);
452 $arr['$user'] = $user_info;
453 $arr['$rss'] = array(
454 'alternate' => $user_info['url'],
455 'self' => System::baseUrl() . "/" . $a->query_string,
456 'base' => System::baseUrl(),
457 'updated' => api_date(null),
458 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
459 'language' => $user_info['language'],
460 'logo' => System::baseUrl() . "/images/friendica-32.png",
468 * @brief Unique contact to contact url.
470 * @param int $id Contact id
471 * @return bool|string
472 * Contact url or False if contact id is unknown
474 function api_unique_id_to_nurl($id)
476 $r = dba::select('contact', array('nurl'), array('uid' => 0, 'id' => $id), array('limit' => 1));
478 if (DBM::is_result($r)) {
486 * @brief Get user info array.
488 * @param object $a App
489 * @param int|string $contact_id Contact ID or URL
491 function api_get_user(App $a, $contact_id = null)
500 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
502 // Searching for contact URL
503 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
504 $user = dbesc(normalise_link($contact_id));
506 $extra_query = "AND `contact`.`nurl` = '%s' ";
507 if (api_user() !== false) {
508 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
512 // Searching for contact id with uid = 0
513 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
514 $user = dbesc(api_unique_id_to_nurl($contact_id));
517 throw new BadRequestException("User not found.");
521 $extra_query = "AND `contact`.`nurl` = '%s' ";
522 if (api_user() !== false) {
523 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
527 if (is_null($user) && x($_GET, 'user_id')) {
528 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
531 throw new BadRequestException("User not found.");
535 $extra_query = "AND `contact`.`nurl` = '%s' ";
536 if (api_user() !== false) {
537 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
540 if (is_null($user) && x($_GET, 'screen_name')) {
541 $user = dbesc($_GET['screen_name']);
543 $extra_query = "AND `contact`.`nick` = '%s' ";
544 if (api_user() !== false) {
545 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
549 if (is_null($user) && x($_GET, 'profileurl')) {
550 $user = dbesc(normalise_link($_GET['profileurl']));
552 $extra_query = "AND `contact`.`nurl` = '%s' ";
553 if (api_user() !== false) {
554 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
558 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
559 $argid = count($called_api);
560 list($user, $null) = explode(".", $a->argv[$argid]);
561 if (is_numeric($user)) {
562 $user = dbesc(api_unique_id_to_nurl($user));
569 $extra_query = "AND `contact`.`nurl` = '%s' ";
570 if (api_user() !== false) {
571 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
574 $user = dbesc($user);
576 $extra_query = "AND `contact`.`nick` = '%s' ";
577 if (api_user() !== false) {
578 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
583 logger("api_get_user: user ".$user, LOGGER_DEBUG);
586 if (api_user() === false) {
590 $user = $_SESSION['uid'];
591 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
595 logger('api_user: ' . $extra_query . ', user: ' . $user);
599 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
605 // Selecting the id by priority, friendica first
606 api_best_nickname($uinfo);
608 // if the contact wasn't found, fetch it from the contacts with uid = 0
609 if (!DBM::is_result($uinfo)) {
613 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
616 if (DBM::is_result($r)) {
617 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
619 // If no nick where given, extract it from the address
620 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
621 $r[0]['nick'] = api_get_nick($r[0]["url"]);
626 'id_str' => (string) $r[0]["id"],
627 'name' => $r[0]["name"],
628 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
629 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
630 'description' => $r[0]["about"],
631 'profile_image_url' => $r[0]["micro"],
632 'profile_image_url_https' => $r[0]["micro"],
633 'url' => $r[0]["url"],
634 'protected' => false,
635 'followers_count' => 0,
636 'friends_count' => 0,
638 'created_at' => api_date($r[0]["created"]),
639 'favourites_count' => 0,
641 'time_zone' => 'UTC',
642 'geo_enabled' => false,
644 'statuses_count' => 0,
646 'contributors_enabled' => false,
647 'is_translator' => false,
648 'is_translation_enabled' => false,
649 'following' => false,
650 'follow_request_sent' => false,
651 'statusnet_blocking' => false,
652 'notifications' => false,
653 'statusnet_profile_url' => $r[0]["url"],
655 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
657 'network' => $r[0]["network"],
662 throw new BadRequestException("User not found.");
666 if ($uinfo[0]['self']) {
667 if ($uinfo[0]['network'] == "") {
668 $uinfo[0]['network'] = NETWORK_DFRN;
672 "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
676 "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
680 /// @TODO old-lost code? (twice)
681 // Counting is deactivated by now, due to performance issues
682 // count public wall messages
683 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
684 // intval($uinfo[0]['uid'])
686 //$countitms = $r[0]['count'];
689 // Counting is deactivated by now, due to performance issues
690 //$r = q("SELECT count(*) as `count` FROM `item`
691 // WHERE `contact-id` = %d",
692 // intval($uinfo[0]['id'])
694 //$countitms = $r[0]['count'];
698 /// @TODO old-lost code? (twice)
700 // Counting is deactivated by now, due to performance issues
702 $r = q("SELECT count(*) as `count` FROM `contact`
703 WHERE `uid` = %d AND `rel` IN ( %d, %d )
704 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
705 intval($uinfo[0]['uid']),
706 intval(CONTACT_IS_SHARING),
707 intval(CONTACT_IS_FRIEND)
709 $countfriends = $r[0]['count'];
711 $r = q("SELECT count(*) as `count` FROM `contact`
712 WHERE `uid` = %d AND `rel` IN ( %d, %d )
713 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
714 intval($uinfo[0]['uid']),
715 intval(CONTACT_IS_FOLLOWER),
716 intval(CONTACT_IS_FRIEND)
718 $countfollowers = $r[0]['count'];
720 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
721 intval($uinfo[0]['uid'])
723 $starred = $r[0]['count'];
726 if (! $uinfo[0]['self']) {
736 // Add a nick if it isn't present there
737 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
738 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
741 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
743 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
746 'id' => intval($pcontact_id),
747 'id_str' => (string) intval($pcontact_id),
748 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
749 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
750 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
751 'description' => (($profile) ? $profile[0]['pdesc'] : null),
752 'profile_image_url' => $uinfo[0]['micro'],
753 'profile_image_url_https' => $uinfo[0]['micro'],
754 'url' => $uinfo[0]['url'],
755 'protected' => false,
756 'followers_count' => intval($countfollowers),
757 'friends_count' => intval($countfriends),
759 'created_at' => api_date($uinfo[0]['created']),
760 'favourites_count' => intval($starred),
762 'time_zone' => 'UTC',
763 'geo_enabled' => false,
765 'statuses_count' => intval($countitms),
767 'contributors_enabled' => false,
768 'is_translator' => false,
769 'is_translation_enabled' => false,
770 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
771 'follow_request_sent' => false,
772 'statusnet_blocking' => false,
773 'notifications' => false,
775 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
776 'statusnet_profile_url' => $uinfo[0]['url'],
777 'uid' => intval($uinfo[0]['uid']),
778 'cid' => intval($uinfo[0]['cid']),
779 'self' => $uinfo[0]['self'],
780 'network' => $uinfo[0]['network'],
783 // If this is a local user and it uses Frio, we can get its color preferences.
785 $theme_info = dba::select('user', ['theme'], ['uid' => $ret['uid']], ['limit' => 1]);
786 if ($theme_info['theme'] === 'frio') {
787 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
788 if ($schema && ($schema != '---')) {
789 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
790 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
791 require_once $schemefile;
794 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
795 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
796 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
802 $link_color = "#6fdbe8";
805 $bgcolor = "#ededed";
808 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
809 $ret['profile_link_color'] = str_replace('#', '', $link_color);
810 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
818 * @brief return api-formatted array for item's author and owner
820 * @param object $a App
821 * @param array $item item from db
822 * @return array(array:author, array:owner)
824 function api_item_get_user(App $a, $item)
826 $status_user = api_get_user($a, $item["author-link"]);
828 $status_user["protected"] = (($item["allow_cid"] != "") ||
829 ($item["allow_gid"] != "") ||
830 ($item["deny_cid"] != "") ||
831 ($item["deny_gid"] != "") ||
834 if ($item['thr-parent'] == $item['uri']) {
835 $owner_user = api_get_user($a, $item["owner-link"]);
837 $owner_user = $status_user;
840 return (array($status_user, $owner_user));
844 * @brief walks recursively through an array with the possibility to change value and key
846 * @param array $array The array to walk through
847 * @param string $callback The callback function
849 * @return array the transformed array
851 function api_walk_recursive(array &$array, callable $callback)
853 $new_array = array();
855 foreach ($array as $k => $v) {
857 if ($callback($v, $k)) {
858 $new_array[$k] = api_walk_recursive($v, $callback);
861 if ($callback($v, $k)) {
872 * @brief Callback function to transform the array in an array that can be transformed in a XML file
874 * @param mixed $item Array item value
875 * @param string $key Array key
877 * @return boolean Should the array item be deleted?
879 function api_reformat_xml(&$item, &$key)
881 if (is_bool($item)) {
882 $item = ($item ? "true" : "false");
885 if (substr($key, 0, 10) == "statusnet_") {
886 $key = "statusnet:".substr($key, 10);
887 } elseif (substr($key, 0, 10) == "friendica_") {
888 $key = "friendica:".substr($key, 10);
890 /// @TODO old-lost code?
892 // $key = "default:".$key;
898 * @brief Creates the XML from a JSON style array
900 * @param array $data JSON style array
901 * @param string $root_element Name of the root element
903 * @return string The XML data
905 function api_create_xml($data, $root_element)
907 $childname = key($data);
908 $data2 = array_pop($data);
911 $namespaces = array("" => "http://api.twitter.com",
912 "statusnet" => "http://status.net/schema/api/1/",
913 "friendica" => "http://friendi.ca/schema/api/1/",
914 "georss" => "http://www.georss.org/georss");
916 /// @todo Auto detection of needed namespaces
917 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
918 $namespaces = array();
921 if (is_array($data2)) {
922 api_walk_recursive($data2, "api_reformat_xml");
929 foreach ($data2 as $item) {
930 $data4[$i++.":".$childname] = $item;
936 $data3 = array($root_element => $data2);
938 $ret = XML::fromArray($data3, $xml, false, $namespaces);
943 * @brief Formats the data according to the data type
945 * @param string $root_element Name of the root element
946 * @param string $type Return type (atom, rss, xml, json)
947 * @param array $data JSON style array
949 * @return (string|object) XML data or JSON data
951 function api_format_data($root_element, $type, $data)
959 $ret = api_create_xml($data, $root_element);
974 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
975 * returns a 401 status code and an error message if not.
976 * http://developer.twitter.com/doc/get/account/verify_credentials
978 function api_account_verify_credentials($type)
983 if (api_user() === false) {
984 throw new ForbiddenException();
987 unset($_REQUEST["user_id"]);
988 unset($_GET["user_id"]);
990 unset($_REQUEST["screen_name"]);
991 unset($_GET["screen_name"]);
993 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
995 $user_info = api_get_user($a);
997 // "verified" isn't used here in the standard
998 unset($user_info["verified"]);
1000 // - Adding last status
1001 if (!$skip_status) {
1002 $user_info["status"] = api_status_show("raw");
1003 if (!count($user_info["status"])) {
1004 unset($user_info["status"]);
1006 unset($user_info["status"]["user"]);
1010 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1011 unset($user_info["uid"]);
1012 unset($user_info["self"]);
1014 return api_format_data("user", $type, array('user' => $user_info));
1017 /// @TODO move to top of file or somwhere better
1018 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1021 * Get data from $_POST or $_GET
1023 function requestdata($k)
1025 if (x($_POST, $k)) {
1034 /*Waitman Gobble Mod*/
1035 function api_statuses_mediap($type)
1039 if (api_user() === false) {
1040 logger('api_statuses_update: no user');
1041 throw new ForbiddenException();
1043 $user_info = api_get_user($a);
1045 $_REQUEST['type'] = 'wall';
1046 $_REQUEST['profile_uid'] = api_user();
1047 $_REQUEST['api_source'] = true;
1048 $txt = requestdata('status');
1049 /// @TODO old-lost code?
1050 //$txt = urldecode(requestdata('status'));
1052 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1053 $txt = html2bb_video($txt);
1054 $config = HTMLPurifier_Config::createDefault();
1055 $config->set('Cache.DefinitionImpl', null);
1056 $purifier = new HTMLPurifier($config);
1057 $txt = $purifier->purify($txt);
1059 $txt = html2bbcode($txt);
1061 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1063 // tell wall_upload function to return img info instead of echo
1064 $_REQUEST['hush'] = 'yeah';
1065 $bebop = wall_upload_post($a);
1067 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1068 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1071 // this should output the last post (the one we just posted).
1072 return api_status_show($type);
1075 /// @TODO move this to top of file or somewhere better!
1076 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1078 function api_statuses_update($type)
1083 if (api_user() === false) {
1084 logger('api_statuses_update: no user');
1085 throw new ForbiddenException();
1088 $user_info = api_get_user($a);
1090 // convert $_POST array items to the form we use for web posts.
1092 // logger('api_post: ' . print_r($_POST,true));
1094 if (requestdata('htmlstatus')) {
1095 $txt = requestdata('htmlstatus');
1096 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1097 $txt = html2bb_video($txt);
1099 $config = HTMLPurifier_Config::createDefault();
1100 $config->set('Cache.DefinitionImpl', null);
1102 $purifier = new HTMLPurifier($config);
1103 $txt = $purifier->purify($txt);
1105 $_REQUEST['body'] = html2bbcode($txt);
1108 $_REQUEST['body'] = requestdata('status');
1111 $_REQUEST['title'] = requestdata('title');
1113 $parent = requestdata('in_reply_to_status_id');
1115 // Twidere sends "-1" if it is no reply ...
1116 if ($parent == -1) {
1120 if (ctype_digit($parent)) {
1121 $_REQUEST['parent'] = $parent;
1123 $_REQUEST['parent_uri'] = $parent;
1126 if (requestdata('lat') && requestdata('long')) {
1127 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1129 $_REQUEST['profile_uid'] = api_user();
1132 $_REQUEST['type'] = 'net-comment';
1134 // Check for throttling (maximum posts per day, week and month)
1135 $throttle_day = Config::get('system', 'throttle_limit_day');
1136 if ($throttle_day > 0) {
1137 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1140 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1141 AND `created` > '%s' AND `id` = `parent`",
1146 if (DBM::is_result($r)) {
1147 $posts_day = $r[0]["posts_day"];
1152 if ($posts_day > $throttle_day) {
1153 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1154 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1155 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1159 $throttle_week = Config::get('system', 'throttle_limit_week');
1160 if ($throttle_week > 0) {
1161 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1164 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1165 AND `created` > '%s' AND `id` = `parent`",
1170 if (DBM::is_result($r)) {
1171 $posts_week = $r[0]["posts_week"];
1176 if ($posts_week > $throttle_week) {
1177 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1178 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1179 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1183 $throttle_month = Config::get('system', 'throttle_limit_month');
1184 if ($throttle_month > 0) {
1185 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1188 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1189 AND `created` > '%s' AND `id` = `parent`",
1194 if (DBM::is_result($r)) {
1195 $posts_month = $r[0]["posts_month"];
1200 if ($posts_month > $throttle_month) {
1201 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1202 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1203 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1207 $_REQUEST['type'] = 'wall';
1210 if (x($_FILES, 'media')) {
1211 // upload the image if we have one
1212 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1213 $media = wall_upload_post($a);
1214 if (strlen($media) > 0) {
1215 $_REQUEST['body'] .= "\n\n" . $media;
1219 // To-Do: Multiple IDs
1220 if (requestdata('media_ids')) {
1222 "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",
1223 intval(requestdata('media_ids')),
1226 if (DBM::is_result($r)) {
1227 $phototypes = Image::supportedTypes();
1228 $ext = $phototypes[$r[0]['type']];
1229 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1230 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1234 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1236 $_REQUEST['api_source'] = true;
1238 if (!x($_REQUEST, "source")) {
1239 $_REQUEST["source"] = api_source();
1242 // call out normal post function
1245 // this should output the last post (the one we just posted).
1246 return api_status_show($type);
1249 /// @TODO move to top of file or somwhere better
1250 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1251 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1253 function api_media_upload($type)
1257 if (api_user() === false) {
1259 throw new ForbiddenException();
1262 $user_info = api_get_user($a);
1264 if (!x($_FILES, 'media')) {
1266 throw new BadRequestException("No media.");
1269 $media = wall_upload_post($a, false);
1272 throw new InternalServerErrorException();
1275 $returndata = array();
1276 $returndata["media_id"] = $media["id"];
1277 $returndata["media_id_string"] = (string)$media["id"];
1278 $returndata["size"] = $media["size"];
1279 $returndata["image"] = array("w" => $media["width"],
1280 "h" => $media["height"],
1281 "image_type" => $media["type"]);
1283 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1285 return array("media" => $returndata);
1288 /// @TODO move to top of file or somwhere better
1289 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1291 function api_status_show($type)
1295 $user_info = api_get_user($a);
1297 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1299 if ($type == "raw") {
1300 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1305 // get last public wall message
1309 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1310 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1311 AND `item`.`type` != 'activity' $privacy_sql
1312 ORDER BY `item`.`id` DESC
1314 intval($user_info['cid']),
1316 dbesc($user_info['url']),
1317 dbesc(normalise_link($user_info['url'])),
1318 dbesc($user_info['url']),
1319 dbesc(normalise_link($user_info['url']))
1322 if (DBM::is_result($lastwall)) {
1323 $lastwall = $lastwall[0];
1325 $in_reply_to = api_in_reply_to($lastwall);
1327 $converted = api_convert_item($lastwall);
1329 if ($type == "xml") {
1330 $geo = "georss:point";
1335 $status_info = array(
1336 'created_at' => api_date($lastwall['created']),
1337 'id' => intval($lastwall['id']),
1338 'id_str' => (string) $lastwall['id'],
1339 'text' => $converted["text"],
1340 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1341 'truncated' => false,
1342 'in_reply_to_status_id' => $in_reply_to['status_id'],
1343 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1344 'in_reply_to_user_id' => $in_reply_to['user_id'],
1345 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1346 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1347 'user' => $user_info,
1349 'coordinates' => "",
1351 'contributors' => "",
1352 'is_quote_status' => false,
1353 'retweet_count' => 0,
1354 'favorite_count' => 0,
1355 'favorited' => $lastwall['starred'] ? true : false,
1356 'retweeted' => false,
1357 'possibly_sensitive' => false,
1359 'statusnet_html' => $converted["html"],
1360 'statusnet_conversation_id' => $lastwall['parent'],
1361 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1364 if (count($converted["attachments"]) > 0) {
1365 $status_info["attachments"] = $converted["attachments"];
1368 if (count($converted["entities"]) > 0) {
1369 $status_info["entities"] = $converted["entities"];
1372 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1373 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1374 } elseif (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1375 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1378 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1379 unset($status_info["user"]["uid"]);
1380 unset($status_info["user"]["self"]);
1383 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1385 if ($type == "raw") {
1386 return $status_info;
1389 return api_format_data("statuses", $type, array('status' => $status_info));
1393 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1394 * The author's most recent status will be returned inline.
1395 * http://developer.twitter.com/doc/get/users/show
1397 function api_users_show($type)
1401 $user_info = api_get_user($a);
1405 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1406 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1407 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1408 AND `type`!='activity'
1409 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1413 dbesc(ACTIVITY_POST),
1414 intval($user_info['cid']),
1415 dbesc($user_info['url']),
1416 dbesc(normalise_link($user_info['url'])),
1417 dbesc($user_info['url']),
1418 dbesc(normalise_link($user_info['url']))
1421 if (DBM::is_result($lastwall)) {
1422 $lastwall = $lastwall[0];
1424 $in_reply_to = api_in_reply_to($lastwall);
1426 $converted = api_convert_item($lastwall);
1428 if ($type == "xml") {
1429 $geo = "georss:point";
1434 $user_info['status'] = array(
1435 'text' => $converted["text"],
1436 'truncated' => false,
1437 'created_at' => api_date($lastwall['created']),
1438 'in_reply_to_status_id' => $in_reply_to['status_id'],
1439 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1440 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1441 'id' => intval($lastwall['contact-id']),
1442 'id_str' => (string) $lastwall['contact-id'],
1443 'in_reply_to_user_id' => $in_reply_to['user_id'],
1444 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1445 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1447 'favorited' => $lastwall['starred'] ? true : false,
1448 'statusnet_html' => $converted["html"],
1449 'statusnet_conversation_id' => $lastwall['parent'],
1450 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1453 if (count($converted["attachments"]) > 0) {
1454 $user_info["status"]["attachments"] = $converted["attachments"];
1457 if (count($converted["entities"]) > 0) {
1458 $user_info["status"]["entities"] = $converted["entities"];
1461 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1462 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1465 if (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1466 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
1470 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1471 unset($user_info["uid"]);
1472 unset($user_info["self"]);
1474 return api_format_data("user", $type, array('user' => $user_info));
1477 /// @TODO move to top of file or somewhere better
1478 api_register_func('api/users/show', 'api_users_show');
1479 api_register_func('api/externalprofile/show', 'api_users_show');
1481 function api_users_search($type)
1485 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1487 $userlist = array();
1489 if (x($_GET, 'q')) {
1490 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1492 if (!DBM::is_result($r)) {
1493 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1496 if (DBM::is_result($r)) {
1498 foreach ($r as $user) {
1499 $user_info = api_get_user($a, $user["id"], "json");
1501 if ($type == "xml") {
1502 $userlist[$k++.":user"] = $user_info;
1504 $userlist[] = $user_info;
1507 $userlist = array("users" => $userlist);
1509 throw new BadRequestException("User not found.");
1512 throw new BadRequestException("User not found.");
1514 return api_format_data("users", $type, $userlist);
1517 /// @TODO move to top of file or somewhere better
1518 api_register_func('api/users/search', 'api_users_search');
1521 * Return user objects
1523 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1525 * @param string $type Return format: json or xml
1527 * @return array|string
1528 * @throws UnauthorizedException
1529 * @throws NotFoundException
1531 function api_users_lookup($type)
1535 if (x($_REQUEST['user_id'])) {
1536 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1538 $users[] = api_get_user(get_app(), $id);
1543 if (empty($users)) {
1544 throw new NotFoundException;
1547 return api_format_data("users", $type, array('users' => $users));
1550 /// @TODO move to top of file or somewhere better
1551 api_register_func('api/users/lookup', 'api_users_lookup', true);
1554 * Returns statuses that match a specified query.
1556 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1558 * @param string $type Return format: json, xml, atom, rss
1560 * @return array|string
1561 * @throws UnauthorizedException
1562 * @throws BadRequestException
1564 function api_search($type)
1568 if (!x($_REQUEST, 'q')) {
1569 throw new BadRequestException("q parameter is required.");
1572 if (x($_REQUEST, 'rpp')) {
1573 $count = $_REQUEST['rpp'];
1574 } elseif (x($_REQUEST, 'count')) {
1575 $count = $_REQUEST['count'];
1580 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1581 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1582 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1584 $start = $page * $count;
1587 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1591 "SELECT ".item_fieldlists()."
1592 FROM `item` ".item_joins()."
1593 WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1594 AND `item`.`body` LIKE CONCAT('%',?,'%')
1597 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
1603 $data['status'] = api_format_items(dba::inArray($r), api_get_user(get_app()));
1605 return api_format_data("statuses", $type, $data);
1608 /// @TODO move to top of file or somewhere better
1609 api_register_func('api/search/tweets', 'api_search', true);
1610 api_register_func('api/search', 'api_search', true);
1614 * http://developer.twitter.com/doc/get/statuses/home_timeline
1616 * TODO: Optional parameters
1617 * TODO: Add reply info
1619 function api_statuses_home_timeline($type)
1623 if (api_user() === false) {
1624 throw new ForbiddenException();
1627 unset($_REQUEST["user_id"]);
1628 unset($_GET["user_id"]);
1630 unset($_REQUEST["screen_name"]);
1631 unset($_GET["screen_name"]);
1633 $user_info = api_get_user($a);
1634 // get last newtork messages
1637 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1638 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1642 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1643 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1644 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1645 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1646 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1648 $start = $page * $count;
1652 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1654 if ($exclude_replies > 0) {
1655 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1657 if ($conversation_id > 0) {
1658 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1662 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1663 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1664 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1665 `contact`.`id` AS `cid`
1667 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1668 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1669 WHERE `item`.`uid` = %d AND `verb` = '%s'
1670 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1673 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1675 dbesc(ACTIVITY_POST),
1681 $ret = api_format_items($r, $user_info, false, $type);
1683 // Set all posts from the query above to seen
1685 foreach ($r as $item) {
1686 $idarray[] = intval($item["id"]);
1689 $idlist = implode(",", $idarray);
1691 if ($idlist != "") {
1692 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1695 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1699 $data = array('status' => $ret);
1703 $data = api_rss_extra($a, $data, $user_info);
1707 return api_format_data("statuses", $type, $data);
1710 /// @TODO move to top of file or somewhere better
1711 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1712 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1714 function api_statuses_public_timeline($type)
1718 if (api_user() === false) {
1719 throw new ForbiddenException();
1722 $user_info = api_get_user($a);
1723 // get last newtork messages
1726 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1727 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1731 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1732 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1733 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1734 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1735 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1737 $start = $page * $count;
1739 if ($exclude_replies && !$conversation_id) {
1741 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1744 $r = dba::p("SELECT " . item_fieldlists() . "
1746 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1747 " . item_joins() . "
1748 STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1749 AND NOT `user`.`hidewall`
1751 AND NOT `thread`.`private`
1753 AND `thread`.`visible`
1754 AND NOT `thread`.`deleted`
1755 AND NOT `thread`.`moderated`
1756 AND `thread`.`iid` > ?
1758 ORDER BY `thread`.`iid` DESC
1759 LIMIT " . intval($start) . ", " . intval($count),
1764 $r = dba::inArray($r);
1767 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1769 if ($conversation_id > 0) {
1770 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1773 $r = dba::p("SELECT " . item_fieldlists() . "
1775 " . item_joins() . "
1776 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1777 AND NOT `user`.`hidewall`
1779 AND NOT `item`.`private`
1781 AND `item`.`visible`
1782 AND NOT `item`.`deleted`
1783 AND NOT `item`.`moderated`
1786 ORDER BY `item`.`id` DESC
1787 LIMIT " . intval($start) . ", " . intval($count),
1792 $r = dba::inArray($r);
1795 $ret = api_format_items($r, $user_info, false, $type);
1797 $data = array('status' => $ret);
1801 $data = api_rss_extra($a, $data, $user_info);
1805 return api_format_data("statuses", $type, $data);
1808 /// @TODO move to top of file or somewhere better
1809 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1812 * @brief Returns the list of public federated posts this node knows about
1814 * @param string $type Return format: json, xml, atom, rss
1815 * @return array|string
1816 * @throws ForbiddenException
1818 function api_statuses_networkpublic_timeline($type)
1822 if (api_user() === false) {
1823 throw new ForbiddenException();
1826 $user_info = api_get_user($a);
1828 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1829 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1832 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1833 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1837 $start = ($page - 1) * $count;
1841 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1844 $r = dba::p("SELECT " . item_fieldlists() . "
1846 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1847 " . item_joins() . "
1848 WHERE `thread`.`uid` = 0
1850 AND NOT `thread`.`private`
1851 AND `thread`.`visible`
1852 AND NOT `thread`.`deleted`
1853 AND NOT `thread`.`moderated`
1854 AND `thread`.`iid` > ?
1856 ORDER BY `thread`.`iid` DESC
1857 LIMIT " . intval($start) . ", " . intval($count),
1862 $r = dba::inArray($r);
1864 $ret = api_format_items($r, $user_info, false, $type);
1866 $data = array('status' => $ret);
1870 $data = api_rss_extra($a, $data, $user_info);
1874 return api_format_data("statuses", $type, $data);
1877 /// @TODO move to top of file or somewhere better
1878 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1881 * @TODO nothing to say?
1883 function api_statuses_show($type)
1887 if (api_user() === false) {
1888 throw new ForbiddenException();
1891 $user_info = api_get_user($a);
1894 $id = intval($a->argv[3]);
1897 $id = intval($_REQUEST["id"]);
1902 $id = intval($a->argv[4]);
1905 logger('API: api_statuses_show: ' . $id);
1907 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1910 if ($conversation) {
1911 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1913 $sql_extra .= " AND `item`.`id` = %d";
1917 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1918 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1919 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1920 `contact`.`id` AS `cid`
1922 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1923 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1924 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1925 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1928 dbesc(ACTIVITY_POST),
1932 /// @TODO How about copying this to above methods which don't check $r ?
1933 if (!DBM::is_result($r)) {
1934 throw new BadRequestException("There is no status with this id.");
1937 $ret = api_format_items($r, $user_info, false, $type);
1939 if ($conversation) {
1940 $data = array('status' => $ret);
1941 return api_format_data("statuses", $type, $data);
1943 $data = array('status' => $ret[0]);
1944 return api_format_data("status", $type, $data);
1948 /// @TODO move to top of file or somewhere better
1949 api_register_func('api/statuses/show', 'api_statuses_show', true);
1952 * @TODO nothing to say?
1954 function api_conversation_show($type)
1958 if (api_user() === false) {
1959 throw new ForbiddenException();
1962 $user_info = api_get_user($a);
1965 $id = intval($a->argv[3]);
1966 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1967 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1971 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1972 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1974 $start = $page*$count;
1977 $id = intval($_REQUEST["id"]);
1982 $id = intval($a->argv[4]);
1985 logger('API: api_conversation_show: '.$id);
1987 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1988 if (DBM::is_result($r)) {
1989 $id = $r[0]["parent"];
1995 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1998 // Not sure why this query was so complicated. We should keep it here for a while,
1999 // just to make sure that we really don't need it.
2000 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
2001 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
2004 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2005 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2006 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2007 `contact`.`id` AS `cid`
2009 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2010 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2011 WHERE `item`.`parent` = %d AND `item`.`visible`
2012 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2013 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2014 AND `item`.`id`>%d $sql_extra
2015 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2016 intval($id), intval(api_user()),
2017 dbesc(ACTIVITY_POST),
2019 intval($start), intval($count)
2022 if (!DBM::is_result($r)) {
2023 throw new BadRequestException("There is no status with this id.");
2026 $ret = api_format_items($r, $user_info, false, $type);
2028 $data = array('status' => $ret);
2029 return api_format_data("statuses", $type, $data);
2032 /// @TODO move to top of file or somewhere better
2033 api_register_func('api/conversation/show', 'api_conversation_show', true);
2034 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2037 * @TODO nothing to say?
2039 function api_statuses_repeat($type)
2045 if (api_user() === false) {
2046 throw new ForbiddenException();
2049 $user_info = api_get_user($a);
2052 $id = intval($a->argv[3]);
2055 $id = intval($_REQUEST["id"]);
2060 $id = intval($a->argv[4]);
2063 logger('API: api_statuses_repeat: '.$id);
2066 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2067 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2068 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2069 `contact`.`id` AS `cid`
2071 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2072 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2073 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2074 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2075 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2077 AND `item`.`id`=%d",
2081 /// @TODO other style than above functions!
2082 if (DBM::is_result($r) && $r[0]['body'] != "") {
2083 if (strpos($r[0]['body'], "[/share]") !== false) {
2084 $pos = strpos($r[0]['body'], "[share");
2085 $post = substr($r[0]['body'], $pos);
2087 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2089 $post .= $r[0]['body'];
2090 $post .= "[/share]";
2092 $_REQUEST['body'] = $post;
2093 $_REQUEST['profile_uid'] = api_user();
2094 $_REQUEST['type'] = 'wall';
2095 $_REQUEST['api_source'] = true;
2097 if (!x($_REQUEST, "source")) {
2098 $_REQUEST["source"] = api_source();
2103 throw new ForbiddenException();
2106 // this should output the last post (the one we just posted).
2108 return api_status_show($type);
2111 /// @TODO move to top of file or somewhere better
2112 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2115 * @TODO nothing to say?
2117 function api_statuses_destroy($type)
2121 if (api_user() === false) {
2122 throw new ForbiddenException();
2125 $user_info = api_get_user($a);
2128 $id = intval($a->argv[3]);
2131 $id = intval($_REQUEST["id"]);
2136 $id = intval($a->argv[4]);
2139 logger('API: api_statuses_destroy: '.$id);
2141 $ret = api_statuses_show($type);
2143 drop_item($id, false);
2148 /// @TODO move to top of file or somewhere better
2149 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2152 * @TODO Nothing more than an URL to say?
2153 * http://developer.twitter.com/doc/get/statuses/mentions
2155 function api_statuses_mentions($type)
2159 if (api_user() === false) {
2160 throw new ForbiddenException();
2163 unset($_REQUEST["user_id"]);
2164 unset($_GET["user_id"]);
2166 unset($_REQUEST["screen_name"]);
2167 unset($_GET["screen_name"]);
2169 $user_info = api_get_user($a);
2170 // get last newtork messages
2174 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2175 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2179 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2180 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2181 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2183 $start = $page * $count;
2185 // Ugly code - should be changed
2186 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2187 $myurl = substr($myurl, strpos($myurl, '://') + 3);
2188 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
2189 $myurl = str_replace('www.', '', $myurl);
2190 $diasp_url = str_replace('/profile/', '/u/', $myurl);
2193 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2197 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2198 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2199 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2200 `contact`.`id` AS `cid`
2201 FROM `item` FORCE INDEX (`uid_id`)
2202 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2203 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2204 WHERE `item`.`uid` = %d AND `verb` = '%s'
2205 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2206 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2207 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2210 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2212 dbesc(ACTIVITY_POST),
2213 dbesc(protect_sprintf($myurl)),
2214 dbesc(protect_sprintf($myurl)),
2221 $ret = api_format_items($r, $user_info, false, $type);
2223 $data = array('status' => $ret);
2227 $data = api_rss_extra($a, $data, $user_info);
2231 return api_format_data("statuses", $type, $data);
2234 /// @TODO move to top of file or somewhere better
2235 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2236 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2239 * @brief Returns a user's public timeline
2241 * @param string $type Either "json" or "xml"
2242 * @return string|array
2243 * @throws ForbiddenException
2245 function api_statuses_user_timeline($type)
2249 if (api_user() === false) {
2250 throw new ForbiddenException();
2253 $user_info = api_get_user($a);
2256 "api_statuses_user_timeline: api_user: ". api_user() .
2257 "\nuser_info: ".print_r($user_info, true) .
2258 "\n_REQUEST: ".print_r($_REQUEST, true),
2262 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2263 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2264 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2265 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2268 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2269 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2273 $start = ($page - 1) * $count;
2276 if ($user_info['self'] == 1) {
2277 $sql_extra .= " AND `item`.`wall` = 1 ";
2280 if ($exclude_replies > 0) {
2281 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2284 if ($conversation_id > 0) {
2285 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2289 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2293 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2294 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2295 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2296 `contact`.`id` AS `cid`
2297 FROM `item` FORCE INDEX (`uid_contactid_id`)
2298 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2299 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2300 WHERE `item`.`uid` = %d AND `verb` = '%s'
2301 AND `item`.`contact-id` = %d
2302 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2304 AND `item`.`id` > %d
2305 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2307 dbesc(ACTIVITY_POST),
2308 intval($user_info['cid']),
2314 $ret = api_format_items($r, $user_info, true, $type);
2316 $data = array('status' => $ret);
2320 $data = api_rss_extra($a, $data, $user_info);
2324 return api_format_data("statuses", $type, $data);
2327 /// @TODO move to top of file or somwhere better
2328 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2331 * Star/unstar an item
2332 * param: id : id of the item
2334 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2336 function api_favorites_create_destroy($type)
2340 if (api_user() === false) {
2341 throw new ForbiddenException();
2344 // for versioned api.
2345 /// @TODO We need a better global soluton
2346 $action_argv_id = 2;
2347 if ($a->argv[1] == "1.1") {
2348 $action_argv_id = 3;
2351 if ($a->argc <= $action_argv_id) {
2352 throw new BadRequestException("Invalid request.");
2354 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2355 if ($a->argc == $action_argv_id + 2) {
2356 $itemid = intval($a->argv[$action_argv_id + 1]);
2358 /// @TODO use x() to check if _REQUEST contains 'id'
2359 $itemid = intval($_REQUEST['id']);
2362 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2364 if (!DBM::is_result($item) || count($item) == 0) {
2365 throw new BadRequestException("Invalid item.");
2370 $item[0]['starred'] = 1;
2373 $item[0]['starred'] = 0;
2376 throw new BadRequestException("Invalid action ".$action);
2379 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2381 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2384 throw new InternalServerErrorException("DB error");
2388 $user_info = api_get_user($a);
2389 $rets = api_format_items($item, $user_info, false, $type);
2392 $data = array('status' => $ret);
2396 $data = api_rss_extra($a, $data, $user_info);
2399 return api_format_data("status", $type, $data);
2402 /// @TODO move to top of file or somwhere better
2403 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2404 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2406 function api_favorites($type)
2412 if (api_user() === false) {
2413 throw new ForbiddenException();
2416 $called_api = array();
2418 $user_info = api_get_user($a);
2420 // in friendica starred item are private
2421 // return favorites only for self
2422 logger('api_favorites: self:' . $user_info['self']);
2424 if ($user_info['self'] == 0) {
2430 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2431 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2432 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2433 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2438 $start = $page*$count;
2441 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2445 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2446 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2447 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2448 `contact`.`id` AS `cid`
2449 FROM `item`, `contact`
2450 WHERE `item`.`uid` = %d
2451 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2452 AND `item`.`starred` = 1
2453 AND `contact`.`id` = `item`.`contact-id`
2454 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2457 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2464 $ret = api_format_items($r, $user_info, false, $type);
2467 $data = array('status' => $ret);
2471 $data = api_rss_extra($a, $data, $user_info);
2474 return api_format_data("statuses", $type, $data);
2477 /// @TODO move to top of file or somwhere better
2478 api_register_func('api/favorites', 'api_favorites', true);
2480 function api_format_messages($item, $recipient, $sender)
2482 // standard meta information
2484 'id' => $item['id'],
2485 'sender_id' => $sender['id'] ,
2487 'recipient_id' => $recipient['id'],
2488 'created_at' => api_date($item['created']),
2489 'sender_screen_name' => $sender['screen_name'],
2490 'recipient_screen_name' => $recipient['screen_name'],
2491 'sender' => $sender,
2492 'recipient' => $recipient,
2494 'friendica_seen' => $item['seen'],
2495 'friendica_parent_uri' => $item['parent-uri'],
2498 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2499 unset($ret["sender"]["uid"]);
2500 unset($ret["sender"]["self"]);
2501 unset($ret["recipient"]["uid"]);
2502 unset($ret["recipient"]["self"]);
2504 //don't send title to regular StatusNET requests to avoid confusing these apps
2505 if (x($_GET, 'getText')) {
2506 $ret['title'] = $item['title'];
2507 if ($_GET['getText'] == 'html') {
2508 $ret['text'] = bbcode($item['body'], false, false);
2509 } elseif ($_GET['getText'] == 'plain') {
2510 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2511 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2514 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2516 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2517 unset($ret['sender']);
2518 unset($ret['recipient']);
2524 function api_convert_item($item)
2526 $body = $item['body'];
2527 $attachments = api_get_attachments($body);
2529 // Workaround for ostatus messages where the title is identically to the body
2530 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2531 $statusbody = trim(html2plain($html, 0));
2533 // handle data: images
2534 $statusbody = api_format_items_embeded_images($item, $statusbody);
2536 $statustitle = trim($item['title']);
2538 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2539 $statustext = trim($statusbody);
2541 $statustext = trim($statustitle."\n\n".$statusbody);
2544 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2545 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2548 $statushtml = trim(bbcode($body, false, false));
2550 // Workaround for clients with limited HTML parser functionality
2551 $search = array("<br>", "<blockquote>", "</blockquote>",
2552 "<h1>", "</h1>", "<h2>", "</h2>",
2553 "<h3>", "</h3>", "<h4>", "</h4>",
2554 "<h5>", "</h5>", "<h6>", "</h6>");
2555 $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2556 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2557 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2558 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2559 $statushtml = str_replace($search, $replace, $statushtml);
2561 if ($item['title'] != "") {
2562 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2566 $oldtext = $statushtml;
2567 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2568 } while ($oldtext != $statushtml);
2570 if (substr($statushtml, 0, 4) == '<br>') {
2571 $statushtml = substr($statushtml, 4);
2574 if (substr($statushtml, 0, -4) == '<br>') {
2575 $statushtml = substr($statushtml, -4);
2578 // feeds without body should contain the link
2579 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2580 $statushtml .= bbcode($item['plink']);
2583 $entities = api_get_entitities($statustext, $body);
2586 "text" => $statustext,
2587 "html" => $statushtml,
2588 "attachments" => $attachments,
2589 "entities" => $entities
2593 function api_get_attachments(&$body)
2596 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2598 $URLSearchString = "^\[\]";
2599 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2605 $attachments = array();
2607 foreach ($images[1] as $image) {
2608 $imagedata = Image::getInfoFromURL($image);
2611 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2615 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2616 foreach ($images[0] as $orig) {
2617 $body = str_replace($orig, "", $body);
2621 return $attachments;
2624 function api_get_entitities(&$text, $bbcode)
2628 * Links at the first character of the post
2633 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2635 if ($include_entities != "true") {
2636 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2638 foreach ($images[1] as $image) {
2639 $replace = proxy_url($image);
2640 $text = str_replace($image, $replace, $text);
2645 $bbcode = bb_CleanPictureLinks($bbcode);
2647 // Change pure links in text to bbcode uris
2648 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2650 $entities = array();
2651 $entities["hashtags"] = array();
2652 $entities["symbols"] = array();
2653 $entities["urls"] = array();
2654 $entities["user_mentions"] = array();
2656 $URLSearchString = "^\[\]";
2658 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2660 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2661 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2662 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2664 $bbcode = preg_replace(
2665 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2666 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2669 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2671 $bbcode = preg_replace(
2672 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2673 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2676 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2678 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2680 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2681 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2683 $ordered_urls = array();
2684 foreach ($urls[1] as $id => $url) {
2685 //$start = strpos($text, $url, $offset);
2686 $start = iconv_strpos($text, $url, 0, "UTF-8");
2687 if (!($start === false)) {
2688 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2692 ksort($ordered_urls);
2695 //foreach ($urls[1] AS $id=>$url) {
2696 foreach ($ordered_urls as $url) {
2697 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2698 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2700 $display_url = $url["title"];
2702 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2703 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2705 if (strlen($display_url) > 26)
2706 $display_url = substr($display_url, 0, 25)."…";
2709 //$start = strpos($text, $url, $offset);
2710 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2711 if (!($start === false)) {
2712 $entities["urls"][] = array("url" => $url["url"],
2713 "expanded_url" => $url["url"],
2714 "display_url" => $display_url,
2715 "indices" => array($start, $start+strlen($url["url"])));
2716 $offset = $start + 1;
2720 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2721 $ordered_images = array();
2722 foreach ($images[1] as $image) {
2723 //$start = strpos($text, $url, $offset);
2724 $start = iconv_strpos($text, $image, 0, "UTF-8");
2725 if (!($start === false))
2726 $ordered_images[$start] = $image;
2728 //$entities["media"] = array();
2731 foreach ($ordered_images as $url) {
2732 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2733 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2735 if (strlen($display_url) > 26)
2736 $display_url = substr($display_url, 0, 25)."…";
2738 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2739 if (!($start === false)) {
2740 $image = Image::getInfoFromURL($url);
2742 // If image cache is activated, then use the following sizes:
2743 // thumb (150), small (340), medium (600) and large (1024)
2744 if (!Config::get("system", "proxy_disabled")) {
2745 $media_url = proxy_url($url);
2748 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2749 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2751 if (($image[0] > 150) || ($image[1] > 150)) {
2752 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2753 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2756 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2757 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2759 if (($image[0] > 600) || ($image[1] > 600)) {
2760 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2761 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2765 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2768 $entities["media"][] = array(
2770 "id_str" => (string)$start+1,
2771 "indices" => array($start, $start+strlen($url)),
2772 "media_url" => normalise_link($media_url),
2773 "media_url_https" => $media_url,
2775 "display_url" => $display_url,
2776 "expanded_url" => $url,
2780 $offset = $start + 1;
2786 function api_format_items_embeded_images(&$item, $text)
2788 $text = preg_replace_callback(
2789 "|data:image/([^;]+)[^=]+=*|m",
2790 function ($match) use ($item) {
2791 return System::baseUrl()."/display/".$item['guid'];
2800 * @brief return <a href='url'>name</a> as array
2802 * @param string $txt text
2807 function api_contactlink_to_array($txt)
2810 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2811 if ($r && count($match)==3) {
2813 'name' => $match[2],
2827 * @brief return likes, dislikes and attend status for item
2829 * @param array $item array
2831 * likes => int count
2832 * dislikes => int count
2834 function api_format_items_activities(&$item, $type = "json")
2838 $activities = array(
2840 'dislike' => array(),
2841 'attendyes' => array(),
2842 'attendno' => array(),
2843 'attendmaybe' => array(),
2848 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2849 intval($item['uid']),
2853 foreach ($items as $i) {
2854 // not used as result should be structured like other user data
2855 //builtin_activity_puller($i, $activities);
2857 // get user data and add it to the array of the activity
2858 $user = api_get_user($a, $i['author-link']);
2859 switch ($i['verb']) {
2861 $activities['like'][] = $user;
2863 case ACTIVITY_DISLIKE:
2864 $activities['dislike'][] = $user;
2866 case ACTIVITY_ATTEND:
2867 $activities['attendyes'][] = $user;
2869 case ACTIVITY_ATTENDNO:
2870 $activities['attendno'][] = $user;
2872 case ACTIVITY_ATTENDMAYBE:
2873 $activities['attendmaybe'][] = $user;
2880 if ($type == "xml") {
2881 $xml_activities = array();
2882 foreach ($activities as $k => $v) {
2883 // change xml element from "like" to "friendica:like"
2884 $xml_activities["friendica:".$k] = $v;
2885 // add user data into xml output
2887 foreach ($v as $user)
2888 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2890 $activities = $xml_activities;
2898 * @brief return data from profiles
2900 * @param array $profile array containing data from db table 'profile'
2901 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2904 function api_format_items_profiles(&$profile = null, $type = "json")
2906 if ($profile != null) {
2907 $profile = array('profile_id' => $profile['id'],
2908 'profile_name' => $profile['profile-name'],
2909 'is_default' => $profile['is-default'] ? true : false,
2910 'hide_friends'=> $profile['hide-friends'] ? true : false,
2911 'profile_photo' => $profile['photo'],
2912 'profile_thumb' => $profile['thumb'],
2913 'publish' => $profile['publish'] ? true : false,
2914 'net_publish' => $profile['net-publish'] ? true : false,
2915 'description' => $profile['pdesc'],
2916 'date_of_birth' => $profile['dob'],
2917 'address' => $profile['address'],
2918 'city' => $profile['locality'],
2919 'region' => $profile['region'],
2920 'postal_code' => $profile['postal-code'],
2921 'country' => $profile['country-name'],
2922 'hometown' => $profile['hometown'],
2923 'gender' => $profile['gender'],
2924 'marital' => $profile['marital'],
2925 'marital_with' => $profile['with'],
2926 'marital_since' => $profile['howlong'],
2927 'sexual' => $profile['sexual'],
2928 'politic' => $profile['politic'],
2929 'religion' => $profile['religion'],
2930 'public_keywords' => $profile['pub_keywords'],
2931 'private_keywords' => $profile['prv_keywords'],
2932 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2933 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2934 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2935 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2936 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2937 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2938 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2939 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2940 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2941 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2942 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2943 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2944 'homepage' => $profile['homepage'],
2951 * @brief format items to be returned by api
2953 * @param array $r array of items
2954 * @param array $user_info
2955 * @param bool $filter_user filter items by $user_info
2957 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2963 foreach ($r as $item) {
2964 localize_item($item);
2965 list($status_user, $owner_user) = api_item_get_user($a, $item);
2967 // Look if the posts are matching if they should be filtered by user id
2968 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2972 $in_reply_to = api_in_reply_to($item);
2974 $converted = api_convert_item($item);
2976 if ($type == "xml") {
2977 $geo = "georss:point";
2983 'text' => $converted["text"],
2984 'truncated' => false,
2985 'created_at'=> api_date($item['created']),
2986 'in_reply_to_status_id' => $in_reply_to['status_id'],
2987 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2988 'source' => (($item['app']) ? $item['app'] : 'web'),
2989 'id' => intval($item['id']),
2990 'id_str' => (string) intval($item['id']),
2991 'in_reply_to_user_id' => $in_reply_to['user_id'],
2992 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2993 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2995 'favorited' => $item['starred'] ? true : false,
2996 'user' => $status_user ,
2997 'friendica_owner' => $owner_user,
2998 //'entities' => NULL,
2999 'statusnet_html' => $converted["html"],
3000 'statusnet_conversation_id' => $item['parent'],
3001 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3002 'friendica_activities' => api_format_items_activities($item, $type),
3005 if (count($converted["attachments"]) > 0) {
3006 $status["attachments"] = $converted["attachments"];
3009 if (count($converted["entities"]) > 0) {
3010 $status["entities"] = $converted["entities"];
3013 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
3014 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
3015 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
3016 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
3020 // Retweets are only valid for top postings
3021 // It doesn't work reliable with the link if its a feed
3022 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
3024 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
3027 if ($item["id"] == $item["parent"]) {
3028 $retweeted_item = api_share_as_retweet($item);
3029 if ($retweeted_item !== false) {
3030 $retweeted_status = $status;
3032 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
3033 } catch (BadRequestException $e) {
3034 // user not found. should be found?
3035 /// @todo check if the user should be always found
3036 $retweeted_status["user"] = array();
3039 $rt_converted = api_convert_item($retweeted_item);
3041 $retweeted_status['text'] = $rt_converted["text"];
3042 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3043 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3044 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3045 $status['retweeted_status'] = $retweeted_status;
3049 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3050 unset($status["user"]["uid"]);
3051 unset($status["user"]["self"]);
3053 if ($item["coord"] != "") {
3054 $coords = explode(' ', $item["coord"]);
3055 if (count($coords) == 2) {
3056 if ($type == "json")
3057 $status["geo"] = array('type' => 'Point',
3058 'coordinates' => array((float) $coords[0],
3059 (float) $coords[1]));
3060 else // Not sure if this is the official format - if someone founds a documentation we can check
3061 $status["georss:point"] = $item["coord"];
3069 function api_account_rate_limit_status($type)
3071 if ($type == "xml") {
3073 'remaining-hits' => '150',
3074 '@attributes' => array("type" => "integer"),
3075 'hourly-limit' => '150',
3076 '@attributes2' => array("type" => "integer"),
3077 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
3078 '@attributes3' => array("type" => "datetime"),
3079 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3080 '@attributes4' => array("type" => "integer"),
3084 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3085 'remaining_hits' => '150',
3086 'hourly_limit' => '150',
3087 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
3091 return api_format_data('hash', $type, array('hash' => $hash));
3094 /// @TODO move to top of file or somwhere better
3095 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3097 function api_help_test($type)
3099 if ($type == 'xml') {
3105 return api_format_data('ok', $type, array("ok" => $ok));
3108 /// @TODO move to top of file or somwhere better
3109 api_register_func('api/help/test', 'api_help_test', false);
3111 function api_lists($type)
3114 /// @TODO $ret is not filled here?
3115 return api_format_data('lists', $type, array("lists_list" => $ret));
3118 /// @TODO move to top of file or somwhere better
3119 api_register_func('api/lists', 'api_lists', true);
3121 function api_lists_list($type)
3124 /// @TODO $ret is not filled here?
3125 return api_format_data('lists', $type, array("lists_list" => $ret));
3128 /// @TODO move to top of file or somwhere better
3129 api_register_func('api/lists/list', 'api_lists_list', true);
3132 * @brief Returns either the friends of the follower list
3134 * Note: Considers friends and followers lists to be private and won't return
3135 * anything if any user_id parameter is passed.
3137 * @param string $qtype Either "friends" or "followers"
3138 * @return boolean|array
3139 * @throws ForbiddenException
3141 function api_statuses_f($qtype)
3145 if (api_user() === false) {
3146 throw new ForbiddenException();
3150 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3151 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3155 $start = ($page - 1) * $count;
3157 $user_info = api_get_user($a);
3159 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3160 /* this is to stop Hotot to load friends multiple times
3161 * I'm not sure if I'm missing return something or
3162 * is a bug in hotot. Workaround, meantime
3166 return array('$users' => $ret);*/
3170 if ($qtype == 'friends') {
3171 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3173 if ($qtype == 'followers') {
3174 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3177 // friends and followers only for self
3178 if ($user_info['self'] == 0) {
3179 $sql_extra = " AND false ";
3182 if ($qtype == 'blocks') {
3183 $sql_filter = 'AND `blocked` AND NOT `pending`';
3184 } elseif ($qtype == 'incoming') {
3185 $sql_filter = 'AND `pending`';
3187 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3205 foreach ($r as $cid) {
3206 $user = api_get_user($a, $cid['nurl']);
3207 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3208 unset($user["uid"]);
3209 unset($user["self"]);
3216 return array('user' => $ret);
3221 * @brief Returns the list of friends of the provided user
3223 * @deprecated By Twitter API in favor of friends/list
3225 * @param string $type Either "json" or "xml"
3226 * @return boolean|string|array
3228 function api_statuses_friends($type)
3230 $data = api_statuses_f("friends");
3231 if ($data === false) {
3234 return api_format_data("users", $type, $data);
3238 * @brief Returns the list of friends of the provided user
3240 * @deprecated By Twitter API in favor of friends/list
3242 * @param string $type Either "json" or "xml"
3243 * @return boolean|string|array
3245 function api_statuses_followers($type)
3247 $data = api_statuses_f("followers");
3248 if ($data === false) {
3251 return api_format_data("users", $type, $data);
3254 /// @TODO move to top of file or somewhere better
3255 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3256 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3259 * Returns the list of blocked users
3261 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3263 * @param string $type Either "json" or "xml"
3265 * @return boolean|string|array
3266 * @throws UnauthorizedException
3268 function api_blocks_list($type)
3270 $data = api_statuses_f('blocks');
3271 if ($data === false) {
3274 return api_format_data("users", $type, $data);
3277 /// @TODO move to top of file or somewhere better
3278 api_register_func('api/blocks/list', 'api_blocks_list', true);
3281 * Returns the list of pending users IDs
3283 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3285 * @param string $type Either "json" or "xml"
3287 * @return boolean|string|array
3288 * @throws UnauthorizedException
3290 function api_friendships_incoming($type)
3292 $data = api_statuses_f('incoming');
3293 if ($data === false) {
3298 foreach ($data['user'] as $user) {
3299 $ids[] = $user['id'];
3302 return api_format_data("ids", $type, array('id' => $ids));
3305 /// @TODO move to top of file or somewhere better
3306 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3308 function api_statusnet_config($type)
3312 $name = $a->config['sitename'];
3313 $server = $a->get_hostname();
3314 $logo = System::baseUrl() . '/images/friendica-64.png';
3315 $email = $a->config['admin_email'];
3316 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3317 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3318 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3319 if ($a->config['api_import_size']) {
3320 $texlimit = string($a->config['api_import_size']);
3322 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3323 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3326 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3327 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3328 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3329 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3330 'shorturllength' => '30',
3331 'friendica' => array(
3332 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3333 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3334 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3335 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3340 return api_format_data('config', $type, array('config' => $config));
3343 /// @TODO move to top of file or somewhere better
3344 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3345 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3347 function api_statusnet_version($type)
3350 $fake_statusnet_version = "0.9.7";
3352 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
3355 /// @TODO move to top of file or somewhere better
3356 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3357 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3360 * @todo use api_format_data() to return data
3362 function api_ff_ids($type,$qtype)
3367 throw new ForbiddenException();
3370 $user_info = api_get_user($a);
3372 if ($qtype == 'friends') {
3373 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3375 if ($qtype == 'followers') {
3376 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3379 if (!$user_info["self"]) {
3380 $sql_extra = " AND false ";
3383 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3386 "SELECT `pcontact`.`id` FROM `contact`
3387 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3388 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3392 if (!DBM::is_result($r)) {
3397 foreach ($r as $rr) {
3398 if ($stringify_ids) {
3401 $ids[] = intval($rr['id']);
3405 return api_format_data("ids", $type, array('id' => $ids));
3408 function api_friends_ids($type)
3410 return api_ff_ids($type, 'friends');
3413 function api_followers_ids($type)
3415 return api_ff_ids($type, 'followers');
3418 /// @TODO move to top of file or somewhere better
3419 api_register_func('api/friends/ids', 'api_friends_ids', true);
3420 api_register_func('api/followers/ids', 'api_followers_ids', true);
3422 function api_direct_messages_new($type)
3427 if (api_user() === false) throw new ForbiddenException();
3429 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) return;
3431 $sender = api_get_user($a);
3433 if ($_POST['screen_name']) {
3435 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3437 dbesc($_POST['screen_name'])
3440 // Selecting the id by priority, friendica first
3441 api_best_nickname($r);
3443 $recipient = api_get_user($a, $r[0]['nurl']);
3445 $recipient = api_get_user($a, $_POST['user_id']);
3450 if (x($_REQUEST, 'replyto')) {
3452 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3454 intval($_REQUEST['replyto'])
3456 $replyto = $r[0]['parent-uri'];
3457 $sub = $r[0]['title'];
3459 if (x($_REQUEST, 'title')) {
3460 $sub = $_REQUEST['title'];
3462 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3466 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3469 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3470 $ret = api_format_messages($r[0], $recipient, $sender);
3472 $ret = array("error"=>$id);
3475 $data = array('direct_message'=>$ret);
3480 $data = api_rss_extra($a, $data, $user_info);
3483 return api_format_data("direct-messages", $type, $data);
3487 /// @TODO move to top of file or somewhere better
3488 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3491 * @brief delete a direct_message from mail table through api
3493 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3496 function api_direct_messages_destroy($type)
3500 if (api_user() === false) {
3501 throw new ForbiddenException();
3505 $user_info = api_get_user($a);
3507 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3509 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3510 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3511 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3513 $uid = $user_info['uid'];
3514 // error if no id or parenturi specified (for clients posting parent-uri as well)
3515 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3516 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3517 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3520 // BadRequestException if no id specified (for clients using Twitter API)
3522 throw new BadRequestException('Message id not specified');
3525 // add parent-uri to sql command if specified by calling app
3526 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3528 // get data of the specified message id
3530 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3535 // error message if specified id is not in database
3536 if (!DBM::is_result($r)) {
3537 if ($verbose == "true") {
3538 $answer = array('result' => 'error', 'message' => 'message id not in database');
3539 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3541 /// @todo BadRequestException ok for Twitter API clients?
3542 throw new BadRequestException('message id not in database');
3547 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3552 if ($verbose == "true") {
3555 $answer = array('result' => 'ok', 'message' => 'message deleted');
3556 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3558 $answer = array('result' => 'error', 'message' => 'unknown error');
3559 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3562 /// @todo return JSON data like Twitter API not yet implemented
3566 /// @TODO move to top of file or somewhere better
3567 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3569 function api_direct_messages_box($type, $box, $verbose)
3573 if (api_user() === false) {
3574 throw new ForbiddenException();
3578 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3579 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3584 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3585 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3587 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3588 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3591 unset($_REQUEST["user_id"]);
3592 unset($_GET["user_id"]);
3594 unset($_REQUEST["screen_name"]);
3595 unset($_GET["screen_name"]);
3597 $user_info = api_get_user($a);
3598 $profile_url = $user_info["url"];
3601 $start = $page * $count;
3604 if ($box=="sentbox") {
3605 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3606 } elseif ($box == "conversation") {
3607 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3608 } elseif ($box == "all") {
3609 $sql_extra = "true";
3610 } elseif ($box == "inbox") {
3611 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3615 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3618 if ($user_id != "") {
3619 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3620 } elseif ($screen_name !="") {
3621 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3625 "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",
3631 if ($verbose == "true" && !DBM::is_result($r)) {
3632 $answer = array('result' => 'error', 'message' => 'no mails available');
3633 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3637 foreach ($r as $item) {
3638 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3639 $recipient = $user_info;
3640 $sender = api_get_user($a, normalise_link($item['contact-url']));
3641 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3642 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3643 $sender = $user_info;
3646 $ret[] = api_format_messages($item, $recipient, $sender);
3650 $data = array('direct_message' => $ret);
3654 $data = api_rss_extra($a, $data, $user_info);
3657 return api_format_data("direct-messages", $type, $data);
3660 function api_direct_messages_sentbox($type)
3662 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3663 return api_direct_messages_box($type, "sentbox", $verbose);
3666 function api_direct_messages_inbox($type)
3668 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3669 return api_direct_messages_box($type, "inbox", $verbose);
3672 function api_direct_messages_all($type)
3674 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3675 return api_direct_messages_box($type, "all", $verbose);
3678 function api_direct_messages_conversation($type)
3680 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3681 return api_direct_messages_box($type, "conversation", $verbose);
3684 /// @TODO move to top of file or somewhere better
3685 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3686 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3687 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3688 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3690 function api_oauth_request_token($type)
3692 $oauth1 = new FKOAuth1();
3694 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3695 } catch (Exception $e) {
3696 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3703 function api_oauth_access_token($type)
3705 $oauth1 = new FKOAuth1();
3707 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3708 } catch (Exception $e) {
3709 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3716 /// @TODO move to top of file or somewhere better
3717 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3718 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3722 * @brief delete a complete photoalbum with all containing photos from database through api
3724 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3727 function api_fr_photoalbum_delete($type)
3729 if (api_user() === false) {
3730 throw new ForbiddenException();
3733 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3735 // we do not allow calls without album string
3737 throw new BadRequestException("no albumname specified");
3739 // check if album is existing
3741 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3745 if (!DBM::is_result($r))
3746 throw new BadRequestException("album not available");
3748 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3749 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3750 foreach ($r as $rr) {
3752 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3753 intval(local_user()),
3754 dbesc($rr['resource-id'])
3757 if (!DBM::is_result($photo_item)) {
3758 throw new InternalServerErrorException("problem with deleting items occured");
3760 drop_item($photo_item[0]['id'], false);
3763 // now let's delete all photos from the album
3764 $result = dba::delete('photo', array('uid' => api_user(), 'album' => $album));
3766 // return success of deletion or error message
3768 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3769 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3771 throw new InternalServerErrorException("unknown error - deleting from database failed");
3776 * @brief update the name of the album for all photos of an album
3778 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3781 function api_fr_photoalbum_update($type)
3783 if (api_user() === false) {
3784 throw new ForbiddenException();
3787 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3788 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3790 // we do not allow calls without album string
3792 throw new BadRequestException("no albumname specified");
3794 if ($album_new == "") {
3795 throw new BadRequestException("no new albumname specified");
3797 // check if album is existing
3799 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3803 if (!DBM::is_result($r)) {
3804 throw new BadRequestException("album not available");
3806 // now let's update all photos to the albumname
3808 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3814 // return success of updating or error message
3816 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3817 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3819 throw new InternalServerErrorException("unknown error - updating in database failed");
3825 * @brief list all photos of the authenticated user
3827 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3830 function api_fr_photos_list($type)
3832 if (api_user() === false) {
3833 throw new ForbiddenException();
3836 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3837 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3838 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3839 intval(local_user())
3842 'image/jpeg' => 'jpg',
3843 'image/png' => 'png',
3844 'image/gif' => 'gif'
3846 $data = array('photo'=>array());
3847 if (DBM::is_result($r)) {
3848 foreach ($r as $rr) {
3850 $photo['id'] = $rr['resource-id'];
3851 $photo['album'] = $rr['album'];
3852 $photo['filename'] = $rr['filename'];
3853 $photo['type'] = $rr['type'];
3854 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3855 $photo['created'] = $rr['created'];
3856 $photo['edited'] = $rr['edited'];
3857 $photo['desc'] = $rr['desc'];
3859 if ($type == "xml") {
3860 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3862 $photo['thumb'] = $thumb;
3863 $data['photo'][] = $photo;
3867 return api_format_data("photos", $type, $data);
3871 * @brief upload a new photo or change an existing photo
3873 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3876 function api_fr_photo_create_update($type)
3878 if (api_user() === false) {
3879 throw new ForbiddenException();
3882 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3883 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3884 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3885 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3886 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3887 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3888 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3889 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3890 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3892 // do several checks on input parameters
3893 // we do not allow calls without album string
3894 if ($album == null) {
3895 throw new BadRequestException("no albumname specified");
3897 // if photo_id == null --> we are uploading a new photo
3898 if ($photo_id == null) {
3901 // error if no media posted in create-mode
3902 if (!x($_FILES, 'media')) {
3904 throw new BadRequestException("no media data submitted");
3907 // album_new will be ignored in create-mode
3912 // check if photo is existing in database
3914 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3919 if (!DBM::is_result($r)) {
3920 throw new BadRequestException("photo not available");
3924 // checks on acl strings provided by clients
3925 $acl_input_error = false;
3926 $acl_input_error |= check_acl_input($allow_cid);
3927 $acl_input_error |= check_acl_input($deny_cid);
3928 $acl_input_error |= check_acl_input($allow_gid);
3929 $acl_input_error |= check_acl_input($deny_gid);
3930 if ($acl_input_error) {
3931 throw new BadRequestException("acl data invalid");
3933 // now let's upload the new media in create-mode
3934 if ($mode == "create") {
3935 $media = $_FILES['media'];
3936 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3938 // return success of updating or error message
3939 if (!is_null($data)) {
3940 return api_format_data("photo_create", $type, $data);
3942 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3946 // now let's do the changes in update-mode
3947 if ($mode == "update") {
3950 if (!is_null($desc)) {
3951 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3954 if (!is_null($album_new)) {
3955 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3958 if (!is_null($allow_cid)) {
3959 $allow_cid = trim($allow_cid);
3960 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3963 if (!is_null($deny_cid)) {
3964 $deny_cid = trim($deny_cid);
3965 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3968 if (!is_null($allow_gid)) {
3969 $allow_gid = trim($allow_gid);
3970 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3973 if (!is_null($deny_gid)) {
3974 $deny_gid = trim($deny_gid);
3975 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3979 if ($sql_extra != "") {
3980 $nothingtodo = false;
3982 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3984 datetime_convert(), // update edited timestamp
3990 $nothingtodo = true;
3993 if (x($_FILES, 'media')) {
3994 $nothingtodo = false;
3995 $media = $_FILES['media'];
3996 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3997 if (!is_null($data)) {
3998 return api_format_data("photo_update", $type, $data);
4002 // return success of updating or error message
4004 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
4005 return api_format_data("photo_update", $type, array('$result' => $answer));
4008 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
4009 return api_format_data("photo_update", $type, array('$result' => $answer));
4011 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4014 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4019 * @brief delete a single photo from the database through api
4021 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4024 function api_fr_photo_delete($type)
4026 if (api_user() === false) {
4027 throw new ForbiddenException();
4030 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4032 // do several checks on input parameters
4033 // we do not allow calls without photo id
4034 if ($photo_id == null) {
4035 throw new BadRequestException("no photo_id specified");
4037 // check if photo is existing in database
4039 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4043 if (!DBM::is_result($r)) {
4044 throw new BadRequestException("photo not available");
4046 // now we can perform on the deletion of the photo
4047 $result = dba::delete('photo', array('uid' => api_user(), 'resource-id' => $photo_id));
4049 // return success of deletion or error message
4051 // retrieve the id of the parent element (the photo element)
4053 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4054 intval(local_user()),
4058 if (!DBM::is_result($photo_item)) {
4059 throw new InternalServerErrorException("problem with deleting items occured");
4061 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4062 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4063 drop_item($photo_item[0]['id'], false);
4065 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
4066 return api_format_data("photo_delete", $type, array('$result' => $answer));
4068 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4074 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4076 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4079 function api_fr_photo_detail($type)
4081 if (api_user() === false) {
4082 throw new ForbiddenException();
4084 if (!x($_REQUEST, 'photo_id')) {
4085 throw new BadRequestException("No photo id.");
4088 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4089 $photo_id = $_REQUEST['photo_id'];
4091 // prepare json/xml output with data from database for the requested photo
4092 $data = prepare_photo_data($type, $scale, $photo_id);
4094 return api_format_data("photo_detail", $type, $data);
4099 * @brief updates the profile image for the user (either a specified profile or the default profile)
4101 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4104 function api_account_update_profile_image($type)
4106 if (api_user() === false) {
4107 throw new ForbiddenException();
4110 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
4112 // error if image data is missing
4113 if (!x($_FILES, 'image')) {
4114 throw new BadRequestException("no media data submitted");
4117 // check if specified profile id is valid
4118 if ($profileid != 0) {
4120 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4124 // error message if specified profile id is not in database
4125 if (!DBM::is_result($r)) {
4126 throw new BadRequestException("profile_id not available");
4128 $is_default_profile = $r['profile'];
4130 $is_default_profile = 1;
4133 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4135 if (x($_FILES, 'image')) {
4136 $media = $_FILES['image'];
4137 } elseif (x($_FILES, 'media')) {
4138 $media = $_FILES['media'];
4140 // save new profile image
4141 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4144 if (is_array($media['type'])) {
4145 $filetype = $media['type'][0];
4147 $filetype = $media['type'];
4149 if ($filetype == "image/jpeg") {
4151 } elseif ($filetype == "image/png") {
4154 // change specified profile or all profiles to the new resource-id
4155 if ($is_default_profile) {
4157 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4158 dbesc($data['photo']['id']),
4159 intval(local_user())
4163 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
4164 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4165 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4166 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4167 intval(local_user())
4171 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4172 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4173 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4174 intval($_REQUEST['profile']),
4175 intval(local_user())
4179 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4180 // so that browsers will do a cache update unconditionally
4183 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4184 dbesc(datetime_convert()),
4185 intval(local_user())
4188 // Update global directory in background
4189 //$user = api_get_user(get_app());
4190 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4191 if ($url && strlen(Config::get('system', 'directory'))) {
4192 Worker::add(PRIORITY_LOW, "Directory", $url);
4195 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4197 // output for client
4199 return api_account_verify_credentials($type);
4201 // SaveMediaToDatabase failed for some reason
4202 throw new InternalServerErrorException("image upload failed");
4206 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4207 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4208 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4209 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4210 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4211 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4212 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4213 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4214 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4217 function check_acl_input($acl_string)
4219 if ($acl_string == null || $acl_string == " ") {
4222 $contact_not_found = false;
4224 // split <x><y><z> into array of cid's
4225 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4227 // check for each cid if it is available on server
4228 $cid_array = $array[0];
4229 foreach ($cid_array as $cid) {
4230 $cid = str_replace("<", "", $cid);
4231 $cid = str_replace(">", "", $cid);
4233 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4237 $contact_not_found |= !DBM::is_result($contact);
4239 return $contact_not_found;
4242 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)
4250 if (is_array($media)) {
4251 if (is_array($media['tmp_name'])) {
4252 $src = $media['tmp_name'][0];
4254 $src = $media['tmp_name'];
4256 if (is_array($media['name'])) {
4257 $filename = basename($media['name'][0]);
4259 $filename = basename($media['name']);
4261 if (is_array($media['size'])) {
4262 $filesize = intval($media['size'][0]);
4264 $filesize = intval($media['size']);
4266 if (is_array($media['type'])) {
4267 $filetype = $media['type'][0];
4269 $filetype = $media['type'];
4273 if ($filetype == "") {
4274 $filetype=Image::guessType($filename);
4276 $imagedata = getimagesize($src);
4278 $filetype = $imagedata['mime'];
4281 "File upload src: " . $src . " - filename: " . $filename .
4282 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG
4285 // check if there was a php upload error
4286 if ($filesize == 0 && $media['error'] == 1) {
4287 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4289 // check against max upload size within Friendica instance
4290 $maximagesize = Config::get('system', 'maximagesize');
4291 if (($maximagesize) && ($filesize > $maximagesize)) {
4292 $formattedBytes = formatBytes($maximagesize);
4293 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4296 // create Photo instance with the data of the image
4297 $imagedata = @file_get_contents($src);
4298 $Image = new Image($imagedata, $filetype);
4299 if (! $Image->isValid()) {
4300 throw new InternalServerErrorException("unable to process image data");
4303 // check orientation of image
4304 $Image->orient($src);
4307 // check max length of images on server
4308 $max_length = Config::get('system', 'max_image_length');
4309 if (! $max_length) {
4310 $max_length = MAX_IMAGE_LENGTH;
4312 if ($max_length > 0) {
4313 $Image->scaleDown($max_length);
4314 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4316 $width = $Image->getWidth();
4317 $height = $Image->getHeight();
4319 // create a new resource-id if not already provided
4320 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
4322 if ($mediatype == "photo") {
4323 // upload normal image (scales 0, 1, 2)
4324 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4326 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4328 logger("photo upload: image upload with scale 0 (original size) failed");
4330 if ($width > 640 || $height > 640) {
4331 $Image->scaleDown(640);
4332 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4334 logger("photo upload: image upload with scale 1 (640x640) failed");
4338 if ($width > 320 || $height > 320) {
4339 $Image->scaleDown(320);
4340 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4342 logger("photo upload: image upload with scale 2 (320x320) failed");
4345 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4346 } elseif ($mediatype == "profileimage") {
4347 // upload profile image (scales 4, 5, 6)
4348 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4350 if ($width > 175 || $height > 175) {
4351 $Image->scaleDown(175);
4352 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4354 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4358 if ($width > 80 || $height > 80) {
4359 $Image->scaleDown(80);
4360 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4362 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4366 if ($width > 48 || $height > 48) {
4367 $Image->scaleDown(48);
4368 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4370 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4373 $Image->__destruct();
4374 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4378 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4379 if ($photo_id == null && $mediatype == "photo") {
4380 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4382 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4383 return prepare_photo_data($type, false, $hash);
4385 throw new InternalServerErrorException("image upload failed");
4389 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4391 // get data about the api authenticated user
4392 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4393 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4396 $arr['guid'] = get_guid(32);
4397 $arr['uid'] = intval(api_user());
4399 $arr['parent-uri'] = $uri;
4400 $arr['type'] = 'photo';
4402 $arr['resource-id'] = $hash;
4403 $arr['contact-id'] = $owner_record[0]['id'];
4404 $arr['owner-name'] = $owner_record[0]['name'];
4405 $arr['owner-link'] = $owner_record[0]['url'];
4406 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4407 $arr['author-name'] = $owner_record[0]['name'];
4408 $arr['author-link'] = $owner_record[0]['url'];
4409 $arr['author-avatar'] = $owner_record[0]['thumb'];
4411 $arr['allow_cid'] = $allow_cid;
4412 $arr['allow_gid'] = $allow_gid;
4413 $arr['deny_cid'] = $deny_cid;
4414 $arr['deny_gid'] = $deny_gid;
4415 $arr['last-child'] = 1;
4416 $arr['visible'] = $visibility;
4420 'image/jpeg' => 'jpg',
4421 'image/png' => 'png',
4422 'image/gif' => 'gif'
4425 // adds link to the thumbnail scale photo
4426 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4427 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4430 // do the magic for storing the item in the database and trigger the federation to other contacts
4434 function prepare_photo_data($type, $scale, $photo_id)
4436 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4437 $data_sql = ($scale === false ? "" : "data, ");
4439 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4440 // clients needs to convert this in their way for further processing
4442 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4443 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4444 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4445 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4447 intval(local_user()),
4453 'image/jpeg' => 'jpg',
4454 'image/png' => 'png',
4455 'image/gif' => 'gif'
4458 // prepare output data for photo
4459 if (DBM::is_result($r)) {
4460 $data = array('photo' => $r[0]);
4461 $data['photo']['id'] = $data['photo']['resource-id'];
4462 if ($scale !== false) {
4463 $data['photo']['data'] = base64_encode($data['photo']['data']);
4465 unset($data['photo']['datasize']); //needed only with scale param
4467 if ($type == "xml") {
4468 $data['photo']['links'] = array();
4469 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4470 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4472 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4475 $data['photo']['link'] = array();
4476 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4478 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4479 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4483 unset($data['photo']['resource-id']);
4484 unset($data['photo']['minscale']);
4485 unset($data['photo']['maxscale']);
4487 throw new NotFoundException();
4490 // retrieve item element for getting activities (like, dislike etc.) related to photo
4492 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4493 intval(local_user()),
4496 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4498 // retrieve comments on photo
4500 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4501 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4502 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4503 `contact`.`id` AS `cid`
4505 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4506 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4507 WHERE `item`.`parent` = %d AND `item`.`visible`
4508 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4509 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4510 intval($item[0]['parent']),
4512 dbesc(ACTIVITY_POST)
4515 // prepare output of comments
4516 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4517 $comments = array();
4518 if ($type == "xml") {
4520 foreach ($commentData as $comment) {
4521 $comments[$k++ . ":comment"] = $comment;
4524 foreach ($commentData as $comment) {
4525 $comments[] = $comment;
4528 $data['photo']['friendica_comments'] = $comments;
4530 // include info if rights on photo and rights on item are mismatching
4531 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4532 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4533 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4534 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4535 $data['photo']['rights_mismatch'] = $rights_mismatch;
4542 * Similar as /mod/redir.php
4543 * redirect to 'url' after dfrn auth
4545 * Why this when there is mod/redir.php already?
4546 * This use api_user() and api_login()
4549 * c_url: url of remote contact to auth to
4550 * url: string, url to redirect after auth
4552 function api_friendica_remoteauth()
4554 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4555 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4557 if ($url === '' || $c_url === '') {
4558 throw new BadRequestException("Wrong parameters.");
4561 $c_url = normalise_link($c_url);
4566 "SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4571 if ((! DBM::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4572 throw new BadRequestException("Unknown contact");
4577 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4579 if ($r[0]['duplex'] && $r[0]['issued-id']) {
4580 $orig_id = $r[0]['issued-id'];
4581 $dfrn_id = '1:' . $orig_id;
4583 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4584 $orig_id = $r[0]['dfrn-id'];
4585 $dfrn_id = '0:' . $orig_id;
4588 $sec = random_string();
4591 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4592 VALUES( %d, %s, '%s', '%s', %d )",
4600 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4601 $dest = (($url) ? '&destination_url=' . $url : '');
4603 $r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4604 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4605 . '&type=profile&sec=' . $sec . $dest . $quiet
4608 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4611 * @brief Return the item shared, if the item contains only the [share] tag
4613 * @param array $item Sharer item
4614 * @return array Shared item or false if not a reshare
4616 function api_share_as_retweet(&$item)
4618 $body = trim($item["body"]);
4620 if (Diaspora::isReshare($body, false)===false) {
4624 /// @TODO "$1" should maybe mean '$1' ?
4625 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4627 * Skip if there is no shared message in there
4628 * we already checked this in diaspora::isReshare()
4629 * but better one more than one less...
4631 if ($body == $attributes) {
4636 // build the fake reshared item
4637 $reshared_item = $item;
4640 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4641 if ($matches[1] != "") {
4642 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4645 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4646 if ($matches[1] != "") {
4647 $author = $matches[1];
4651 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4652 if ($matches[1] != "") {
4653 $profile = $matches[1];
4656 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4657 if ($matches[1] != "") {
4658 $profile = $matches[1];
4662 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4663 if ($matches[1] != "") {
4664 $avatar = $matches[1];
4667 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4668 if ($matches[1] != "") {
4669 $avatar = $matches[1];
4673 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4674 if ($matches[1] != "") {
4675 $link = $matches[1];
4678 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4679 if ($matches[1] != "") {
4680 $link = $matches[1];
4684 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4685 if ($matches[1] != "")
4686 $posted = $matches[1];
4688 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4689 if ($matches[1] != "") {
4690 $posted = $matches[1];
4693 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4695 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4699 $reshared_item["body"] = $shared_body;
4700 $reshared_item["author-name"] = $author;
4701 $reshared_item["author-link"] = $profile;
4702 $reshared_item["author-avatar"] = $avatar;
4703 $reshared_item["plink"] = $link;
4704 $reshared_item["created"] = $posted;
4705 $reshared_item["edited"] = $posted;
4707 return $reshared_item;
4711 function api_get_nick($profile)
4714 - remove trailing junk from profile url
4715 - pump.io check has to check the website
4721 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4722 dbesc(normalise_link($profile))
4725 if (DBM::is_result($r)) {
4726 $nick = $r[0]["nick"];
4731 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4732 dbesc(normalise_link($profile))
4735 if (DBM::is_result($r)) {
4736 $nick = $r[0]["nick"];
4741 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4742 if ($friendica != $profile) {
4748 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4749 if ($diaspora != $profile) {
4755 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4756 if ($twitter != $profile) {
4763 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4764 if ($StatusnetHost != $profile) {
4765 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4766 if ($StatusnetUser != $profile) {
4767 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4768 $user = json_decode($UserData);
4770 $nick = $user->screen_name;
4776 // To-Do: look at the page if its really a pumpio site
4777 //if (!$nick == "") {
4778 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4779 // if ($pumpio != $profile)
4781 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4792 function api_in_reply_to($item)
4794 $in_reply_to = array();
4796 $in_reply_to['status_id'] = null;
4797 $in_reply_to['user_id'] = null;
4798 $in_reply_to['status_id_str'] = null;
4799 $in_reply_to['user_id_str'] = null;
4800 $in_reply_to['screen_name'] = null;
4802 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4803 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4804 intval($item['uid']),
4805 dbesc($item['thr-parent']));
4807 if (DBM::is_result($r)) {
4808 $in_reply_to['status_id'] = intval($r[0]['id']);
4810 $in_reply_to['status_id'] = intval($item['parent']);
4813 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4815 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4816 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4817 WHERE `item`.`id` = %d LIMIT 1",
4818 intval($in_reply_to['status_id'])
4821 if (DBM::is_result($r)) {
4822 if ($r[0]['nick'] == "") {
4823 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4826 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4827 $in_reply_to['user_id'] = intval($r[0]['id']);
4828 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4831 // There seems to be situation, where both fields are identical:
4832 // https://github.com/friendica/friendica/issues/1010
4833 // This is a bugfix for that.
4834 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4835 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4836 $in_reply_to['status_id'] = null;
4837 $in_reply_to['user_id'] = null;
4838 $in_reply_to['status_id_str'] = null;
4839 $in_reply_to['user_id_str'] = null;
4840 $in_reply_to['screen_name'] = null;
4844 return $in_reply_to;
4847 function api_clean_plain_items($Text)
4849 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4851 $Text = bb_CleanPictureLinks($Text);
4852 $URLSearchString = "^\[\]";
4854 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
4856 if ($include_entities == "true") {
4857 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
4860 // Simplify "attachment" element
4861 $Text = api_clean_attachments($Text);
4867 * @brief Removes most sharing information for API text export
4869 * @param string $body The original body
4871 * @return string Cleaned body
4873 function api_clean_attachments($body)
4875 $data = get_attachment_data($body);
4882 if (isset($data["text"]))
4883 $body = $data["text"];
4885 if (($body == "") && (isset($data["title"])))
4886 $body = $data["title"];
4888 if (isset($data["url"]))
4889 $body .= "\n".$data["url"];
4891 $body .= $data["after"];
4896 function api_best_nickname(&$contacts)
4898 $best_contact = array();
4900 if (count($contact) == 0)
4903 foreach ($contacts as $contact)
4904 if ($contact["network"] == "") {
4905 $contact["network"] = "dfrn";
4906 $best_contact = array($contact);
4909 if (sizeof($best_contact) == 0)
4910 foreach ($contacts as $contact)
4911 if ($contact["network"] == "dfrn")
4912 $best_contact = array($contact);
4914 if (sizeof($best_contact) == 0)
4915 foreach ($contacts as $contact)
4916 if ($contact["network"] == "dspr")
4917 $best_contact = array($contact);
4919 if (sizeof($best_contact) == 0)
4920 foreach ($contacts as $contact)
4921 if ($contact["network"] == "stat")
4922 $best_contact = array($contact);
4924 if (sizeof($best_contact) == 0)
4925 foreach ($contacts as $contact)
4926 if ($contact["network"] == "pump")
4927 $best_contact = array($contact);
4929 if (sizeof($best_contact) == 0)
4930 foreach ($contacts as $contact)
4931 if ($contact["network"] == "twit")
4932 $best_contact = array($contact);
4934 if (sizeof($best_contact) == 1) {
4935 $contacts = $best_contact;
4937 $contacts = array($contacts[0]);
4941 // return all or a specified group of the user with the containing contacts
4942 function api_friendica_group_show($type)
4946 if (api_user() === false) throw new ForbiddenException();
4949 $user_info = api_get_user($a);
4950 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4951 $uid = $user_info['uid'];
4953 // get data of the specified group id or all groups if not specified
4956 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4960 // error message if specified gid is not in database
4961 if (!DBM::is_result($r))
4962 throw new BadRequestException("gid not available");
4965 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4970 // loop through all groups and retrieve all members for adding data in the user array
4971 foreach ($r as $rr) {
4972 $members = Contact::getByGroupId($rr['id']);
4975 if ($type == "xml") {
4976 $user_element = "users";
4978 foreach ($members as $member) {
4979 $user = api_get_user($a, $member['nurl']);
4980 $users[$k++.":user"] = $user;
4983 $user_element = "user";
4984 foreach ($members as $member) {
4985 $user = api_get_user($a, $member['nurl']);
4989 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4991 return api_format_data("groups", $type, array('group' => $grps));
4993 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4996 // delete the specified group of the user
4997 function api_friendica_group_delete($type)
5001 if (api_user() === false) {
5002 throw new ForbiddenException();
5006 $user_info = api_get_user($a);
5007 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5008 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5009 $uid = $user_info['uid'];
5011 // error if no gid specified
5012 if ($gid == 0 || $name == "") {
5013 throw new BadRequestException('gid or name not specified');
5016 // get data of the specified group id
5018 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5022 // error message if specified gid is not in database
5023 if (!DBM::is_result($r)) {
5024 throw new BadRequestException('gid not available');
5027 // get data of the specified group id and group name
5029 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5034 // error message if specified gid is not in database
5035 if (!DBM::is_result($rname)) {
5036 throw new BadRequestException('wrong group name');
5040 $ret = Group::removeByName($uid, $name);
5043 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
5044 return api_format_data("group_delete", $type, array('result' => $success));
5046 throw new BadRequestException('other API error');
5049 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5052 // create the specified group with the posted array of contacts
5053 function api_friendica_group_create($type)
5057 if (api_user() === false) throw new ForbiddenException();
5060 $user_info = api_get_user($a);
5061 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5062 $uid = $user_info['uid'];
5063 $json = json_decode($_POST['json'], true);
5064 $users = $json['user'];
5066 // error if no name specified
5068 throw new BadRequestException('group name not specified');
5070 // get data of the specified group name
5072 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5076 // error message if specified group name already exists
5077 if (DBM::is_result($rname))
5078 throw new BadRequestException('group name already exists');
5080 // check if specified group name is a deleted group
5082 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5086 // error message if specified group name already exists
5087 if (DBM::is_result($rname))
5088 $reactivate_group = true;
5091 $ret = Group::create($uid, $name);
5093 $gid = Group::getIdByName($uid, $name);
5095 throw new BadRequestException('other API error');
5099 $erroraddinguser = false;
5100 $errorusers = array();
5101 foreach ($users as $user) {
5102 $cid = $user['cid'];
5103 // check if user really exists as contact
5105 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5109 if (count($contact))
5110 $result = Group::addMember($gid, $cid);
5112 $erroraddinguser = true;
5113 $errorusers[] = $cid;
5117 // return success message incl. missing users in array
5118 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
5119 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
5120 return api_format_data("group_create", $type, array('result' => $success));
5122 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5125 // update the specified group with the posted array of contacts
5126 function api_friendica_group_update($type)
5130 if (api_user() === false) throw new ForbiddenException();
5133 $user_info = api_get_user($a);
5134 $uid = $user_info['uid'];
5135 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5136 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5137 $json = json_decode($_POST['json'], true);
5138 $users = $json['user'];
5140 // error if no name specified
5142 throw new BadRequestException('group name not specified');
5144 // error if no gid specified
5146 throw new BadRequestException('gid not specified');
5149 $members = Contact::getByGroupId($gid);
5150 foreach ($members as $member) {
5151 $cid = $member['id'];
5152 foreach ($users as $user) {
5153 $found = ($user['cid'] == $cid ? true : false);
5156 $ret = Group::removeMemberByName($uid, $name, $cid);
5161 $erroraddinguser = false;
5162 $errorusers = array();
5163 foreach ($users as $user) {
5164 $cid = $user['cid'];
5165 // check if user really exists as contact
5167 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5172 if (count($contact)) {
5173 $result = Group::addMember($gid, $cid);
5175 $erroraddinguser = true;
5176 $errorusers[] = $cid;
5180 // return success message incl. missing users in array
5181 $status = ($erroraddinguser ? "missing user" : "ok");
5182 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
5183 return api_format_data("group_update", $type, array('result' => $success));
5186 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5188 function api_friendica_activity($type)
5192 if (api_user() === false) throw new ForbiddenException();
5193 $verb = strtolower($a->argv[3]);
5194 $verb = preg_replace("|\..*$|", "", $verb);
5196 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5198 $res = do_like($id, $verb);
5201 if ($type == "xml") {
5206 return api_format_data('ok', $type, array('ok' => $ok));
5208 throw new BadRequestException('Error adding activity');
5212 /// @TODO move to top of file or somwhere better
5213 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5214 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5215 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5216 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5217 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5218 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5219 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5220 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5221 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5222 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5225 * @brief Returns notifications
5227 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5230 function api_friendica_notification($type)
5234 if (api_user() === false) throw new ForbiddenException();
5235 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
5236 $nm = new NotificationsManager();
5238 $notes = $nm->getAll(array(), "+seen -date", 50);
5240 if ($type == "xml") {
5241 $xmlnotes = array();
5242 foreach ($notes as $note)
5243 $xmlnotes[] = array("@attributes" => $note);
5248 return api_format_data("notes", $type, array('note' => $notes));
5252 * @brief Set notification as seen and returns associated item (if possible)
5254 * POST request with 'id' param as notification id
5256 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5259 function api_friendica_notification_seen($type)
5263 if (api_user() === false) throw new ForbiddenException();
5264 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
5266 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5268 $nm = new NotificationsManager();
5269 $note = $nm->getByID($id);
5270 if (is_null($note)) throw new BadRequestException("Invalid argument");
5272 $nm->setSeen($note);
5273 if ($note['otype']=='item') {
5274 // would be really better with an ItemsManager and $im->getByID() :-P
5276 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5277 intval($note['iid']),
5278 intval(local_user())
5281 // we found the item, return it to the user
5282 $user_info = api_get_user($a);
5283 $ret = api_format_items($r, $user_info, false, $type);
5284 $data = array('status' => $ret);
5285 return api_format_data("status", $type, $data);
5287 // the item can't be found, but we set the note as seen, so we count this as a success
5289 return api_format_data('result', $type, array('result' => "success"));
5292 /// @TODO move to top of file or somwhere better
5293 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5294 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5297 * @brief update a direct_message to seen state
5299 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5300 * @return string (success result=ok, error result=error with error message)
5302 function api_friendica_direct_messages_setseen($type)
5305 if (api_user() === false) {
5306 throw new ForbiddenException();
5310 $user_info = api_get_user($a);
5311 $uid = $user_info['uid'];
5312 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5314 // return error if id is zero
5316 $answer = array('result' => 'error', 'message' => 'message id not specified');
5317 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5320 // get data of the specified message id
5322 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5327 // error message if specified id is not in database
5328 if (!DBM::is_result($r)) {
5329 $answer = array('result' => 'error', 'message' => 'message id not in database');
5330 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5333 // update seen indicator
5335 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5342 $answer = array('result' => 'ok', 'message' => 'message set to seen');
5343 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
5345 $answer = array('result' => 'error', 'message' => 'unknown error');
5346 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5350 /// @TODO move to top of file or somwhere better
5351 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5354 * @brief search for direct_messages containing a searchstring through api
5356 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5357 * @return string (success: success=true if found and search_result contains found messages
5358 * success=false if nothing was found, search_result='nothing found',
5359 * error: result=error with error message)
5361 function api_friendica_direct_messages_search($type)
5365 if (api_user() === false) {
5366 throw new ForbiddenException();
5370 $user_info = api_get_user($a);
5371 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5372 $uid = $user_info['uid'];
5374 // error if no searchstring specified
5375 if ($searchstring == "") {
5376 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
5377 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
5380 // get data for the specified searchstring
5382 "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",
5384 dbesc('%'.$searchstring.'%')
5387 $profile_url = $user_info["url"];
5389 // message if nothing was found
5390 if (!DBM::is_result($r)) {
5391 $success = array('success' => false, 'search_results' => 'problem with query');
5392 } elseif (count($r) == 0) {
5393 $success = array('success' => false, 'search_results' => 'nothing found');
5396 foreach ($r as $item) {
5397 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5398 $recipient = $user_info;
5399 $sender = api_get_user($a, normalise_link($item['contact-url']));
5400 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5401 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5402 $sender = $user_info;
5405 $ret[] = api_format_messages($item, $recipient, $sender);
5407 $success = array('success' => true, 'search_results' => $ret);
5410 return api_format_data("direct_message_search", $type, array('$result' => $success));
5413 /// @TODO move to top of file or somwhere better
5414 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5417 * @brief return data of all the profiles a user has to the client
5419 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5422 function api_friendica_profile_show($type)
5426 if (api_user() === false) {
5427 throw new ForbiddenException();
5431 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5433 // retrieve general information about profiles for user
5434 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5435 $directory = Config::get('system', 'directory');
5437 // get data of the specified profile id or all profiles of the user if not specified
5438 if ($profileid != 0) {
5440 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5445 // error message if specified gid is not in database
5446 if (!DBM::is_result($r)) {
5447 throw new BadRequestException("profile_id not available");
5451 "SELECT * FROM `profile` WHERE `uid` = %d",
5455 // loop through all returned profiles and retrieve data and users
5457 foreach ($r as $rr) {
5458 $profile = api_format_items_profiles($rr, $type);
5460 // select all users from contact table, loop and prepare standard return for user data
5463 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5465 intval($rr['profile_id'])
5468 foreach ($r as $rr) {
5469 $user = api_get_user($a, $rr['nurl']);
5470 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5472 $profile['users'] = $users;
5474 // add prepared profile data to array for final return
5475 if ($type == "xml") {
5476 $profiles[$k++ . ":profile"] = $profile;
5478 $profiles[] = $profile;
5482 // return settings, authenticated user and profiles data
5483 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5485 $result = array('multi_profiles' => $multi_profiles ? true : false,
5486 'global_dir' => $directory,
5487 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5488 'profiles' => $profiles);
5489 return api_format_data("friendica_profiles", $type, array('$result' => $result));
5491 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5494 @TODO Maybe open to implement?
5496 [pagename] => api/1.1/statuses/lookup.json
5497 [id] => 605138389168451584
5498 [include_cards] => true
5499 [cards_platform] => Android-12
5500 [include_entities] => true
5501 [include_my_retweet] => 1
5503 [include_reply_count] => true
5504 [include_descendent_reply_count] => true
5508 Not implemented by now:
5509 statuses/retweets_of_me
5514 account/update_location
5515 account/update_profile_background_image
5518 friendica/profile/update
5519 friendica/profile/create
5520 friendica/profile/delete
5522 Not implemented in status.net:
5523 statuses/retweeted_to_me
5524 statuses/retweeted_by_me
5525 direct_messages/destroy
5527 account/update_delivery_device
5528 notifications/follow