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 * Returns statuses that match a specified query.
1523 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1525 * @param string $type Return format: json, xml, atom, rss
1527 * @return array|string
1528 * @throws UnauthorizedException
1529 * @throws BadRequestException
1531 function api_search($type)
1535 if (!x($_REQUEST, 'q')) {
1536 throw new BadRequestException("q parameter is required.");
1539 if (x($_REQUEST, 'rpp')) {
1540 $count = $_REQUEST['rpp'];
1541 } elseif (x($_REQUEST, 'count')) {
1542 $count = $_REQUEST['count'];
1547 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1548 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1549 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1551 $start = $page * $count;
1554 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1558 "SELECT ".item_fieldlists()."
1559 FROM `item` ".item_joins()."
1560 WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1561 AND `item`.`body` LIKE CONCAT('%',?,'%')
1564 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
1570 $data['status'] = api_format_items(dba::inArray($r), api_get_user(get_app()));
1572 return api_format_data("statuses", $type, $data);
1575 /// @TODO move to top of file or somewhere better
1576 api_register_func('api/search/tweets', 'api_search', true);
1577 api_register_func('api/search', 'api_search', true);
1581 * http://developer.twitter.com/doc/get/statuses/home_timeline
1583 * TODO: Optional parameters
1584 * TODO: Add reply info
1586 function api_statuses_home_timeline($type)
1590 if (api_user() === false) {
1591 throw new ForbiddenException();
1594 unset($_REQUEST["user_id"]);
1595 unset($_GET["user_id"]);
1597 unset($_REQUEST["screen_name"]);
1598 unset($_GET["screen_name"]);
1600 $user_info = api_get_user($a);
1601 // get last newtork messages
1604 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1605 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1609 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1610 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1611 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1612 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1613 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1615 $start = $page * $count;
1619 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1621 if ($exclude_replies > 0) {
1622 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1624 if ($conversation_id > 0) {
1625 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1629 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1630 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1631 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1632 `contact`.`id` AS `cid`
1634 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1635 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1636 WHERE `item`.`uid` = %d AND `verb` = '%s'
1637 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1640 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1642 dbesc(ACTIVITY_POST),
1648 $ret = api_format_items($r, $user_info, false, $type);
1650 // Set all posts from the query above to seen
1652 foreach ($r as $item) {
1653 $idarray[] = intval($item["id"]);
1656 $idlist = implode(",", $idarray);
1658 if ($idlist != "") {
1659 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1662 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1666 $data = array('status' => $ret);
1670 $data = api_rss_extra($a, $data, $user_info);
1674 return api_format_data("statuses", $type, $data);
1677 /// @TODO move to top of file or somewhere better
1678 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1679 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1681 function api_statuses_public_timeline($type)
1685 if (api_user() === false) {
1686 throw new ForbiddenException();
1689 $user_info = api_get_user($a);
1690 // get last newtork messages
1693 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1694 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1698 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1699 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1700 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1701 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1702 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1704 $start = $page * $count;
1706 if ($exclude_replies && !$conversation_id) {
1708 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1711 $r = dba::p("SELECT " . item_fieldlists() . "
1713 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1714 " . item_joins() . "
1715 STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1716 AND NOT `user`.`hidewall`
1718 AND NOT `thread`.`private`
1720 AND `thread`.`visible`
1721 AND NOT `thread`.`deleted`
1722 AND NOT `thread`.`moderated`
1723 AND `thread`.`iid` > ?
1725 ORDER BY `thread`.`iid` DESC
1726 LIMIT " . intval($start) . ", " . intval($count),
1731 $r = dba::inArray($r);
1734 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1736 if ($conversation_id > 0) {
1737 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1740 $r = dba::p("SELECT " . item_fieldlists() . "
1742 " . item_joins() . "
1743 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1744 AND NOT `user`.`hidewall`
1746 AND NOT `item`.`private`
1748 AND `item`.`visible`
1749 AND NOT `item`.`deleted`
1750 AND NOT `item`.`moderated`
1753 ORDER BY `item`.`id` DESC
1754 LIMIT " . intval($start) . ", " . intval($count),
1759 $r = dba::inArray($r);
1762 $ret = api_format_items($r, $user_info, false, $type);
1764 $data = array('status' => $ret);
1768 $data = api_rss_extra($a, $data, $user_info);
1772 return api_format_data("statuses", $type, $data);
1775 /// @TODO move to top of file or somewhere better
1776 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1779 * @brief Returns the list of public federated posts this node knows about
1781 * @param string $type Return format: json, xml, atom, rss
1782 * @return array|string
1783 * @throws ForbiddenException
1785 function api_statuses_networkpublic_timeline($type)
1789 if (api_user() === false) {
1790 throw new ForbiddenException();
1793 $user_info = api_get_user($a);
1795 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1796 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1799 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1800 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1804 $start = ($page - 1) * $count;
1808 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1811 $r = dba::p("SELECT " . item_fieldlists() . "
1813 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1814 " . item_joins() . "
1815 WHERE `thread`.`uid` = 0
1817 AND NOT `thread`.`private`
1818 AND `thread`.`visible`
1819 AND NOT `thread`.`deleted`
1820 AND NOT `thread`.`moderated`
1821 AND `thread`.`iid` > ?
1823 ORDER BY `thread`.`iid` DESC
1824 LIMIT " . intval($start) . ", " . intval($count),
1829 $r = dba::inArray($r);
1831 $ret = api_format_items($r, $user_info, false, $type);
1833 $data = array('status' => $ret);
1837 $data = api_rss_extra($a, $data, $user_info);
1841 return api_format_data("statuses", $type, $data);
1844 /// @TODO move to top of file or somewhere better
1845 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1848 * @TODO nothing to say?
1850 function api_statuses_show($type)
1854 if (api_user() === false) {
1855 throw new ForbiddenException();
1858 $user_info = api_get_user($a);
1861 $id = intval($a->argv[3]);
1864 $id = intval($_REQUEST["id"]);
1869 $id = intval($a->argv[4]);
1872 logger('API: api_statuses_show: ' . $id);
1874 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1877 if ($conversation) {
1878 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1880 $sql_extra .= " AND `item`.`id` = %d";
1884 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1885 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1886 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1887 `contact`.`id` AS `cid`
1889 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1890 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1891 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1892 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1895 dbesc(ACTIVITY_POST),
1899 /// @TODO How about copying this to above methods which don't check $r ?
1900 if (!DBM::is_result($r)) {
1901 throw new BadRequestException("There is no status with this id.");
1904 $ret = api_format_items($r, $user_info, false, $type);
1906 if ($conversation) {
1907 $data = array('status' => $ret);
1908 return api_format_data("statuses", $type, $data);
1910 $data = array('status' => $ret[0]);
1911 return api_format_data("status", $type, $data);
1915 /// @TODO move to top of file or somewhere better
1916 api_register_func('api/statuses/show', 'api_statuses_show', true);
1919 * @TODO nothing to say?
1921 function api_conversation_show($type)
1925 if (api_user() === false) {
1926 throw new ForbiddenException();
1929 $user_info = api_get_user($a);
1932 $id = intval($a->argv[3]);
1933 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1934 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1938 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1939 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1941 $start = $page*$count;
1944 $id = intval($_REQUEST["id"]);
1949 $id = intval($a->argv[4]);
1952 logger('API: api_conversation_show: '.$id);
1954 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1955 if (DBM::is_result($r)) {
1956 $id = $r[0]["parent"];
1962 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1965 // Not sure why this query was so complicated. We should keep it here for a while,
1966 // just to make sure that we really don't need it.
1967 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1968 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1971 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1972 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1973 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1974 `contact`.`id` AS `cid`
1976 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1977 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1978 WHERE `item`.`parent` = %d AND `item`.`visible`
1979 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1980 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1981 AND `item`.`id`>%d $sql_extra
1982 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1983 intval($id), intval(api_user()),
1984 dbesc(ACTIVITY_POST),
1986 intval($start), intval($count)
1989 if (!DBM::is_result($r)) {
1990 throw new BadRequestException("There is no status with this id.");
1993 $ret = api_format_items($r, $user_info, false, $type);
1995 $data = array('status' => $ret);
1996 return api_format_data("statuses", $type, $data);
1999 /// @TODO move to top of file or somewhere better
2000 api_register_func('api/conversation/show', 'api_conversation_show', true);
2001 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2004 * @TODO nothing to say?
2006 function api_statuses_repeat($type)
2012 if (api_user() === false) {
2013 throw new ForbiddenException();
2016 $user_info = api_get_user($a);
2019 $id = intval($a->argv[3]);
2022 $id = intval($_REQUEST["id"]);
2027 $id = intval($a->argv[4]);
2030 logger('API: api_statuses_repeat: '.$id);
2033 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2034 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2035 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2036 `contact`.`id` AS `cid`
2038 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2039 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2040 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2041 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2042 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2044 AND `item`.`id`=%d",
2048 /// @TODO other style than above functions!
2049 if (DBM::is_result($r) && $r[0]['body'] != "") {
2050 if (strpos($r[0]['body'], "[/share]") !== false) {
2051 $pos = strpos($r[0]['body'], "[share");
2052 $post = substr($r[0]['body'], $pos);
2054 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2056 $post .= $r[0]['body'];
2057 $post .= "[/share]";
2059 $_REQUEST['body'] = $post;
2060 $_REQUEST['profile_uid'] = api_user();
2061 $_REQUEST['type'] = 'wall';
2062 $_REQUEST['api_source'] = true;
2064 if (!x($_REQUEST, "source")) {
2065 $_REQUEST["source"] = api_source();
2070 throw new ForbiddenException();
2073 // this should output the last post (the one we just posted).
2075 return api_status_show($type);
2078 /// @TODO move to top of file or somewhere better
2079 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2082 * @TODO nothing to say?
2084 function api_statuses_destroy($type)
2088 if (api_user() === false) {
2089 throw new ForbiddenException();
2092 $user_info = api_get_user($a);
2095 $id = intval($a->argv[3]);
2098 $id = intval($_REQUEST["id"]);
2103 $id = intval($a->argv[4]);
2106 logger('API: api_statuses_destroy: '.$id);
2108 $ret = api_statuses_show($type);
2110 drop_item($id, false);
2115 /// @TODO move to top of file or somewhere better
2116 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2119 * @TODO Nothing more than an URL to say?
2120 * http://developer.twitter.com/doc/get/statuses/mentions
2122 function api_statuses_mentions($type)
2126 if (api_user() === false) {
2127 throw new ForbiddenException();
2130 unset($_REQUEST["user_id"]);
2131 unset($_GET["user_id"]);
2133 unset($_REQUEST["screen_name"]);
2134 unset($_GET["screen_name"]);
2136 $user_info = api_get_user($a);
2137 // get last newtork messages
2141 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2142 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2146 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2147 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2148 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2150 $start = $page * $count;
2152 // Ugly code - should be changed
2153 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2154 $myurl = substr($myurl, strpos($myurl, '://') + 3);
2155 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
2156 $myurl = str_replace('www.', '', $myurl);
2157 $diasp_url = str_replace('/profile/', '/u/', $myurl);
2160 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2164 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2165 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2166 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2167 `contact`.`id` AS `cid`
2168 FROM `item` FORCE INDEX (`uid_id`)
2169 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2170 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2171 WHERE `item`.`uid` = %d AND `verb` = '%s'
2172 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2173 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2174 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2177 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2179 dbesc(ACTIVITY_POST),
2180 dbesc(protect_sprintf($myurl)),
2181 dbesc(protect_sprintf($myurl)),
2188 $ret = api_format_items($r, $user_info, false, $type);
2190 $data = array('status' => $ret);
2194 $data = api_rss_extra($a, $data, $user_info);
2198 return api_format_data("statuses", $type, $data);
2201 /// @TODO move to top of file or somewhere better
2202 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2203 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2206 * @brief Returns a user's public timeline
2208 * @param string $type Either "json" or "xml"
2209 * @return string|array
2210 * @throws ForbiddenException
2212 function api_statuses_user_timeline($type)
2216 if (api_user() === false) {
2217 throw new ForbiddenException();
2220 $user_info = api_get_user($a);
2223 "api_statuses_user_timeline: api_user: ". api_user() .
2224 "\nuser_info: ".print_r($user_info, true) .
2225 "\n_REQUEST: ".print_r($_REQUEST, true),
2229 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2230 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2231 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2232 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2235 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2236 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2240 $start = ($page - 1) * $count;
2243 if ($user_info['self'] == 1) {
2244 $sql_extra .= " AND `item`.`wall` = 1 ";
2247 if ($exclude_replies > 0) {
2248 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2251 if ($conversation_id > 0) {
2252 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2256 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2260 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2261 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2262 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2263 `contact`.`id` AS `cid`
2264 FROM `item` FORCE INDEX (`uid_contactid_id`)
2265 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2266 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2267 WHERE `item`.`uid` = %d AND `verb` = '%s'
2268 AND `item`.`contact-id` = %d
2269 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2271 AND `item`.`id` > %d
2272 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2274 dbesc(ACTIVITY_POST),
2275 intval($user_info['cid']),
2281 $ret = api_format_items($r, $user_info, true, $type);
2283 $data = array('status' => $ret);
2287 $data = api_rss_extra($a, $data, $user_info);
2291 return api_format_data("statuses", $type, $data);
2294 /// @TODO move to top of file or somwhere better
2295 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2298 * Star/unstar an item
2299 * param: id : id of the item
2301 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2303 function api_favorites_create_destroy($type)
2307 if (api_user() === false) {
2308 throw new ForbiddenException();
2311 // for versioned api.
2312 /// @TODO We need a better global soluton
2313 $action_argv_id = 2;
2314 if ($a->argv[1] == "1.1") {
2315 $action_argv_id = 3;
2318 if ($a->argc <= $action_argv_id) {
2319 throw new BadRequestException("Invalid request.");
2321 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2322 if ($a->argc == $action_argv_id + 2) {
2323 $itemid = intval($a->argv[$action_argv_id + 1]);
2325 /// @TODO use x() to check if _REQUEST contains 'id'
2326 $itemid = intval($_REQUEST['id']);
2329 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2331 if (!DBM::is_result($item) || count($item) == 0) {
2332 throw new BadRequestException("Invalid item.");
2337 $item[0]['starred'] = 1;
2340 $item[0]['starred'] = 0;
2343 throw new BadRequestException("Invalid action ".$action);
2346 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2348 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2351 throw new InternalServerErrorException("DB error");
2355 $user_info = api_get_user($a);
2356 $rets = api_format_items($item, $user_info, false, $type);
2359 $data = array('status' => $ret);
2363 $data = api_rss_extra($a, $data, $user_info);
2366 return api_format_data("status", $type, $data);
2369 /// @TODO move to top of file or somwhere better
2370 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2371 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2373 function api_favorites($type)
2379 if (api_user() === false) {
2380 throw new ForbiddenException();
2383 $called_api = array();
2385 $user_info = api_get_user($a);
2387 // in friendica starred item are private
2388 // return favorites only for self
2389 logger('api_favorites: self:' . $user_info['self']);
2391 if ($user_info['self'] == 0) {
2397 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2398 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2399 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2400 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2405 $start = $page*$count;
2408 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2412 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2413 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2414 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2415 `contact`.`id` AS `cid`
2416 FROM `item`, `contact`
2417 WHERE `item`.`uid` = %d
2418 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2419 AND `item`.`starred` = 1
2420 AND `contact`.`id` = `item`.`contact-id`
2421 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2424 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2431 $ret = api_format_items($r, $user_info, false, $type);
2434 $data = array('status' => $ret);
2438 $data = api_rss_extra($a, $data, $user_info);
2441 return api_format_data("statuses", $type, $data);
2444 /// @TODO move to top of file or somwhere better
2445 api_register_func('api/favorites', 'api_favorites', true);
2447 function api_format_messages($item, $recipient, $sender)
2449 // standard meta information
2451 'id' => $item['id'],
2452 'sender_id' => $sender['id'] ,
2454 'recipient_id' => $recipient['id'],
2455 'created_at' => api_date($item['created']),
2456 'sender_screen_name' => $sender['screen_name'],
2457 'recipient_screen_name' => $recipient['screen_name'],
2458 'sender' => $sender,
2459 'recipient' => $recipient,
2461 'friendica_seen' => $item['seen'],
2462 'friendica_parent_uri' => $item['parent-uri'],
2465 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2466 unset($ret["sender"]["uid"]);
2467 unset($ret["sender"]["self"]);
2468 unset($ret["recipient"]["uid"]);
2469 unset($ret["recipient"]["self"]);
2471 //don't send title to regular StatusNET requests to avoid confusing these apps
2472 if (x($_GET, 'getText')) {
2473 $ret['title'] = $item['title'];
2474 if ($_GET['getText'] == 'html') {
2475 $ret['text'] = bbcode($item['body'], false, false);
2476 } elseif ($_GET['getText'] == 'plain') {
2477 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2478 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2481 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2483 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2484 unset($ret['sender']);
2485 unset($ret['recipient']);
2491 function api_convert_item($item)
2493 $body = $item['body'];
2494 $attachments = api_get_attachments($body);
2496 // Workaround for ostatus messages where the title is identically to the body
2497 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2498 $statusbody = trim(html2plain($html, 0));
2500 // handle data: images
2501 $statusbody = api_format_items_embeded_images($item, $statusbody);
2503 $statustitle = trim($item['title']);
2505 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2506 $statustext = trim($statusbody);
2508 $statustext = trim($statustitle."\n\n".$statusbody);
2511 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2512 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2515 $statushtml = trim(bbcode($body, false, false));
2517 // Workaround for clients with limited HTML parser functionality
2518 $search = array("<br>", "<blockquote>", "</blockquote>",
2519 "<h1>", "</h1>", "<h2>", "</h2>",
2520 "<h3>", "</h3>", "<h4>", "</h4>",
2521 "<h5>", "</h5>", "<h6>", "</h6>");
2522 $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2523 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2524 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2525 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2526 $statushtml = str_replace($search, $replace, $statushtml);
2528 if ($item['title'] != "") {
2529 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2533 $oldtext = $statushtml;
2534 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2535 } while ($oldtext != $statushtml);
2537 if (substr($statushtml, 0, 4) == '<br>') {
2538 $statushtml = substr($statushtml, 4);
2541 if (substr($statushtml, 0, -4) == '<br>') {
2542 $statushtml = substr($statushtml, -4);
2545 // feeds without body should contain the link
2546 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2547 $statushtml .= bbcode($item['plink']);
2550 $entities = api_get_entitities($statustext, $body);
2553 "text" => $statustext,
2554 "html" => $statushtml,
2555 "attachments" => $attachments,
2556 "entities" => $entities
2560 function api_get_attachments(&$body)
2563 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2565 $URLSearchString = "^\[\]";
2566 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2572 $attachments = array();
2574 foreach ($images[1] as $image) {
2575 $imagedata = Image::getInfoFromURL($image);
2578 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2582 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2583 foreach ($images[0] as $orig) {
2584 $body = str_replace($orig, "", $body);
2588 return $attachments;
2591 function api_get_entitities(&$text, $bbcode)
2595 * Links at the first character of the post
2600 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2602 if ($include_entities != "true") {
2603 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2605 foreach ($images[1] as $image) {
2606 $replace = proxy_url($image);
2607 $text = str_replace($image, $replace, $text);
2612 $bbcode = bb_CleanPictureLinks($bbcode);
2614 // Change pure links in text to bbcode uris
2615 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2617 $entities = array();
2618 $entities["hashtags"] = array();
2619 $entities["symbols"] = array();
2620 $entities["urls"] = array();
2621 $entities["user_mentions"] = array();
2623 $URLSearchString = "^\[\]";
2625 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2627 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2628 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2629 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2631 $bbcode = preg_replace(
2632 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2633 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2636 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2638 $bbcode = preg_replace(
2639 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2640 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2643 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2645 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2647 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2648 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2650 $ordered_urls = array();
2651 foreach ($urls[1] as $id => $url) {
2652 //$start = strpos($text, $url, $offset);
2653 $start = iconv_strpos($text, $url, 0, "UTF-8");
2654 if (!($start === false)) {
2655 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2659 ksort($ordered_urls);
2662 //foreach ($urls[1] AS $id=>$url) {
2663 foreach ($ordered_urls as $url) {
2664 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2665 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2667 $display_url = $url["title"];
2669 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2670 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2672 if (strlen($display_url) > 26)
2673 $display_url = substr($display_url, 0, 25)."…";
2676 //$start = strpos($text, $url, $offset);
2677 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2678 if (!($start === false)) {
2679 $entities["urls"][] = array("url" => $url["url"],
2680 "expanded_url" => $url["url"],
2681 "display_url" => $display_url,
2682 "indices" => array($start, $start+strlen($url["url"])));
2683 $offset = $start + 1;
2687 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2688 $ordered_images = array();
2689 foreach ($images[1] as $image) {
2690 //$start = strpos($text, $url, $offset);
2691 $start = iconv_strpos($text, $image, 0, "UTF-8");
2692 if (!($start === false))
2693 $ordered_images[$start] = $image;
2695 //$entities["media"] = array();
2698 foreach ($ordered_images as $url) {
2699 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2700 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2702 if (strlen($display_url) > 26)
2703 $display_url = substr($display_url, 0, 25)."…";
2705 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2706 if (!($start === false)) {
2707 $image = Image::getInfoFromURL($url);
2709 // If image cache is activated, then use the following sizes:
2710 // thumb (150), small (340), medium (600) and large (1024)
2711 if (!Config::get("system", "proxy_disabled")) {
2712 $media_url = proxy_url($url);
2715 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2716 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2718 if (($image[0] > 150) || ($image[1] > 150)) {
2719 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2720 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2723 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2724 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2726 if (($image[0] > 600) || ($image[1] > 600)) {
2727 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2728 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2732 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2735 $entities["media"][] = array(
2737 "id_str" => (string)$start+1,
2738 "indices" => array($start, $start+strlen($url)),
2739 "media_url" => normalise_link($media_url),
2740 "media_url_https" => $media_url,
2742 "display_url" => $display_url,
2743 "expanded_url" => $url,
2747 $offset = $start + 1;
2753 function api_format_items_embeded_images(&$item, $text)
2755 $text = preg_replace_callback(
2756 "|data:image/([^;]+)[^=]+=*|m",
2757 function ($match) use ($item) {
2758 return System::baseUrl()."/display/".$item['guid'];
2767 * @brief return <a href='url'>name</a> as array
2769 * @param string $txt text
2774 function api_contactlink_to_array($txt)
2777 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2778 if ($r && count($match)==3) {
2780 'name' => $match[2],
2794 * @brief return likes, dislikes and attend status for item
2796 * @param array $item array
2798 * likes => int count
2799 * dislikes => int count
2801 function api_format_items_activities(&$item, $type = "json")
2805 $activities = array(
2807 'dislike' => array(),
2808 'attendyes' => array(),
2809 'attendno' => array(),
2810 'attendmaybe' => array(),
2815 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2816 intval($item['uid']),
2820 foreach ($items as $i) {
2821 // not used as result should be structured like other user data
2822 //builtin_activity_puller($i, $activities);
2824 // get user data and add it to the array of the activity
2825 $user = api_get_user($a, $i['author-link']);
2826 switch ($i['verb']) {
2828 $activities['like'][] = $user;
2830 case ACTIVITY_DISLIKE:
2831 $activities['dislike'][] = $user;
2833 case ACTIVITY_ATTEND:
2834 $activities['attendyes'][] = $user;
2836 case ACTIVITY_ATTENDNO:
2837 $activities['attendno'][] = $user;
2839 case ACTIVITY_ATTENDMAYBE:
2840 $activities['attendmaybe'][] = $user;
2847 if ($type == "xml") {
2848 $xml_activities = array();
2849 foreach ($activities as $k => $v) {
2850 // change xml element from "like" to "friendica:like"
2851 $xml_activities["friendica:".$k] = $v;
2852 // add user data into xml output
2854 foreach ($v as $user)
2855 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2857 $activities = $xml_activities;
2865 * @brief return data from profiles
2867 * @param array $profile array containing data from db table 'profile'
2868 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2871 function api_format_items_profiles(&$profile = null, $type = "json")
2873 if ($profile != null) {
2874 $profile = array('profile_id' => $profile['id'],
2875 'profile_name' => $profile['profile-name'],
2876 'is_default' => $profile['is-default'] ? true : false,
2877 'hide_friends'=> $profile['hide-friends'] ? true : false,
2878 'profile_photo' => $profile['photo'],
2879 'profile_thumb' => $profile['thumb'],
2880 'publish' => $profile['publish'] ? true : false,
2881 'net_publish' => $profile['net-publish'] ? true : false,
2882 'description' => $profile['pdesc'],
2883 'date_of_birth' => $profile['dob'],
2884 'address' => $profile['address'],
2885 'city' => $profile['locality'],
2886 'region' => $profile['region'],
2887 'postal_code' => $profile['postal-code'],
2888 'country' => $profile['country-name'],
2889 'hometown' => $profile['hometown'],
2890 'gender' => $profile['gender'],
2891 'marital' => $profile['marital'],
2892 'marital_with' => $profile['with'],
2893 'marital_since' => $profile['howlong'],
2894 'sexual' => $profile['sexual'],
2895 'politic' => $profile['politic'],
2896 'religion' => $profile['religion'],
2897 'public_keywords' => $profile['pub_keywords'],
2898 'private_keywords' => $profile['prv_keywords'],
2899 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2900 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2901 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2902 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2903 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2904 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2905 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2906 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2907 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2908 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2909 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2910 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2911 'homepage' => $profile['homepage'],
2918 * @brief format items to be returned by api
2920 * @param array $r array of items
2921 * @param array $user_info
2922 * @param bool $filter_user filter items by $user_info
2924 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2930 foreach ($r as $item) {
2931 localize_item($item);
2932 list($status_user, $owner_user) = api_item_get_user($a, $item);
2934 // Look if the posts are matching if they should be filtered by user id
2935 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2939 $in_reply_to = api_in_reply_to($item);
2941 $converted = api_convert_item($item);
2943 if ($type == "xml") {
2944 $geo = "georss:point";
2950 'text' => $converted["text"],
2951 'truncated' => false,
2952 'created_at'=> api_date($item['created']),
2953 'in_reply_to_status_id' => $in_reply_to['status_id'],
2954 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2955 'source' => (($item['app']) ? $item['app'] : 'web'),
2956 'id' => intval($item['id']),
2957 'id_str' => (string) intval($item['id']),
2958 'in_reply_to_user_id' => $in_reply_to['user_id'],
2959 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2960 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2962 'favorited' => $item['starred'] ? true : false,
2963 'user' => $status_user ,
2964 'friendica_owner' => $owner_user,
2965 //'entities' => NULL,
2966 'statusnet_html' => $converted["html"],
2967 'statusnet_conversation_id' => $item['parent'],
2968 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2969 'friendica_activities' => api_format_items_activities($item, $type),
2972 if (count($converted["attachments"]) > 0) {
2973 $status["attachments"] = $converted["attachments"];
2976 if (count($converted["entities"]) > 0) {
2977 $status["entities"] = $converted["entities"];
2980 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
2981 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2982 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2983 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2987 // Retweets are only valid for top postings
2988 // It doesn't work reliable with the link if its a feed
2989 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2991 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
2994 if ($item["id"] == $item["parent"]) {
2995 $retweeted_item = api_share_as_retweet($item);
2996 if ($retweeted_item !== false) {
2997 $retweeted_status = $status;
2999 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
3000 } catch (BadRequestException $e) {
3001 // user not found. should be found?
3002 /// @todo check if the user should be always found
3003 $retweeted_status["user"] = array();
3006 $rt_converted = api_convert_item($retweeted_item);
3008 $retweeted_status['text'] = $rt_converted["text"];
3009 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3010 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3011 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3012 $status['retweeted_status'] = $retweeted_status;
3016 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3017 unset($status["user"]["uid"]);
3018 unset($status["user"]["self"]);
3020 if ($item["coord"] != "") {
3021 $coords = explode(' ', $item["coord"]);
3022 if (count($coords) == 2) {
3023 if ($type == "json")
3024 $status["geo"] = array('type' => 'Point',
3025 'coordinates' => array((float) $coords[0],
3026 (float) $coords[1]));
3027 else // Not sure if this is the official format - if someone founds a documentation we can check
3028 $status["georss:point"] = $item["coord"];
3036 function api_account_rate_limit_status($type)
3038 if ($type == "xml") {
3040 'remaining-hits' => '150',
3041 '@attributes' => array("type" => "integer"),
3042 'hourly-limit' => '150',
3043 '@attributes2' => array("type" => "integer"),
3044 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
3045 '@attributes3' => array("type" => "datetime"),
3046 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3047 '@attributes4' => array("type" => "integer"),
3051 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3052 'remaining_hits' => '150',
3053 'hourly_limit' => '150',
3054 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
3058 return api_format_data('hash', $type, array('hash' => $hash));
3061 /// @TODO move to top of file or somwhere better
3062 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3064 function api_help_test($type)
3066 if ($type == 'xml') {
3072 return api_format_data('ok', $type, array("ok" => $ok));
3075 /// @TODO move to top of file or somwhere better
3076 api_register_func('api/help/test', 'api_help_test', false);
3078 function api_lists($type)
3081 /// @TODO $ret is not filled here?
3082 return api_format_data('lists', $type, array("lists_list" => $ret));
3085 /// @TODO move to top of file or somwhere better
3086 api_register_func('api/lists', 'api_lists', true);
3088 function api_lists_list($type)
3091 /// @TODO $ret is not filled here?
3092 return api_format_data('lists', $type, array("lists_list" => $ret));
3095 /// @TODO move to top of file or somwhere better
3096 api_register_func('api/lists/list', 'api_lists_list', true);
3099 * @brief Returns either the friends of the follower list
3101 * Note: Considers friends and followers lists to be private and won't return
3102 * anything if any user_id parameter is passed.
3104 * @param string $qtype Either "friends" or "followers"
3105 * @return boolean|array
3106 * @throws ForbiddenException
3108 function api_statuses_f($qtype)
3112 if (api_user() === false) {
3113 throw new ForbiddenException();
3117 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3118 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3122 $start = ($page - 1) * $count;
3124 $user_info = api_get_user($a);
3126 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3127 /* this is to stop Hotot to load friends multiple times
3128 * I'm not sure if I'm missing return something or
3129 * is a bug in hotot. Workaround, meantime
3133 return array('$users' => $ret);*/
3137 if ($qtype == 'friends') {
3138 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3140 if ($qtype == 'followers') {
3141 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3144 // friends and followers only for self
3145 if ($user_info['self'] == 0) {
3146 $sql_extra = " AND false ";
3149 if ($qtype == 'blocks') {
3150 $sql_blocked = 'AND `blocked`';
3152 $sql_blocked = 'AND NOT `blocked`';
3171 foreach ($r as $cid) {
3172 $user = api_get_user($a, $cid['nurl']);
3173 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3174 unset($user["uid"]);
3175 unset($user["self"]);
3182 return array('user' => $ret);
3187 * @brief Returns the list of friends of the provided user
3189 * @deprecated By Twitter API in favor of friends/list
3191 * @param string $type Either "json" or "xml"
3192 * @return boolean|string|array
3194 function api_statuses_friends($type)
3196 $data = api_statuses_f("friends");
3197 if ($data === false) {
3200 return api_format_data("users", $type, $data);
3204 * @brief Returns the list of friends of the provided user
3206 * @deprecated By Twitter API in favor of friends/list
3208 * @param string $type Either "json" or "xml"
3209 * @return boolean|string|array
3211 function api_statuses_followers($type)
3213 $data = api_statuses_f("followers");
3214 if ($data === false) {
3217 return api_format_data("users", $type, $data);
3220 /// @TODO move to top of file or somewhere better
3221 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3222 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3225 * Returns the list of blocked users
3227 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3229 * @param string $type Either "json" or "xml"
3231 * @return boolean|string|array
3232 * @throws UnauthorizedException
3234 function api_blocks_list($type)
3236 $data = api_statuses_f('blocks');
3237 if ($data === false) {
3240 return api_format_data("users", $type, $data);
3243 /// @TODO move to top of file or somewhere better
3244 api_register_func('api/blocks/list', 'api_blocks_list', true);
3246 function api_statusnet_config($type)
3250 $name = $a->config['sitename'];
3251 $server = $a->get_hostname();
3252 $logo = System::baseUrl() . '/images/friendica-64.png';
3253 $email = $a->config['admin_email'];
3254 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3255 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3256 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3257 if ($a->config['api_import_size']) {
3258 $texlimit = string($a->config['api_import_size']);
3260 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3261 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3264 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3265 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3266 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3267 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3268 'shorturllength' => '30',
3269 'friendica' => array(
3270 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3271 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3272 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3273 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3278 return api_format_data('config', $type, array('config' => $config));
3281 /// @TODO move to top of file or somewhere better
3282 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3283 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3285 function api_statusnet_version($type)
3288 $fake_statusnet_version = "0.9.7";
3290 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
3293 /// @TODO move to top of file or somewhere better
3294 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3295 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3298 * @todo use api_format_data() to return data
3300 function api_ff_ids($type,$qtype)
3305 throw new ForbiddenException();
3308 $user_info = api_get_user($a);
3310 if ($qtype == 'friends') {
3311 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3313 if ($qtype == 'followers') {
3314 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3317 if (!$user_info["self"]) {
3318 $sql_extra = " AND false ";
3321 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3324 "SELECT `pcontact`.`id` FROM `contact`
3325 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3326 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3330 if (!DBM::is_result($r)) {
3335 foreach ($r as $rr) {
3336 if ($stringify_ids) {
3339 $ids[] = intval($rr['id']);
3343 return api_format_data("ids", $type, array('id' => $ids));
3346 function api_friends_ids($type)
3348 return api_ff_ids($type, 'friends');
3351 function api_followers_ids($type)
3353 return api_ff_ids($type, 'followers');
3356 /// @TODO move to top of file or somewhere better
3357 api_register_func('api/friends/ids', 'api_friends_ids', true);
3358 api_register_func('api/followers/ids', 'api_followers_ids', true);
3360 function api_direct_messages_new($type)
3365 if (api_user() === false) throw new ForbiddenException();
3367 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) return;
3369 $sender = api_get_user($a);
3371 if ($_POST['screen_name']) {
3373 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3375 dbesc($_POST['screen_name'])
3378 // Selecting the id by priority, friendica first
3379 api_best_nickname($r);
3381 $recipient = api_get_user($a, $r[0]['nurl']);
3383 $recipient = api_get_user($a, $_POST['user_id']);
3388 if (x($_REQUEST, 'replyto')) {
3390 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3392 intval($_REQUEST['replyto'])
3394 $replyto = $r[0]['parent-uri'];
3395 $sub = $r[0]['title'];
3397 if (x($_REQUEST, 'title')) {
3398 $sub = $_REQUEST['title'];
3400 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3404 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3407 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3408 $ret = api_format_messages($r[0], $recipient, $sender);
3410 $ret = array("error"=>$id);
3413 $data = array('direct_message'=>$ret);
3418 $data = api_rss_extra($a, $data, $user_info);
3421 return api_format_data("direct-messages", $type, $data);
3425 /// @TODO move to top of file or somewhere better
3426 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3429 * @brief delete a direct_message from mail table through api
3431 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3434 function api_direct_messages_destroy($type)
3438 if (api_user() === false) {
3439 throw new ForbiddenException();
3443 $user_info = api_get_user($a);
3445 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3447 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3448 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3449 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3451 $uid = $user_info['uid'];
3452 // error if no id or parenturi specified (for clients posting parent-uri as well)
3453 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3454 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3455 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3458 // BadRequestException if no id specified (for clients using Twitter API)
3460 throw new BadRequestException('Message id not specified');
3463 // add parent-uri to sql command if specified by calling app
3464 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3466 // get data of the specified message id
3468 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3473 // error message if specified id is not in database
3474 if (!DBM::is_result($r)) {
3475 if ($verbose == "true") {
3476 $answer = array('result' => 'error', 'message' => 'message id not in database');
3477 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3479 /// @todo BadRequestException ok for Twitter API clients?
3480 throw new BadRequestException('message id not in database');
3485 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3490 if ($verbose == "true") {
3493 $answer = array('result' => 'ok', 'message' => 'message deleted');
3494 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3496 $answer = array('result' => 'error', 'message' => 'unknown error');
3497 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3500 /// @todo return JSON data like Twitter API not yet implemented
3504 /// @TODO move to top of file or somewhere better
3505 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3507 function api_direct_messages_box($type, $box, $verbose)
3511 if (api_user() === false) {
3512 throw new ForbiddenException();
3516 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3517 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3522 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3523 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3525 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3526 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3529 unset($_REQUEST["user_id"]);
3530 unset($_GET["user_id"]);
3532 unset($_REQUEST["screen_name"]);
3533 unset($_GET["screen_name"]);
3535 $user_info = api_get_user($a);
3536 $profile_url = $user_info["url"];
3539 $start = $page * $count;
3542 if ($box=="sentbox") {
3543 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3544 } elseif ($box == "conversation") {
3545 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3546 } elseif ($box == "all") {
3547 $sql_extra = "true";
3548 } elseif ($box == "inbox") {
3549 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3553 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3556 if ($user_id != "") {
3557 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3558 } elseif ($screen_name !="") {
3559 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3563 "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",
3569 if ($verbose == "true" && !DBM::is_result($r)) {
3570 $answer = array('result' => 'error', 'message' => 'no mails available');
3571 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3575 foreach ($r as $item) {
3576 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3577 $recipient = $user_info;
3578 $sender = api_get_user($a, normalise_link($item['contact-url']));
3579 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3580 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3581 $sender = $user_info;
3584 $ret[] = api_format_messages($item, $recipient, $sender);
3588 $data = array('direct_message' => $ret);
3592 $data = api_rss_extra($a, $data, $user_info);
3595 return api_format_data("direct-messages", $type, $data);
3598 function api_direct_messages_sentbox($type)
3600 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3601 return api_direct_messages_box($type, "sentbox", $verbose);
3604 function api_direct_messages_inbox($type)
3606 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3607 return api_direct_messages_box($type, "inbox", $verbose);
3610 function api_direct_messages_all($type)
3612 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3613 return api_direct_messages_box($type, "all", $verbose);
3616 function api_direct_messages_conversation($type)
3618 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3619 return api_direct_messages_box($type, "conversation", $verbose);
3622 /// @TODO move to top of file or somewhere better
3623 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3624 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3625 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3626 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3628 function api_oauth_request_token($type)
3630 $oauth1 = new FKOAuth1();
3632 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3633 } catch (Exception $e) {
3634 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3641 function api_oauth_access_token($type)
3643 $oauth1 = new FKOAuth1();
3645 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3646 } catch (Exception $e) {
3647 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3654 /// @TODO move to top of file or somewhere better
3655 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3656 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3660 * @brief delete a complete photoalbum with all containing photos from database through api
3662 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3665 function api_fr_photoalbum_delete($type)
3667 if (api_user() === false) {
3668 throw new ForbiddenException();
3671 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3673 // we do not allow calls without album string
3675 throw new BadRequestException("no albumname specified");
3677 // check if album is existing
3679 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3683 if (!DBM::is_result($r))
3684 throw new BadRequestException("album not available");
3686 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3687 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3688 foreach ($r as $rr) {
3690 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3691 intval(local_user()),
3692 dbesc($rr['resource-id'])
3695 if (!DBM::is_result($photo_item)) {
3696 throw new InternalServerErrorException("problem with deleting items occured");
3698 drop_item($photo_item[0]['id'], false);
3701 // now let's delete all photos from the album
3702 $result = dba::delete('photo', array('uid' => api_user(), 'album' => $album));
3704 // return success of deletion or error message
3706 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3707 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3709 throw new InternalServerErrorException("unknown error - deleting from database failed");
3714 * @brief update the name of the album for all photos of an album
3716 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3719 function api_fr_photoalbum_update($type)
3721 if (api_user() === false) {
3722 throw new ForbiddenException();
3725 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3726 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3728 // we do not allow calls without album string
3730 throw new BadRequestException("no albumname specified");
3732 if ($album_new == "") {
3733 throw new BadRequestException("no new albumname specified");
3735 // check if album is existing
3737 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3741 if (!DBM::is_result($r)) {
3742 throw new BadRequestException("album not available");
3744 // now let's update all photos to the albumname
3746 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3752 // return success of updating or error message
3754 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3755 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3757 throw new InternalServerErrorException("unknown error - updating in database failed");
3763 * @brief list all photos of the authenticated user
3765 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3768 function api_fr_photos_list($type)
3770 if (api_user() === false) {
3771 throw new ForbiddenException();
3774 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3775 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3776 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3777 intval(local_user())
3780 'image/jpeg' => 'jpg',
3781 'image/png' => 'png',
3782 'image/gif' => 'gif'
3784 $data = array('photo'=>array());
3785 if (DBM::is_result($r)) {
3786 foreach ($r as $rr) {
3788 $photo['id'] = $rr['resource-id'];
3789 $photo['album'] = $rr['album'];
3790 $photo['filename'] = $rr['filename'];
3791 $photo['type'] = $rr['type'];
3792 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3793 $photo['created'] = $rr['created'];
3794 $photo['edited'] = $rr['edited'];
3795 $photo['desc'] = $rr['desc'];
3797 if ($type == "xml") {
3798 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3800 $photo['thumb'] = $thumb;
3801 $data['photo'][] = $photo;
3805 return api_format_data("photos", $type, $data);
3809 * @brief upload a new photo or change an existing photo
3811 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3814 function api_fr_photo_create_update($type)
3816 if (api_user() === false) {
3817 throw new ForbiddenException();
3820 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3821 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3822 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3823 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3824 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3825 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3826 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3827 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3828 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3830 // do several checks on input parameters
3831 // we do not allow calls without album string
3832 if ($album == null) {
3833 throw new BadRequestException("no albumname specified");
3835 // if photo_id == null --> we are uploading a new photo
3836 if ($photo_id == null) {
3839 // error if no media posted in create-mode
3840 if (!x($_FILES, 'media')) {
3842 throw new BadRequestException("no media data submitted");
3845 // album_new will be ignored in create-mode
3850 // check if photo is existing in database
3852 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3857 if (!DBM::is_result($r)) {
3858 throw new BadRequestException("photo not available");
3862 // checks on acl strings provided by clients
3863 $acl_input_error = false;
3864 $acl_input_error |= check_acl_input($allow_cid);
3865 $acl_input_error |= check_acl_input($deny_cid);
3866 $acl_input_error |= check_acl_input($allow_gid);
3867 $acl_input_error |= check_acl_input($deny_gid);
3868 if ($acl_input_error) {
3869 throw new BadRequestException("acl data invalid");
3871 // now let's upload the new media in create-mode
3872 if ($mode == "create") {
3873 $media = $_FILES['media'];
3874 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3876 // return success of updating or error message
3877 if (!is_null($data)) {
3878 return api_format_data("photo_create", $type, $data);
3880 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3884 // now let's do the changes in update-mode
3885 if ($mode == "update") {
3888 if (!is_null($desc)) {
3889 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3892 if (!is_null($album_new)) {
3893 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3896 if (!is_null($allow_cid)) {
3897 $allow_cid = trim($allow_cid);
3898 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3901 if (!is_null($deny_cid)) {
3902 $deny_cid = trim($deny_cid);
3903 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3906 if (!is_null($allow_gid)) {
3907 $allow_gid = trim($allow_gid);
3908 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3911 if (!is_null($deny_gid)) {
3912 $deny_gid = trim($deny_gid);
3913 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3917 if ($sql_extra != "") {
3918 $nothingtodo = false;
3920 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3922 datetime_convert(), // update edited timestamp
3928 $nothingtodo = true;
3931 if (x($_FILES, 'media')) {
3932 $nothingtodo = false;
3933 $media = $_FILES['media'];
3934 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3935 if (!is_null($data)) {
3936 return api_format_data("photo_update", $type, $data);
3940 // return success of updating or error message
3942 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
3943 return api_format_data("photo_update", $type, array('$result' => $answer));
3946 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
3947 return api_format_data("photo_update", $type, array('$result' => $answer));
3949 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3952 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3957 * @brief delete a single photo from the database through api
3959 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3962 function api_fr_photo_delete($type)
3964 if (api_user() === false) {
3965 throw new ForbiddenException();
3968 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3970 // do several checks on input parameters
3971 // we do not allow calls without photo id
3972 if ($photo_id == null) {
3973 throw new BadRequestException("no photo_id specified");
3975 // check if photo is existing in database
3977 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3981 if (!DBM::is_result($r)) {
3982 throw new BadRequestException("photo not available");
3984 // now we can perform on the deletion of the photo
3985 $result = dba::delete('photo', array('uid' => api_user(), 'resource-id' => $photo_id));
3987 // return success of deletion or error message
3989 // retrieve the id of the parent element (the photo element)
3991 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3992 intval(local_user()),
3996 if (!DBM::is_result($photo_item)) {
3997 throw new InternalServerErrorException("problem with deleting items occured");
3999 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4000 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4001 drop_item($photo_item[0]['id'], false);
4003 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
4004 return api_format_data("photo_delete", $type, array('$result' => $answer));
4006 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4012 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4014 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4017 function api_fr_photo_detail($type)
4019 if (api_user() === false) {
4020 throw new ForbiddenException();
4022 if (!x($_REQUEST, 'photo_id')) {
4023 throw new BadRequestException("No photo id.");
4026 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4027 $photo_id = $_REQUEST['photo_id'];
4029 // prepare json/xml output with data from database for the requested photo
4030 $data = prepare_photo_data($type, $scale, $photo_id);
4032 return api_format_data("photo_detail", $type, $data);
4037 * @brief updates the profile image for the user (either a specified profile or the default profile)
4039 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4042 function api_account_update_profile_image($type)
4044 if (api_user() === false) {
4045 throw new ForbiddenException();
4048 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
4050 // error if image data is missing
4051 if (!x($_FILES, 'image')) {
4052 throw new BadRequestException("no media data submitted");
4055 // check if specified profile id is valid
4056 if ($profileid != 0) {
4058 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4062 // error message if specified profile id is not in database
4063 if (!DBM::is_result($r)) {
4064 throw new BadRequestException("profile_id not available");
4066 $is_default_profile = $r['profile'];
4068 $is_default_profile = 1;
4071 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4073 if (x($_FILES, 'image')) {
4074 $media = $_FILES['image'];
4075 } elseif (x($_FILES, 'media')) {
4076 $media = $_FILES['media'];
4078 // save new profile image
4079 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4082 if (is_array($media['type'])) {
4083 $filetype = $media['type'][0];
4085 $filetype = $media['type'];
4087 if ($filetype == "image/jpeg") {
4089 } elseif ($filetype == "image/png") {
4092 // change specified profile or all profiles to the new resource-id
4093 if ($is_default_profile) {
4095 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4096 dbesc($data['photo']['id']),
4097 intval(local_user())
4101 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
4102 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4103 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4104 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4105 intval(local_user())
4109 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4110 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4111 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4112 intval($_REQUEST['profile']),
4113 intval(local_user())
4117 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4118 // so that browsers will do a cache update unconditionally
4121 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4122 dbesc(datetime_convert()),
4123 intval(local_user())
4126 // Update global directory in background
4127 //$user = api_get_user(get_app());
4128 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4129 if ($url && strlen(Config::get('system', 'directory'))) {
4130 Worker::add(PRIORITY_LOW, "Directory", $url);
4133 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4135 // output for client
4137 return api_account_verify_credentials($type);
4139 // SaveMediaToDatabase failed for some reason
4140 throw new InternalServerErrorException("image upload failed");
4144 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4145 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4146 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4147 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4148 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4149 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4150 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4151 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4152 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4155 function check_acl_input($acl_string)
4157 if ($acl_string == null || $acl_string == " ") {
4160 $contact_not_found = false;
4162 // split <x><y><z> into array of cid's
4163 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4165 // check for each cid if it is available on server
4166 $cid_array = $array[0];
4167 foreach ($cid_array as $cid) {
4168 $cid = str_replace("<", "", $cid);
4169 $cid = str_replace(">", "", $cid);
4171 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4175 $contact_not_found |= !DBM::is_result($contact);
4177 return $contact_not_found;
4180 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)
4188 if (is_array($media)) {
4189 if (is_array($media['tmp_name'])) {
4190 $src = $media['tmp_name'][0];
4192 $src = $media['tmp_name'];
4194 if (is_array($media['name'])) {
4195 $filename = basename($media['name'][0]);
4197 $filename = basename($media['name']);
4199 if (is_array($media['size'])) {
4200 $filesize = intval($media['size'][0]);
4202 $filesize = intval($media['size']);
4204 if (is_array($media['type'])) {
4205 $filetype = $media['type'][0];
4207 $filetype = $media['type'];
4211 if ($filetype == "") {
4212 $filetype=Image::guessType($filename);
4214 $imagedata = getimagesize($src);
4216 $filetype = $imagedata['mime'];
4219 "File upload src: " . $src . " - filename: " . $filename .
4220 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG
4223 // check if there was a php upload error
4224 if ($filesize == 0 && $media['error'] == 1) {
4225 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4227 // check against max upload size within Friendica instance
4228 $maximagesize = Config::get('system', 'maximagesize');
4229 if (($maximagesize) && ($filesize > $maximagesize)) {
4230 $formattedBytes = formatBytes($maximagesize);
4231 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4234 // create Photo instance with the data of the image
4235 $imagedata = @file_get_contents($src);
4236 $Image = new Image($imagedata, $filetype);
4237 if (! $Image->isValid()) {
4238 throw new InternalServerErrorException("unable to process image data");
4241 // check orientation of image
4242 $Image->orient($src);
4245 // check max length of images on server
4246 $max_length = Config::get('system', 'max_image_length');
4247 if (! $max_length) {
4248 $max_length = MAX_IMAGE_LENGTH;
4250 if ($max_length > 0) {
4251 $Image->scaleDown($max_length);
4252 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4254 $width = $Image->getWidth();
4255 $height = $Image->getHeight();
4257 // create a new resource-id if not already provided
4258 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
4260 if ($mediatype == "photo") {
4261 // upload normal image (scales 0, 1, 2)
4262 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4264 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4266 logger("photo upload: image upload with scale 0 (original size) failed");
4268 if ($width > 640 || $height > 640) {
4269 $Image->scaleDown(640);
4270 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4272 logger("photo upload: image upload with scale 1 (640x640) failed");
4276 if ($width > 320 || $height > 320) {
4277 $Image->scaleDown(320);
4278 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4280 logger("photo upload: image upload with scale 2 (320x320) failed");
4283 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4284 } elseif ($mediatype == "profileimage") {
4285 // upload profile image (scales 4, 5, 6)
4286 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4288 if ($width > 175 || $height > 175) {
4289 $Image->scaleDown(175);
4290 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4292 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4296 if ($width > 80 || $height > 80) {
4297 $Image->scaleDown(80);
4298 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4300 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4304 if ($width > 48 || $height > 48) {
4305 $Image->scaleDown(48);
4306 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4308 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4311 $Image->__destruct();
4312 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4316 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4317 if ($photo_id == null && $mediatype == "photo") {
4318 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4320 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4321 return prepare_photo_data($type, false, $hash);
4323 throw new InternalServerErrorException("image upload failed");
4327 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4329 // get data about the api authenticated user
4330 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4331 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4334 $arr['guid'] = get_guid(32);
4335 $arr['uid'] = intval(api_user());
4337 $arr['parent-uri'] = $uri;
4338 $arr['type'] = 'photo';
4340 $arr['resource-id'] = $hash;
4341 $arr['contact-id'] = $owner_record[0]['id'];
4342 $arr['owner-name'] = $owner_record[0]['name'];
4343 $arr['owner-link'] = $owner_record[0]['url'];
4344 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4345 $arr['author-name'] = $owner_record[0]['name'];
4346 $arr['author-link'] = $owner_record[0]['url'];
4347 $arr['author-avatar'] = $owner_record[0]['thumb'];
4349 $arr['allow_cid'] = $allow_cid;
4350 $arr['allow_gid'] = $allow_gid;
4351 $arr['deny_cid'] = $deny_cid;
4352 $arr['deny_gid'] = $deny_gid;
4353 $arr['last-child'] = 1;
4354 $arr['visible'] = $visibility;
4358 'image/jpeg' => 'jpg',
4359 'image/png' => 'png',
4360 'image/gif' => 'gif'
4363 // adds link to the thumbnail scale photo
4364 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4365 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4368 // do the magic for storing the item in the database and trigger the federation to other contacts
4372 function prepare_photo_data($type, $scale, $photo_id)
4374 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4375 $data_sql = ($scale === false ? "" : "data, ");
4377 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4378 // clients needs to convert this in their way for further processing
4380 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4381 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4382 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4383 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4385 intval(local_user()),
4391 'image/jpeg' => 'jpg',
4392 'image/png' => 'png',
4393 'image/gif' => 'gif'
4396 // prepare output data for photo
4397 if (DBM::is_result($r)) {
4398 $data = array('photo' => $r[0]);
4399 $data['photo']['id'] = $data['photo']['resource-id'];
4400 if ($scale !== false) {
4401 $data['photo']['data'] = base64_encode($data['photo']['data']);
4403 unset($data['photo']['datasize']); //needed only with scale param
4405 if ($type == "xml") {
4406 $data['photo']['links'] = array();
4407 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4408 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4410 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4413 $data['photo']['link'] = array();
4414 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4416 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4417 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4421 unset($data['photo']['resource-id']);
4422 unset($data['photo']['minscale']);
4423 unset($data['photo']['maxscale']);
4425 throw new NotFoundException();
4428 // retrieve item element for getting activities (like, dislike etc.) related to photo
4430 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4431 intval(local_user()),
4434 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4436 // retrieve comments on photo
4438 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4439 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4440 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4441 `contact`.`id` AS `cid`
4443 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4444 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4445 WHERE `item`.`parent` = %d AND `item`.`visible`
4446 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4447 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4448 intval($item[0]['parent']),
4450 dbesc(ACTIVITY_POST)
4453 // prepare output of comments
4454 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4455 $comments = array();
4456 if ($type == "xml") {
4458 foreach ($commentData as $comment) {
4459 $comments[$k++ . ":comment"] = $comment;
4462 foreach ($commentData as $comment) {
4463 $comments[] = $comment;
4466 $data['photo']['friendica_comments'] = $comments;
4468 // include info if rights on photo and rights on item are mismatching
4469 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4470 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4471 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4472 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4473 $data['photo']['rights_mismatch'] = $rights_mismatch;
4480 * Similar as /mod/redir.php
4481 * redirect to 'url' after dfrn auth
4483 * Why this when there is mod/redir.php already?
4484 * This use api_user() and api_login()
4487 * c_url: url of remote contact to auth to
4488 * url: string, url to redirect after auth
4490 function api_friendica_remoteauth()
4492 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4493 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4495 if ($url === '' || $c_url === '') {
4496 throw new BadRequestException("Wrong parameters.");
4499 $c_url = normalise_link($c_url);
4504 "SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4509 if ((! DBM::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4510 throw new BadRequestException("Unknown contact");
4515 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4517 if ($r[0]['duplex'] && $r[0]['issued-id']) {
4518 $orig_id = $r[0]['issued-id'];
4519 $dfrn_id = '1:' . $orig_id;
4521 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4522 $orig_id = $r[0]['dfrn-id'];
4523 $dfrn_id = '0:' . $orig_id;
4526 $sec = random_string();
4529 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4530 VALUES( %d, %s, '%s', '%s', %d )",
4538 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4539 $dest = (($url) ? '&destination_url=' . $url : '');
4541 $r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4542 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4543 . '&type=profile&sec=' . $sec . $dest . $quiet
4546 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4549 * @brief Return the item shared, if the item contains only the [share] tag
4551 * @param array $item Sharer item
4552 * @return array Shared item or false if not a reshare
4554 function api_share_as_retweet(&$item)
4556 $body = trim($item["body"]);
4558 if (Diaspora::isReshare($body, false)===false) {
4562 /// @TODO "$1" should maybe mean '$1' ?
4563 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4565 * Skip if there is no shared message in there
4566 * we already checked this in diaspora::isReshare()
4567 * but better one more than one less...
4569 if ($body == $attributes) {
4574 // build the fake reshared item
4575 $reshared_item = $item;
4578 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4579 if ($matches[1] != "") {
4580 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4583 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4584 if ($matches[1] != "") {
4585 $author = $matches[1];
4589 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4590 if ($matches[1] != "") {
4591 $profile = $matches[1];
4594 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4595 if ($matches[1] != "") {
4596 $profile = $matches[1];
4600 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4601 if ($matches[1] != "") {
4602 $avatar = $matches[1];
4605 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4606 if ($matches[1] != "") {
4607 $avatar = $matches[1];
4611 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4612 if ($matches[1] != "") {
4613 $link = $matches[1];
4616 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4617 if ($matches[1] != "") {
4618 $link = $matches[1];
4622 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4623 if ($matches[1] != "")
4624 $posted = $matches[1];
4626 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4627 if ($matches[1] != "") {
4628 $posted = $matches[1];
4631 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4633 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4637 $reshared_item["body"] = $shared_body;
4638 $reshared_item["author-name"] = $author;
4639 $reshared_item["author-link"] = $profile;
4640 $reshared_item["author-avatar"] = $avatar;
4641 $reshared_item["plink"] = $link;
4642 $reshared_item["created"] = $posted;
4643 $reshared_item["edited"] = $posted;
4645 return $reshared_item;
4649 function api_get_nick($profile)
4652 - remove trailing junk from profile url
4653 - pump.io check has to check the website
4659 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4660 dbesc(normalise_link($profile))
4663 if (DBM::is_result($r)) {
4664 $nick = $r[0]["nick"];
4669 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4670 dbesc(normalise_link($profile))
4673 if (DBM::is_result($r)) {
4674 $nick = $r[0]["nick"];
4679 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4680 if ($friendica != $profile) {
4686 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4687 if ($diaspora != $profile) {
4693 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4694 if ($twitter != $profile) {
4701 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4702 if ($StatusnetHost != $profile) {
4703 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4704 if ($StatusnetUser != $profile) {
4705 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4706 $user = json_decode($UserData);
4708 $nick = $user->screen_name;
4714 // To-Do: look at the page if its really a pumpio site
4715 //if (!$nick == "") {
4716 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4717 // if ($pumpio != $profile)
4719 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4730 function api_in_reply_to($item)
4732 $in_reply_to = array();
4734 $in_reply_to['status_id'] = null;
4735 $in_reply_to['user_id'] = null;
4736 $in_reply_to['status_id_str'] = null;
4737 $in_reply_to['user_id_str'] = null;
4738 $in_reply_to['screen_name'] = null;
4740 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4741 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4742 intval($item['uid']),
4743 dbesc($item['thr-parent']));
4745 if (DBM::is_result($r)) {
4746 $in_reply_to['status_id'] = intval($r[0]['id']);
4748 $in_reply_to['status_id'] = intval($item['parent']);
4751 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4753 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4754 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4755 WHERE `item`.`id` = %d LIMIT 1",
4756 intval($in_reply_to['status_id'])
4759 if (DBM::is_result($r)) {
4760 if ($r[0]['nick'] == "") {
4761 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4764 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4765 $in_reply_to['user_id'] = intval($r[0]['id']);
4766 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4769 // There seems to be situation, where both fields are identical:
4770 // https://github.com/friendica/friendica/issues/1010
4771 // This is a bugfix for that.
4772 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4773 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4774 $in_reply_to['status_id'] = null;
4775 $in_reply_to['user_id'] = null;
4776 $in_reply_to['status_id_str'] = null;
4777 $in_reply_to['user_id_str'] = null;
4778 $in_reply_to['screen_name'] = null;
4782 return $in_reply_to;
4785 function api_clean_plain_items($Text)
4787 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4789 $Text = bb_CleanPictureLinks($Text);
4790 $URLSearchString = "^\[\]";
4792 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
4794 if ($include_entities == "true") {
4795 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
4798 // Simplify "attachment" element
4799 $Text = api_clean_attachments($Text);
4805 * @brief Removes most sharing information for API text export
4807 * @param string $body The original body
4809 * @return string Cleaned body
4811 function api_clean_attachments($body)
4813 $data = get_attachment_data($body);
4820 if (isset($data["text"]))
4821 $body = $data["text"];
4823 if (($body == "") && (isset($data["title"])))
4824 $body = $data["title"];
4826 if (isset($data["url"]))
4827 $body .= "\n".$data["url"];
4829 $body .= $data["after"];
4834 function api_best_nickname(&$contacts)
4836 $best_contact = array();
4838 if (count($contact) == 0)
4841 foreach ($contacts as $contact)
4842 if ($contact["network"] == "") {
4843 $contact["network"] = "dfrn";
4844 $best_contact = array($contact);
4847 if (sizeof($best_contact) == 0)
4848 foreach ($contacts as $contact)
4849 if ($contact["network"] == "dfrn")
4850 $best_contact = array($contact);
4852 if (sizeof($best_contact) == 0)
4853 foreach ($contacts as $contact)
4854 if ($contact["network"] == "dspr")
4855 $best_contact = array($contact);
4857 if (sizeof($best_contact) == 0)
4858 foreach ($contacts as $contact)
4859 if ($contact["network"] == "stat")
4860 $best_contact = array($contact);
4862 if (sizeof($best_contact) == 0)
4863 foreach ($contacts as $contact)
4864 if ($contact["network"] == "pump")
4865 $best_contact = array($contact);
4867 if (sizeof($best_contact) == 0)
4868 foreach ($contacts as $contact)
4869 if ($contact["network"] == "twit")
4870 $best_contact = array($contact);
4872 if (sizeof($best_contact) == 1) {
4873 $contacts = $best_contact;
4875 $contacts = array($contacts[0]);
4879 // return all or a specified group of the user with the containing contacts
4880 function api_friendica_group_show($type)
4884 if (api_user() === false) throw new ForbiddenException();
4887 $user_info = api_get_user($a);
4888 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4889 $uid = $user_info['uid'];
4891 // get data of the specified group id or all groups if not specified
4894 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4898 // error message if specified gid is not in database
4899 if (!DBM::is_result($r))
4900 throw new BadRequestException("gid not available");
4903 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4908 // loop through all groups and retrieve all members for adding data in the user array
4909 foreach ($r as $rr) {
4910 $members = Contact::getByGroupId($rr['id']);
4913 if ($type == "xml") {
4914 $user_element = "users";
4916 foreach ($members as $member) {
4917 $user = api_get_user($a, $member['nurl']);
4918 $users[$k++.":user"] = $user;
4921 $user_element = "user";
4922 foreach ($members as $member) {
4923 $user = api_get_user($a, $member['nurl']);
4927 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4929 return api_format_data("groups", $type, array('group' => $grps));
4931 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4934 // delete the specified group of the user
4935 function api_friendica_group_delete($type)
4939 if (api_user() === false) {
4940 throw new ForbiddenException();
4944 $user_info = api_get_user($a);
4945 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4946 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4947 $uid = $user_info['uid'];
4949 // error if no gid specified
4950 if ($gid == 0 || $name == "") {
4951 throw new BadRequestException('gid or name not specified');
4954 // get data of the specified group id
4956 "SELECT * FROM `group` WHERE `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 // get data of the specified group id and group name
4967 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
4972 // error message if specified gid is not in database
4973 if (!DBM::is_result($rname)) {
4974 throw new BadRequestException('wrong group name');
4978 $ret = Group::removeByName($uid, $name);
4981 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
4982 return api_format_data("group_delete", $type, array('result' => $success));
4984 throw new BadRequestException('other API error');
4987 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4990 // create the specified group with the posted array of contacts
4991 function api_friendica_group_create($type)
4995 if (api_user() === false) throw new ForbiddenException();
4998 $user_info = api_get_user($a);
4999 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5000 $uid = $user_info['uid'];
5001 $json = json_decode($_POST['json'], true);
5002 $users = $json['user'];
5004 // error if no name specified
5006 throw new BadRequestException('group name not specified');
5008 // get data of the specified group name
5010 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5014 // error message if specified group name already exists
5015 if (DBM::is_result($rname))
5016 throw new BadRequestException('group name already exists');
5018 // check if specified group name is a deleted group
5020 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5024 // error message if specified group name already exists
5025 if (DBM::is_result($rname))
5026 $reactivate_group = true;
5029 $ret = Group::create($uid, $name);
5031 $gid = Group::getIdByName($uid, $name);
5033 throw new BadRequestException('other API error');
5037 $erroraddinguser = false;
5038 $errorusers = array();
5039 foreach ($users as $user) {
5040 $cid = $user['cid'];
5041 // check if user really exists as contact
5043 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5047 if (count($contact))
5048 $result = Group::addMember($gid, $cid);
5050 $erroraddinguser = true;
5051 $errorusers[] = $cid;
5055 // return success message incl. missing users in array
5056 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
5057 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
5058 return api_format_data("group_create", $type, array('result' => $success));
5060 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5063 // update the specified group with the posted array of contacts
5064 function api_friendica_group_update($type)
5068 if (api_user() === false) throw new ForbiddenException();
5071 $user_info = api_get_user($a);
5072 $uid = $user_info['uid'];
5073 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5074 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5075 $json = json_decode($_POST['json'], true);
5076 $users = $json['user'];
5078 // error if no name specified
5080 throw new BadRequestException('group name not specified');
5082 // error if no gid specified
5084 throw new BadRequestException('gid not specified');
5087 $members = Contact::getByGroupId($gid);
5088 foreach ($members as $member) {
5089 $cid = $member['id'];
5090 foreach ($users as $user) {
5091 $found = ($user['cid'] == $cid ? true : false);
5094 $ret = Group::removeMemberByName($uid, $name, $cid);
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",
5110 if (count($contact)) {
5111 $result = Group::addMember($gid, $cid);
5113 $erroraddinguser = true;
5114 $errorusers[] = $cid;
5118 // return success message incl. missing users in array
5119 $status = ($erroraddinguser ? "missing user" : "ok");
5120 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
5121 return api_format_data("group_update", $type, array('result' => $success));
5124 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5126 function api_friendica_activity($type)
5130 if (api_user() === false) throw new ForbiddenException();
5131 $verb = strtolower($a->argv[3]);
5132 $verb = preg_replace("|\..*$|", "", $verb);
5134 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5136 $res = do_like($id, $verb);
5139 if ($type == "xml") {
5144 return api_format_data('ok', $type, array('ok' => $ok));
5146 throw new BadRequestException('Error adding activity');
5150 /// @TODO move to top of file or somwhere better
5151 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5152 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5153 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5154 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5155 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5156 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5157 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5158 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5159 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5160 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5163 * @brief Returns notifications
5165 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5168 function api_friendica_notification($type)
5172 if (api_user() === false) throw new ForbiddenException();
5173 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
5174 $nm = new NotificationsManager();
5176 $notes = $nm->getAll(array(), "+seen -date", 50);
5178 if ($type == "xml") {
5179 $xmlnotes = array();
5180 foreach ($notes as $note)
5181 $xmlnotes[] = array("@attributes" => $note);
5186 return api_format_data("notes", $type, array('note' => $notes));
5190 * @brief Set notification as seen and returns associated item (if possible)
5192 * POST request with 'id' param as notification id
5194 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5197 function api_friendica_notification_seen($type)
5201 if (api_user() === false) throw new ForbiddenException();
5202 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
5204 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5206 $nm = new NotificationsManager();
5207 $note = $nm->getByID($id);
5208 if (is_null($note)) throw new BadRequestException("Invalid argument");
5210 $nm->setSeen($note);
5211 if ($note['otype']=='item') {
5212 // would be really better with an ItemsManager and $im->getByID() :-P
5214 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5215 intval($note['iid']),
5216 intval(local_user())
5219 // we found the item, return it to the user
5220 $user_info = api_get_user($a);
5221 $ret = api_format_items($r, $user_info, false, $type);
5222 $data = array('status' => $ret);
5223 return api_format_data("status", $type, $data);
5225 // the item can't be found, but we set the note as seen, so we count this as a success
5227 return api_format_data('result', $type, array('result' => "success"));
5230 /// @TODO move to top of file or somwhere better
5231 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5232 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5235 * @brief update a direct_message to seen state
5237 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5238 * @return string (success result=ok, error result=error with error message)
5240 function api_friendica_direct_messages_setseen($type)
5243 if (api_user() === false) {
5244 throw new ForbiddenException();
5248 $user_info = api_get_user($a);
5249 $uid = $user_info['uid'];
5250 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5252 // return error if id is zero
5254 $answer = array('result' => 'error', 'message' => 'message id not specified');
5255 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5258 // get data of the specified message id
5260 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5265 // error message if specified id is not in database
5266 if (!DBM::is_result($r)) {
5267 $answer = array('result' => 'error', 'message' => 'message id not in database');
5268 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5271 // update seen indicator
5273 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5280 $answer = array('result' => 'ok', 'message' => 'message set to seen');
5281 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
5283 $answer = array('result' => 'error', 'message' => 'unknown error');
5284 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5288 /// @TODO move to top of file or somwhere better
5289 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5292 * @brief search for direct_messages containing a searchstring through api
5294 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5295 * @return string (success: success=true if found and search_result contains found messages
5296 * success=false if nothing was found, search_result='nothing found',
5297 * error: result=error with error message)
5299 function api_friendica_direct_messages_search($type)
5303 if (api_user() === false) {
5304 throw new ForbiddenException();
5308 $user_info = api_get_user($a);
5309 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5310 $uid = $user_info['uid'];
5312 // error if no searchstring specified
5313 if ($searchstring == "") {
5314 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
5315 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
5318 // get data for the specified searchstring
5320 "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",
5322 dbesc('%'.$searchstring.'%')
5325 $profile_url = $user_info["url"];
5327 // message if nothing was found
5328 if (!DBM::is_result($r)) {
5329 $success = array('success' => false, 'search_results' => 'problem with query');
5330 } elseif (count($r) == 0) {
5331 $success = array('success' => false, 'search_results' => 'nothing found');
5334 foreach ($r as $item) {
5335 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5336 $recipient = $user_info;
5337 $sender = api_get_user($a, normalise_link($item['contact-url']));
5338 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5339 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5340 $sender = $user_info;
5343 $ret[] = api_format_messages($item, $recipient, $sender);
5345 $success = array('success' => true, 'search_results' => $ret);
5348 return api_format_data("direct_message_search", $type, array('$result' => $success));
5351 /// @TODO move to top of file or somwhere better
5352 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5355 * @brief return data of all the profiles a user has to the client
5357 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5360 function api_friendica_profile_show($type)
5364 if (api_user() === false) {
5365 throw new ForbiddenException();
5369 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5371 // retrieve general information about profiles for user
5372 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5373 $directory = Config::get('system', 'directory');
5375 // get data of the specified profile id or all profiles of the user if not specified
5376 if ($profileid != 0) {
5378 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5383 // error message if specified gid is not in database
5384 if (!DBM::is_result($r)) {
5385 throw new BadRequestException("profile_id not available");
5389 "SELECT * FROM `profile` WHERE `uid` = %d",
5393 // loop through all returned profiles and retrieve data and users
5395 foreach ($r as $rr) {
5396 $profile = api_format_items_profiles($rr, $type);
5398 // select all users from contact table, loop and prepare standard return for user data
5401 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5403 intval($rr['profile_id'])
5406 foreach ($r as $rr) {
5407 $user = api_get_user($a, $rr['nurl']);
5408 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5410 $profile['users'] = $users;
5412 // add prepared profile data to array for final return
5413 if ($type == "xml") {
5414 $profiles[$k++ . ":profile"] = $profile;
5416 $profiles[] = $profile;
5420 // return settings, authenticated user and profiles data
5421 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5423 $result = array('multi_profiles' => $multi_profiles ? true : false,
5424 'global_dir' => $directory,
5425 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5426 'profiles' => $profiles);
5427 return api_format_data("friendica_profiles", $type, array('$result' => $result));
5429 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5432 @TODO Maybe open to implement?
5434 [pagename] => api/1.1/statuses/lookup.json
5435 [id] => 605138389168451584
5436 [include_cards] => true
5437 [cards_platform] => Android-12
5438 [include_entities] => true
5439 [include_my_retweet] => 1
5441 [include_reply_count] => true
5442 [include_descendent_reply_count] => true
5446 Not implemented by now:
5447 statuses/retweets_of_me
5452 account/update_location
5453 account/update_profile_background_image
5456 friendica/profile/update
5457 friendica/profile/create
5458 friendica/profile/delete
5460 Not implemented in status.net:
5461 statuses/retweeted_to_me
5462 statuses/retweeted_by_me
5463 direct_messages/destroy
5465 account/update_delivery_device
5466 notifications/follow