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');
1522 * http://developer.twitter.com/doc/get/statuses/home_timeline
1524 * TODO: Optional parameters
1525 * TODO: Add reply info
1527 function api_statuses_home_timeline($type)
1531 if (api_user() === false) {
1532 throw new ForbiddenException();
1535 unset($_REQUEST["user_id"]);
1536 unset($_GET["user_id"]);
1538 unset($_REQUEST["screen_name"]);
1539 unset($_GET["screen_name"]);
1541 $user_info = api_get_user($a);
1542 // get last newtork messages
1545 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1546 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1550 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1551 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1552 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1553 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1554 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1556 $start = $page * $count;
1560 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1562 if ($exclude_replies > 0) {
1563 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1565 if ($conversation_id > 0) {
1566 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1570 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1571 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1572 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1573 `contact`.`id` AS `cid`
1575 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1576 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1577 WHERE `item`.`uid` = %d AND `verb` = '%s'
1578 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1581 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1583 dbesc(ACTIVITY_POST),
1589 $ret = api_format_items($r, $user_info, false, $type);
1591 // Set all posts from the query above to seen
1593 foreach ($r as $item) {
1594 $idarray[] = intval($item["id"]);
1597 $idlist = implode(",", $idarray);
1599 if ($idlist != "") {
1600 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1603 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1607 $data = array('status' => $ret);
1611 $data = api_rss_extra($a, $data, $user_info);
1615 return api_format_data("statuses", $type, $data);
1618 /// @TODO move to top of file or somewhere better
1619 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1620 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1622 function api_statuses_public_timeline($type)
1626 if (api_user() === false) {
1627 throw new ForbiddenException();
1630 $user_info = api_get_user($a);
1631 // get last newtork messages
1634 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1635 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1639 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1640 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1641 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1642 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1643 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1645 $start = $page * $count;
1647 if ($exclude_replies && !$conversation_id) {
1649 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1652 $r = dba::p("SELECT " . item_fieldlists() . "
1654 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1655 " . item_joins() . "
1656 STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1657 AND NOT `user`.`hidewall`
1659 AND NOT `thread`.`private`
1661 AND `thread`.`visible`
1662 AND NOT `thread`.`deleted`
1663 AND NOT `thread`.`moderated`
1664 AND `thread`.`iid` > ?
1666 ORDER BY `thread`.`iid` DESC
1667 LIMIT " . intval($start) . ", " . intval($count),
1672 $r = dba::inArray($r);
1675 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1677 if ($conversation_id > 0) {
1678 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1681 $r = dba::p("SELECT " . item_fieldlists() . "
1683 " . item_joins() . "
1684 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1685 AND NOT `user`.`hidewall`
1687 AND NOT `item`.`private`
1689 AND `item`.`visible`
1690 AND NOT `item`.`deleted`
1691 AND NOT `item`.`moderated`
1694 ORDER BY `item`.`id` DESC
1695 LIMIT " . intval($start) . ", " . intval($count),
1700 $r = dba::inArray($r);
1703 $ret = api_format_items($r, $user_info, false, $type);
1705 $data = array('status' => $ret);
1709 $data = api_rss_extra($a, $data, $user_info);
1713 return api_format_data("statuses", $type, $data);
1716 /// @TODO move to top of file or somewhere better
1717 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1720 * @brief Returns the list of public federated posts this node knows about
1722 * @param string $type Return format: json, xml, atom, rss
1723 * @return array|string
1724 * @throws ForbiddenException
1726 function api_statuses_networkpublic_timeline($type)
1730 if (api_user() === false) {
1731 throw new ForbiddenException();
1734 $user_info = api_get_user($a);
1736 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1737 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1740 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1741 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1745 $start = ($page - 1) * $count;
1749 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1752 $r = dba::p("SELECT " . item_fieldlists() . "
1754 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1755 " . item_joins() . "
1756 WHERE `thread`.`uid` = 0
1758 AND NOT `thread`.`private`
1759 AND `thread`.`visible`
1760 AND NOT `thread`.`deleted`
1761 AND NOT `thread`.`moderated`
1762 AND `thread`.`iid` > ?
1764 ORDER BY `thread`.`iid` DESC
1765 LIMIT " . intval($start) . ", " . intval($count),
1770 $r = dba::inArray($r);
1772 $ret = api_format_items($r, $user_info, false, $type);
1774 $data = array('status' => $ret);
1778 $data = api_rss_extra($a, $data, $user_info);
1782 return api_format_data("statuses", $type, $data);
1785 /// @TODO move to top of file or somewhere better
1786 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1789 * @TODO nothing to say?
1791 function api_statuses_show($type)
1795 if (api_user() === false) {
1796 throw new ForbiddenException();
1799 $user_info = api_get_user($a);
1802 $id = intval($a->argv[3]);
1805 $id = intval($_REQUEST["id"]);
1810 $id = intval($a->argv[4]);
1813 logger('API: api_statuses_show: ' . $id);
1815 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1818 if ($conversation) {
1819 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1821 $sql_extra .= " AND `item`.`id` = %d";
1825 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1826 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1827 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1828 `contact`.`id` AS `cid`
1830 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1831 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1832 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1833 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1836 dbesc(ACTIVITY_POST),
1840 /// @TODO How about copying this to above methods which don't check $r ?
1841 if (!DBM::is_result($r)) {
1842 throw new BadRequestException("There is no status with this id.");
1845 $ret = api_format_items($r, $user_info, false, $type);
1847 if ($conversation) {
1848 $data = array('status' => $ret);
1849 return api_format_data("statuses", $type, $data);
1851 $data = array('status' => $ret[0]);
1852 return api_format_data("status", $type, $data);
1856 /// @TODO move to top of file or somewhere better
1857 api_register_func('api/statuses/show', 'api_statuses_show', true);
1860 * @TODO nothing to say?
1862 function api_conversation_show($type)
1866 if (api_user() === false) {
1867 throw new ForbiddenException();
1870 $user_info = api_get_user($a);
1873 $id = intval($a->argv[3]);
1874 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1875 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1879 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1880 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1882 $start = $page*$count;
1885 $id = intval($_REQUEST["id"]);
1890 $id = intval($a->argv[4]);
1893 logger('API: api_conversation_show: '.$id);
1895 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1896 if (DBM::is_result($r)) {
1897 $id = $r[0]["parent"];
1903 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1906 // Not sure why this query was so complicated. We should keep it here for a while,
1907 // just to make sure that we really don't need it.
1908 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1909 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1912 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1913 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1914 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1915 `contact`.`id` AS `cid`
1917 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1918 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1919 WHERE `item`.`parent` = %d AND `item`.`visible`
1920 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1921 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1922 AND `item`.`id`>%d $sql_extra
1923 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1924 intval($id), intval(api_user()),
1925 dbesc(ACTIVITY_POST),
1927 intval($start), intval($count)
1930 if (!DBM::is_result($r)) {
1931 throw new BadRequestException("There is no status with this id.");
1934 $ret = api_format_items($r, $user_info, false, $type);
1936 $data = array('status' => $ret);
1937 return api_format_data("statuses", $type, $data);
1940 /// @TODO move to top of file or somewhere better
1941 api_register_func('api/conversation/show', 'api_conversation_show', true);
1942 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1945 * @TODO nothing to say?
1947 function api_statuses_repeat($type)
1953 if (api_user() === false) {
1954 throw new ForbiddenException();
1957 $user_info = api_get_user($a);
1960 $id = intval($a->argv[3]);
1963 $id = intval($_REQUEST["id"]);
1968 $id = intval($a->argv[4]);
1971 logger('API: api_statuses_repeat: '.$id);
1974 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1975 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1976 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1977 `contact`.`id` AS `cid`
1979 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1980 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1981 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1982 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1983 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1985 AND `item`.`id`=%d",
1989 /// @TODO other style than above functions!
1990 if (DBM::is_result($r) && $r[0]['body'] != "") {
1991 if (strpos($r[0]['body'], "[/share]") !== false) {
1992 $pos = strpos($r[0]['body'], "[share");
1993 $post = substr($r[0]['body'], $pos);
1995 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1997 $post .= $r[0]['body'];
1998 $post .= "[/share]";
2000 $_REQUEST['body'] = $post;
2001 $_REQUEST['profile_uid'] = api_user();
2002 $_REQUEST['type'] = 'wall';
2003 $_REQUEST['api_source'] = true;
2005 if (!x($_REQUEST, "source")) {
2006 $_REQUEST["source"] = api_source();
2011 throw new ForbiddenException();
2014 // this should output the last post (the one we just posted).
2016 return api_status_show($type);
2019 /// @TODO move to top of file or somewhere better
2020 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2023 * @TODO nothing to say?
2025 function api_statuses_destroy($type)
2029 if (api_user() === false) {
2030 throw new ForbiddenException();
2033 $user_info = api_get_user($a);
2036 $id = intval($a->argv[3]);
2039 $id = intval($_REQUEST["id"]);
2044 $id = intval($a->argv[4]);
2047 logger('API: api_statuses_destroy: '.$id);
2049 $ret = api_statuses_show($type);
2051 drop_item($id, false);
2056 /// @TODO move to top of file or somewhere better
2057 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2060 * @TODO Nothing more than an URL to say?
2061 * http://developer.twitter.com/doc/get/statuses/mentions
2063 function api_statuses_mentions($type)
2067 if (api_user() === false) {
2068 throw new ForbiddenException();
2071 unset($_REQUEST["user_id"]);
2072 unset($_GET["user_id"]);
2074 unset($_REQUEST["screen_name"]);
2075 unset($_GET["screen_name"]);
2077 $user_info = api_get_user($a);
2078 // get last newtork messages
2082 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2083 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2087 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2088 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2089 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2091 $start = $page * $count;
2093 // Ugly code - should be changed
2094 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2095 $myurl = substr($myurl, strpos($myurl, '://') + 3);
2096 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
2097 $myurl = str_replace('www.', '', $myurl);
2098 $diasp_url = str_replace('/profile/', '/u/', $myurl);
2101 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2105 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2106 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2107 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2108 `contact`.`id` AS `cid`
2109 FROM `item` FORCE INDEX (`uid_id`)
2110 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2111 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2112 WHERE `item`.`uid` = %d AND `verb` = '%s'
2113 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2114 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2115 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2118 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2120 dbesc(ACTIVITY_POST),
2121 dbesc(protect_sprintf($myurl)),
2122 dbesc(protect_sprintf($myurl)),
2129 $ret = api_format_items($r, $user_info, false, $type);
2131 $data = array('status' => $ret);
2135 $data = api_rss_extra($a, $data, $user_info);
2139 return api_format_data("statuses", $type, $data);
2142 /// @TODO move to top of file or somewhere better
2143 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2144 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2147 * @brief Returns a user's public timeline
2149 * @param string $type Either "json" or "xml"
2150 * @return string|array
2151 * @throws ForbiddenException
2153 function api_statuses_user_timeline($type)
2157 if (api_user() === false) {
2158 throw new ForbiddenException();
2161 $user_info = api_get_user($a);
2164 "api_statuses_user_timeline: api_user: ". api_user() .
2165 "\nuser_info: ".print_r($user_info, true) .
2166 "\n_REQUEST: ".print_r($_REQUEST, true),
2170 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2171 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2172 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2173 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2176 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2177 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2181 $start = ($page - 1) * $count;
2184 if ($user_info['self'] == 1) {
2185 $sql_extra .= " AND `item`.`wall` = 1 ";
2188 if ($exclude_replies > 0) {
2189 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2192 if ($conversation_id > 0) {
2193 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2197 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2201 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2202 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2203 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2204 `contact`.`id` AS `cid`
2205 FROM `item` FORCE INDEX (`uid_contactid_id`)
2206 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2207 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2208 WHERE `item`.`uid` = %d AND `verb` = '%s'
2209 AND `item`.`contact-id` = %d
2210 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2212 AND `item`.`id` > %d
2213 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2215 dbesc(ACTIVITY_POST),
2216 intval($user_info['cid']),
2222 $ret = api_format_items($r, $user_info, true, $type);
2224 $data = array('status' => $ret);
2228 $data = api_rss_extra($a, $data, $user_info);
2232 return api_format_data("statuses", $type, $data);
2235 /// @TODO move to top of file or somwhere better
2236 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2239 * Star/unstar an item
2240 * param: id : id of the item
2242 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2244 function api_favorites_create_destroy($type)
2248 if (api_user() === false) {
2249 throw new ForbiddenException();
2252 // for versioned api.
2253 /// @TODO We need a better global soluton
2254 $action_argv_id = 2;
2255 if ($a->argv[1] == "1.1") {
2256 $action_argv_id = 3;
2259 if ($a->argc <= $action_argv_id) {
2260 throw new BadRequestException("Invalid request.");
2262 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2263 if ($a->argc == $action_argv_id + 2) {
2264 $itemid = intval($a->argv[$action_argv_id + 1]);
2266 /// @TODO use x() to check if _REQUEST contains 'id'
2267 $itemid = intval($_REQUEST['id']);
2270 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2272 if (!DBM::is_result($item) || count($item) == 0) {
2273 throw new BadRequestException("Invalid item.");
2278 $item[0]['starred'] = 1;
2281 $item[0]['starred'] = 0;
2284 throw new BadRequestException("Invalid action ".$action);
2287 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2289 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2292 throw new InternalServerErrorException("DB error");
2296 $user_info = api_get_user($a);
2297 $rets = api_format_items($item, $user_info, false, $type);
2300 $data = array('status' => $ret);
2304 $data = api_rss_extra($a, $data, $user_info);
2307 return api_format_data("status", $type, $data);
2310 /// @TODO move to top of file or somwhere better
2311 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2312 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2314 function api_favorites($type)
2320 if (api_user() === false) {
2321 throw new ForbiddenException();
2324 $called_api = array();
2326 $user_info = api_get_user($a);
2328 // in friendica starred item are private
2329 // return favorites only for self
2330 logger('api_favorites: self:' . $user_info['self']);
2332 if ($user_info['self'] == 0) {
2338 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2339 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2340 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2341 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2346 $start = $page*$count;
2349 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2353 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2354 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2355 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2356 `contact`.`id` AS `cid`
2357 FROM `item`, `contact`
2358 WHERE `item`.`uid` = %d
2359 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2360 AND `item`.`starred` = 1
2361 AND `contact`.`id` = `item`.`contact-id`
2362 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2365 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2372 $ret = api_format_items($r, $user_info, false, $type);
2375 $data = array('status' => $ret);
2379 $data = api_rss_extra($a, $data, $user_info);
2382 return api_format_data("statuses", $type, $data);
2385 /// @TODO move to top of file or somwhere better
2386 api_register_func('api/favorites', 'api_favorites', true);
2388 function api_format_messages($item, $recipient, $sender)
2390 // standard meta information
2392 'id' => $item['id'],
2393 'sender_id' => $sender['id'] ,
2395 'recipient_id' => $recipient['id'],
2396 'created_at' => api_date($item['created']),
2397 'sender_screen_name' => $sender['screen_name'],
2398 'recipient_screen_name' => $recipient['screen_name'],
2399 'sender' => $sender,
2400 'recipient' => $recipient,
2402 'friendica_seen' => $item['seen'],
2403 'friendica_parent_uri' => $item['parent-uri'],
2406 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2407 unset($ret["sender"]["uid"]);
2408 unset($ret["sender"]["self"]);
2409 unset($ret["recipient"]["uid"]);
2410 unset($ret["recipient"]["self"]);
2412 //don't send title to regular StatusNET requests to avoid confusing these apps
2413 if (x($_GET, 'getText')) {
2414 $ret['title'] = $item['title'];
2415 if ($_GET['getText'] == 'html') {
2416 $ret['text'] = bbcode($item['body'], false, false);
2417 } elseif ($_GET['getText'] == 'plain') {
2418 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2419 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2422 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2424 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2425 unset($ret['sender']);
2426 unset($ret['recipient']);
2432 function api_convert_item($item)
2434 $body = $item['body'];
2435 $attachments = api_get_attachments($body);
2437 // Workaround for ostatus messages where the title is identically to the body
2438 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2439 $statusbody = trim(html2plain($html, 0));
2441 // handle data: images
2442 $statusbody = api_format_items_embeded_images($item, $statusbody);
2444 $statustitle = trim($item['title']);
2446 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2447 $statustext = trim($statusbody);
2449 $statustext = trim($statustitle."\n\n".$statusbody);
2452 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2453 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2456 $statushtml = trim(bbcode($body, false, false));
2458 // Workaround for clients with limited HTML parser functionality
2459 $search = array("<br>", "<blockquote>", "</blockquote>",
2460 "<h1>", "</h1>", "<h2>", "</h2>",
2461 "<h3>", "</h3>", "<h4>", "</h4>",
2462 "<h5>", "</h5>", "<h6>", "</h6>");
2463 $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2464 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2465 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2466 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2467 $statushtml = str_replace($search, $replace, $statushtml);
2469 if ($item['title'] != "") {
2470 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2474 $oldtext = $statushtml;
2475 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2476 } while ($oldtext != $statushtml);
2478 if (substr($statushtml, 0, 4) == '<br>') {
2479 $statushtml = substr($statushtml, 4);
2482 if (substr($statushtml, 0, -4) == '<br>') {
2483 $statushtml = substr($statushtml, -4);
2486 // feeds without body should contain the link
2487 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2488 $statushtml .= bbcode($item['plink']);
2491 $entities = api_get_entitities($statustext, $body);
2494 "text" => $statustext,
2495 "html" => $statushtml,
2496 "attachments" => $attachments,
2497 "entities" => $entities
2501 function api_get_attachments(&$body)
2504 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2506 $URLSearchString = "^\[\]";
2507 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2513 $attachments = array();
2515 foreach ($images[1] as $image) {
2516 $imagedata = Image::getInfoFromURL($image);
2519 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2523 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2524 foreach ($images[0] as $orig) {
2525 $body = str_replace($orig, "", $body);
2529 return $attachments;
2532 function api_get_entitities(&$text, $bbcode)
2536 * Links at the first character of the post
2541 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2543 if ($include_entities != "true") {
2544 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2546 foreach ($images[1] as $image) {
2547 $replace = proxy_url($image);
2548 $text = str_replace($image, $replace, $text);
2553 $bbcode = bb_CleanPictureLinks($bbcode);
2555 // Change pure links in text to bbcode uris
2556 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2558 $entities = array();
2559 $entities["hashtags"] = array();
2560 $entities["symbols"] = array();
2561 $entities["urls"] = array();
2562 $entities["user_mentions"] = array();
2564 $URLSearchString = "^\[\]";
2566 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2568 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2569 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2570 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2572 $bbcode = preg_replace(
2573 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2574 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2577 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2579 $bbcode = preg_replace(
2580 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2581 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2584 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2586 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2588 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2589 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2591 $ordered_urls = array();
2592 foreach ($urls[1] as $id => $url) {
2593 //$start = strpos($text, $url, $offset);
2594 $start = iconv_strpos($text, $url, 0, "UTF-8");
2595 if (!($start === false)) {
2596 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2600 ksort($ordered_urls);
2603 //foreach ($urls[1] AS $id=>$url) {
2604 foreach ($ordered_urls as $url) {
2605 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2606 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2608 $display_url = $url["title"];
2610 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2611 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2613 if (strlen($display_url) > 26)
2614 $display_url = substr($display_url, 0, 25)."…";
2617 //$start = strpos($text, $url, $offset);
2618 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2619 if (!($start === false)) {
2620 $entities["urls"][] = array("url" => $url["url"],
2621 "expanded_url" => $url["url"],
2622 "display_url" => $display_url,
2623 "indices" => array($start, $start+strlen($url["url"])));
2624 $offset = $start + 1;
2628 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2629 $ordered_images = array();
2630 foreach ($images[1] as $image) {
2631 //$start = strpos($text, $url, $offset);
2632 $start = iconv_strpos($text, $image, 0, "UTF-8");
2633 if (!($start === false))
2634 $ordered_images[$start] = $image;
2636 //$entities["media"] = array();
2639 foreach ($ordered_images as $url) {
2640 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2641 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2643 if (strlen($display_url) > 26)
2644 $display_url = substr($display_url, 0, 25)."…";
2646 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2647 if (!($start === false)) {
2648 $image = Image::getInfoFromURL($url);
2650 // If image cache is activated, then use the following sizes:
2651 // thumb (150), small (340), medium (600) and large (1024)
2652 if (!Config::get("system", "proxy_disabled")) {
2653 $media_url = proxy_url($url);
2656 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2657 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2659 if (($image[0] > 150) || ($image[1] > 150)) {
2660 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2661 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2664 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2665 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2667 if (($image[0] > 600) || ($image[1] > 600)) {
2668 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2669 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2673 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2676 $entities["media"][] = array(
2678 "id_str" => (string)$start+1,
2679 "indices" => array($start, $start+strlen($url)),
2680 "media_url" => normalise_link($media_url),
2681 "media_url_https" => $media_url,
2683 "display_url" => $display_url,
2684 "expanded_url" => $url,
2688 $offset = $start + 1;
2694 function api_format_items_embeded_images(&$item, $text)
2696 $text = preg_replace_callback(
2697 "|data:image/([^;]+)[^=]+=*|m",
2698 function ($match) use ($item) {
2699 return System::baseUrl()."/display/".$item['guid'];
2708 * @brief return <a href='url'>name</a> as array
2710 * @param string $txt text
2715 function api_contactlink_to_array($txt)
2718 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2719 if ($r && count($match)==3) {
2721 'name' => $match[2],
2735 * @brief return likes, dislikes and attend status for item
2737 * @param array $item array
2739 * likes => int count
2740 * dislikes => int count
2742 function api_format_items_activities(&$item, $type = "json")
2746 $activities = array(
2748 'dislike' => array(),
2749 'attendyes' => array(),
2750 'attendno' => array(),
2751 'attendmaybe' => array(),
2756 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2757 intval($item['uid']),
2761 foreach ($items as $i) {
2762 // not used as result should be structured like other user data
2763 //builtin_activity_puller($i, $activities);
2765 // get user data and add it to the array of the activity
2766 $user = api_get_user($a, $i['author-link']);
2767 switch ($i['verb']) {
2769 $activities['like'][] = $user;
2771 case ACTIVITY_DISLIKE:
2772 $activities['dislike'][] = $user;
2774 case ACTIVITY_ATTEND:
2775 $activities['attendyes'][] = $user;
2777 case ACTIVITY_ATTENDNO:
2778 $activities['attendno'][] = $user;
2780 case ACTIVITY_ATTENDMAYBE:
2781 $activities['attendmaybe'][] = $user;
2788 if ($type == "xml") {
2789 $xml_activities = array();
2790 foreach ($activities as $k => $v) {
2791 // change xml element from "like" to "friendica:like"
2792 $xml_activities["friendica:".$k] = $v;
2793 // add user data into xml output
2795 foreach ($v as $user)
2796 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2798 $activities = $xml_activities;
2806 * @brief return data from profiles
2808 * @param array $profile array containing data from db table 'profile'
2809 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2812 function api_format_items_profiles(&$profile = null, $type = "json")
2814 if ($profile != null) {
2815 $profile = array('profile_id' => $profile['id'],
2816 'profile_name' => $profile['profile-name'],
2817 'is_default' => $profile['is-default'] ? true : false,
2818 'hide_friends'=> $profile['hide-friends'] ? true : false,
2819 'profile_photo' => $profile['photo'],
2820 'profile_thumb' => $profile['thumb'],
2821 'publish' => $profile['publish'] ? true : false,
2822 'net_publish' => $profile['net-publish'] ? true : false,
2823 'description' => $profile['pdesc'],
2824 'date_of_birth' => $profile['dob'],
2825 'address' => $profile['address'],
2826 'city' => $profile['locality'],
2827 'region' => $profile['region'],
2828 'postal_code' => $profile['postal-code'],
2829 'country' => $profile['country-name'],
2830 'hometown' => $profile['hometown'],
2831 'gender' => $profile['gender'],
2832 'marital' => $profile['marital'],
2833 'marital_with' => $profile['with'],
2834 'marital_since' => $profile['howlong'],
2835 'sexual' => $profile['sexual'],
2836 'politic' => $profile['politic'],
2837 'religion' => $profile['religion'],
2838 'public_keywords' => $profile['pub_keywords'],
2839 'private_keywords' => $profile['prv_keywords'],
2840 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2841 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2842 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2843 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2844 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2845 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2846 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2847 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2848 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2849 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2850 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2851 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2852 'homepage' => $profile['homepage'],
2859 * @brief format items to be returned by api
2861 * @param array $r array of items
2862 * @param array $user_info
2863 * @param bool $filter_user filter items by $user_info
2865 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2871 foreach ($r as $item) {
2872 localize_item($item);
2873 list($status_user, $owner_user) = api_item_get_user($a, $item);
2875 // Look if the posts are matching if they should be filtered by user id
2876 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2880 $in_reply_to = api_in_reply_to($item);
2882 $converted = api_convert_item($item);
2884 if ($type == "xml") {
2885 $geo = "georss:point";
2891 'text' => $converted["text"],
2892 'truncated' => false,
2893 'created_at'=> api_date($item['created']),
2894 'in_reply_to_status_id' => $in_reply_to['status_id'],
2895 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2896 'source' => (($item['app']) ? $item['app'] : 'web'),
2897 'id' => intval($item['id']),
2898 'id_str' => (string) intval($item['id']),
2899 'in_reply_to_user_id' => $in_reply_to['user_id'],
2900 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2901 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2903 'favorited' => $item['starred'] ? true : false,
2904 'user' => $status_user ,
2905 'friendica_owner' => $owner_user,
2906 //'entities' => NULL,
2907 'statusnet_html' => $converted["html"],
2908 'statusnet_conversation_id' => $item['parent'],
2909 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2910 'friendica_activities' => api_format_items_activities($item, $type),
2913 if (count($converted["attachments"]) > 0) {
2914 $status["attachments"] = $converted["attachments"];
2917 if (count($converted["entities"]) > 0) {
2918 $status["entities"] = $converted["entities"];
2921 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
2922 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2923 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2924 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2928 // Retweets are only valid for top postings
2929 // It doesn't work reliable with the link if its a feed
2930 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2932 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
2935 if ($item["id"] == $item["parent"]) {
2936 $retweeted_item = api_share_as_retweet($item);
2937 if ($retweeted_item !== false) {
2938 $retweeted_status = $status;
2940 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
2941 } catch (BadRequestException $e) {
2942 // user not found. should be found?
2943 /// @todo check if the user should be always found
2944 $retweeted_status["user"] = array();
2947 $rt_converted = api_convert_item($retweeted_item);
2949 $retweeted_status['text'] = $rt_converted["text"];
2950 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2951 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2952 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2953 $status['retweeted_status'] = $retweeted_status;
2957 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2958 unset($status["user"]["uid"]);
2959 unset($status["user"]["self"]);
2961 if ($item["coord"] != "") {
2962 $coords = explode(' ', $item["coord"]);
2963 if (count($coords) == 2) {
2964 if ($type == "json")
2965 $status["geo"] = array('type' => 'Point',
2966 'coordinates' => array((float) $coords[0],
2967 (float) $coords[1]));
2968 else // Not sure if this is the official format - if someone founds a documentation we can check
2969 $status["georss:point"] = $item["coord"];
2977 function api_account_rate_limit_status($type)
2979 if ($type == "xml") {
2981 'remaining-hits' => '150',
2982 '@attributes' => array("type" => "integer"),
2983 'hourly-limit' => '150',
2984 '@attributes2' => array("type" => "integer"),
2985 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
2986 '@attributes3' => array("type" => "datetime"),
2987 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2988 '@attributes4' => array("type" => "integer"),
2992 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2993 'remaining_hits' => '150',
2994 'hourly_limit' => '150',
2995 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
2999 return api_format_data('hash', $type, array('hash' => $hash));
3002 /// @TODO move to top of file or somwhere better
3003 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3005 function api_help_test($type)
3007 if ($type == 'xml') {
3013 return api_format_data('ok', $type, array("ok" => $ok));
3016 /// @TODO move to top of file or somwhere better
3017 api_register_func('api/help/test', 'api_help_test', false);
3019 function api_lists($type)
3022 /// @TODO $ret is not filled here?
3023 return api_format_data('lists', $type, array("lists_list" => $ret));
3026 /// @TODO move to top of file or somwhere better
3027 api_register_func('api/lists', 'api_lists', true);
3029 function api_lists_list($type)
3032 /// @TODO $ret is not filled here?
3033 return api_format_data('lists', $type, array("lists_list" => $ret));
3036 /// @TODO move to top of file or somwhere better
3037 api_register_func('api/lists/list', 'api_lists_list', true);
3040 * @brief Returns either the friends of the follower list
3042 * Note: Considers friends and followers lists to be private and won't return
3043 * anything if any user_id parameter is passed.
3045 * @param string $qtype Either "friends" or "followers"
3046 * @return boolean|array
3047 * @throws ForbiddenException
3049 function api_statuses_f($qtype)
3053 if (api_user() === false) {
3054 throw new ForbiddenException();
3058 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3059 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3063 $start = ($page - 1) * $count;
3065 $user_info = api_get_user($a);
3067 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3068 /* this is to stop Hotot to load friends multiple times
3069 * I'm not sure if I'm missing return something or
3070 * is a bug in hotot. Workaround, meantime
3074 return array('$users' => $ret);*/
3078 if ($qtype == 'friends') {
3079 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3081 if ($qtype == 'followers') {
3082 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3085 // friends and followers only for self
3086 if ($user_info['self'] == 0) {
3087 $sql_extra = " AND false ";
3095 AND (NOT `blocked` OR `pending`)
3105 foreach ($r as $cid) {
3106 $user = api_get_user($a, $cid['nurl']);
3107 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3108 unset($user["uid"]);
3109 unset($user["self"]);
3116 return array('user' => $ret);
3121 * @brief Returns the list of friends of the provided user
3123 * @deprecated By Twitter API in favor of friends/list
3125 * @param string $type Either "json" or "xml"
3126 * @return boolean|string|array
3128 function api_statuses_friends($type)
3130 $data = api_statuses_f("friends");
3131 if ($data === false) {
3134 return api_format_data("users", $type, $data);
3138 * @brief Returns the list of friends of the provided user
3140 * @deprecated By Twitter API in favor of friends/list
3142 * @param string $type Either "json" or "xml"
3143 * @return boolean|string|array
3145 function api_statuses_followers($type)
3147 $data = api_statuses_f("followers");
3148 if ($data === false) {
3151 return api_format_data("users", $type, $data);
3154 /// @TODO move to top of file or somewhere better
3155 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3156 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3158 function api_statusnet_config($type)
3162 $name = $a->config['sitename'];
3163 $server = $a->get_hostname();
3164 $logo = System::baseUrl() . '/images/friendica-64.png';
3165 $email = $a->config['admin_email'];
3166 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3167 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3168 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3169 if ($a->config['api_import_size']) {
3170 $texlimit = string($a->config['api_import_size']);
3172 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3173 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3176 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3177 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3178 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3179 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3180 'shorturllength' => '30',
3181 'friendica' => array(
3182 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3183 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3184 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3185 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3190 return api_format_data('config', $type, array('config' => $config));
3193 /// @TODO move to top of file or somewhere better
3194 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3195 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3197 function api_statusnet_version($type)
3200 $fake_statusnet_version = "0.9.7";
3202 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
3205 /// @TODO move to top of file or somewhere better
3206 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3207 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3210 * @todo use api_format_data() to return data
3212 function api_ff_ids($type,$qtype)
3217 throw new ForbiddenException();
3220 $user_info = api_get_user($a);
3222 if ($qtype == 'friends') {
3223 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3225 if ($qtype == 'followers') {
3226 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3229 if (!$user_info["self"]) {
3230 $sql_extra = " AND false ";
3233 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3236 "SELECT `pcontact`.`id` FROM `contact`
3237 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3238 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3242 if (!DBM::is_result($r)) {
3247 foreach ($r as $rr) {
3248 if ($stringify_ids) {
3251 $ids[] = intval($rr['id']);
3255 return api_format_data("ids", $type, array('id' => $ids));
3258 function api_friends_ids($type)
3260 return api_ff_ids($type, 'friends');
3263 function api_followers_ids($type)
3265 return api_ff_ids($type, 'followers');
3268 /// @TODO move to top of file or somewhere better
3269 api_register_func('api/friends/ids', 'api_friends_ids', true);
3270 api_register_func('api/followers/ids', 'api_followers_ids', true);
3272 function api_direct_messages_new($type)
3277 if (api_user() === false) throw new ForbiddenException();
3279 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) return;
3281 $sender = api_get_user($a);
3283 if ($_POST['screen_name']) {
3285 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3287 dbesc($_POST['screen_name'])
3290 // Selecting the id by priority, friendica first
3291 api_best_nickname($r);
3293 $recipient = api_get_user($a, $r[0]['nurl']);
3295 $recipient = api_get_user($a, $_POST['user_id']);
3300 if (x($_REQUEST, 'replyto')) {
3302 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3304 intval($_REQUEST['replyto'])
3306 $replyto = $r[0]['parent-uri'];
3307 $sub = $r[0]['title'];
3309 if (x($_REQUEST, 'title')) {
3310 $sub = $_REQUEST['title'];
3312 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3316 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3319 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3320 $ret = api_format_messages($r[0], $recipient, $sender);
3322 $ret = array("error"=>$id);
3325 $data = array('direct_message'=>$ret);
3330 $data = api_rss_extra($a, $data, $user_info);
3333 return api_format_data("direct-messages", $type, $data);
3337 /// @TODO move to top of file or somewhere better
3338 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3341 * @brief delete a direct_message from mail table through api
3343 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3346 function api_direct_messages_destroy($type)
3350 if (api_user() === false) {
3351 throw new ForbiddenException();
3355 $user_info = api_get_user($a);
3357 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3359 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3360 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3361 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3363 $uid = $user_info['uid'];
3364 // error if no id or parenturi specified (for clients posting parent-uri as well)
3365 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3366 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3367 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3370 // BadRequestException if no id specified (for clients using Twitter API)
3372 throw new BadRequestException('Message id not specified');
3375 // add parent-uri to sql command if specified by calling app
3376 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3378 // get data of the specified message id
3380 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3385 // error message if specified id is not in database
3386 if (!DBM::is_result($r)) {
3387 if ($verbose == "true") {
3388 $answer = array('result' => 'error', 'message' => 'message id not in database');
3389 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3391 /// @todo BadRequestException ok for Twitter API clients?
3392 throw new BadRequestException('message id not in database');
3397 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3402 if ($verbose == "true") {
3405 $answer = array('result' => 'ok', 'message' => 'message deleted');
3406 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3408 $answer = array('result' => 'error', 'message' => 'unknown error');
3409 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3412 /// @todo return JSON data like Twitter API not yet implemented
3416 /// @TODO move to top of file or somewhere better
3417 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3419 function api_direct_messages_box($type, $box, $verbose)
3423 if (api_user() === false) {
3424 throw new ForbiddenException();
3428 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3429 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3434 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3435 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3437 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3438 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3441 unset($_REQUEST["user_id"]);
3442 unset($_GET["user_id"]);
3444 unset($_REQUEST["screen_name"]);
3445 unset($_GET["screen_name"]);
3447 $user_info = api_get_user($a);
3448 $profile_url = $user_info["url"];
3451 $start = $page * $count;
3454 if ($box=="sentbox") {
3455 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3456 } elseif ($box == "conversation") {
3457 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3458 } elseif ($box == "all") {
3459 $sql_extra = "true";
3460 } elseif ($box == "inbox") {
3461 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3465 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3468 if ($user_id != "") {
3469 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3470 } elseif ($screen_name !="") {
3471 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3475 "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",
3481 if ($verbose == "true" && !DBM::is_result($r)) {
3482 $answer = array('result' => 'error', 'message' => 'no mails available');
3483 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3487 foreach ($r as $item) {
3488 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3489 $recipient = $user_info;
3490 $sender = api_get_user($a, normalise_link($item['contact-url']));
3491 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3492 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3493 $sender = $user_info;
3496 $ret[] = api_format_messages($item, $recipient, $sender);
3500 $data = array('direct_message' => $ret);
3504 $data = api_rss_extra($a, $data, $user_info);
3507 return api_format_data("direct-messages", $type, $data);
3510 function api_direct_messages_sentbox($type)
3512 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3513 return api_direct_messages_box($type, "sentbox", $verbose);
3516 function api_direct_messages_inbox($type)
3518 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3519 return api_direct_messages_box($type, "inbox", $verbose);
3522 function api_direct_messages_all($type)
3524 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3525 return api_direct_messages_box($type, "all", $verbose);
3528 function api_direct_messages_conversation($type)
3530 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3531 return api_direct_messages_box($type, "conversation", $verbose);
3534 /// @TODO move to top of file or somewhere better
3535 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3536 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3537 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3538 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3540 function api_oauth_request_token($type)
3542 $oauth1 = new FKOAuth1();
3544 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3545 } catch (Exception $e) {
3546 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3553 function api_oauth_access_token($type)
3555 $oauth1 = new FKOAuth1();
3557 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3558 } catch (Exception $e) {
3559 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3566 /// @TODO move to top of file or somewhere better
3567 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3568 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3572 * @brief delete a complete photoalbum with all containing photos from database through api
3574 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3577 function api_fr_photoalbum_delete($type)
3579 if (api_user() === false) {
3580 throw new ForbiddenException();
3583 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3585 // we do not allow calls without album string
3587 throw new BadRequestException("no albumname specified");
3589 // check if album is existing
3591 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3595 if (!DBM::is_result($r))
3596 throw new BadRequestException("album not available");
3598 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3599 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3600 foreach ($r as $rr) {
3602 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3603 intval(local_user()),
3604 dbesc($rr['resource-id'])
3607 if (!DBM::is_result($photo_item)) {
3608 throw new InternalServerErrorException("problem with deleting items occured");
3610 drop_item($photo_item[0]['id'], false);
3613 // now let's delete all photos from the album
3614 $result = dba::delete('photo', array('uid' => api_user(), 'album' => $album));
3616 // return success of deletion or error message
3618 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3619 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3621 throw new InternalServerErrorException("unknown error - deleting from database failed");
3626 * @brief update the name of the album for all photos of an album
3628 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3631 function api_fr_photoalbum_update($type)
3633 if (api_user() === false) {
3634 throw new ForbiddenException();
3637 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3638 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3640 // we do not allow calls without album string
3642 throw new BadRequestException("no albumname specified");
3644 if ($album_new == "") {
3645 throw new BadRequestException("no new albumname specified");
3647 // check if album is existing
3649 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3653 if (!DBM::is_result($r)) {
3654 throw new BadRequestException("album not available");
3656 // now let's update all photos to the albumname
3658 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3664 // return success of updating or error message
3666 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3667 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3669 throw new InternalServerErrorException("unknown error - updating in database failed");
3675 * @brief list all photos of the authenticated user
3677 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3680 function api_fr_photos_list($type)
3682 if (api_user() === false) {
3683 throw new ForbiddenException();
3686 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3687 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3688 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3689 intval(local_user())
3692 'image/jpeg' => 'jpg',
3693 'image/png' => 'png',
3694 'image/gif' => 'gif'
3696 $data = array('photo'=>array());
3697 if (DBM::is_result($r)) {
3698 foreach ($r as $rr) {
3700 $photo['id'] = $rr['resource-id'];
3701 $photo['album'] = $rr['album'];
3702 $photo['filename'] = $rr['filename'];
3703 $photo['type'] = $rr['type'];
3704 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3705 $photo['created'] = $rr['created'];
3706 $photo['edited'] = $rr['edited'];
3707 $photo['desc'] = $rr['desc'];
3709 if ($type == "xml") {
3710 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3712 $photo['thumb'] = $thumb;
3713 $data['photo'][] = $photo;
3717 return api_format_data("photos", $type, $data);
3721 * @brief upload a new photo or change an existing photo
3723 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3726 function api_fr_photo_create_update($type)
3728 if (api_user() === false) {
3729 throw new ForbiddenException();
3732 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3733 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3734 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3735 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3736 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3737 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3738 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3739 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3740 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3742 // do several checks on input parameters
3743 // we do not allow calls without album string
3744 if ($album == null) {
3745 throw new BadRequestException("no albumname specified");
3747 // if photo_id == null --> we are uploading a new photo
3748 if ($photo_id == null) {
3751 // error if no media posted in create-mode
3752 if (!x($_FILES, 'media')) {
3754 throw new BadRequestException("no media data submitted");
3757 // album_new will be ignored in create-mode
3762 // check if photo is existing in database
3764 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3769 if (!DBM::is_result($r)) {
3770 throw new BadRequestException("photo not available");
3774 // checks on acl strings provided by clients
3775 $acl_input_error = false;
3776 $acl_input_error |= check_acl_input($allow_cid);
3777 $acl_input_error |= check_acl_input($deny_cid);
3778 $acl_input_error |= check_acl_input($allow_gid);
3779 $acl_input_error |= check_acl_input($deny_gid);
3780 if ($acl_input_error) {
3781 throw new BadRequestException("acl data invalid");
3783 // now let's upload the new media in create-mode
3784 if ($mode == "create") {
3785 $media = $_FILES['media'];
3786 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3788 // return success of updating or error message
3789 if (!is_null($data)) {
3790 return api_format_data("photo_create", $type, $data);
3792 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3796 // now let's do the changes in update-mode
3797 if ($mode == "update") {
3800 if (!is_null($desc)) {
3801 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3804 if (!is_null($album_new)) {
3805 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3808 if (!is_null($allow_cid)) {
3809 $allow_cid = trim($allow_cid);
3810 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3813 if (!is_null($deny_cid)) {
3814 $deny_cid = trim($deny_cid);
3815 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3818 if (!is_null($allow_gid)) {
3819 $allow_gid = trim($allow_gid);
3820 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3823 if (!is_null($deny_gid)) {
3824 $deny_gid = trim($deny_gid);
3825 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3829 if ($sql_extra != "") {
3830 $nothingtodo = false;
3832 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3834 datetime_convert(), // update edited timestamp
3840 $nothingtodo = true;
3843 if (x($_FILES, 'media')) {
3844 $nothingtodo = false;
3845 $media = $_FILES['media'];
3846 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3847 if (!is_null($data)) {
3848 return api_format_data("photo_update", $type, $data);
3852 // return success of updating or error message
3854 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
3855 return api_format_data("photo_update", $type, array('$result' => $answer));
3858 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
3859 return api_format_data("photo_update", $type, array('$result' => $answer));
3861 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3864 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3869 * @brief delete a single photo from the database through api
3871 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3874 function api_fr_photo_delete($type)
3876 if (api_user() === false) {
3877 throw new ForbiddenException();
3880 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3882 // do several checks on input parameters
3883 // we do not allow calls without photo id
3884 if ($photo_id == null) {
3885 throw new BadRequestException("no photo_id specified");
3887 // check if photo is existing in database
3889 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3893 if (!DBM::is_result($r)) {
3894 throw new BadRequestException("photo not available");
3896 // now we can perform on the deletion of the photo
3897 $result = dba::delete('photo', array('uid' => api_user(), 'resource-id' => $photo_id));
3899 // return success of deletion or error message
3901 // retrieve the id of the parent element (the photo element)
3903 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3904 intval(local_user()),
3908 if (!DBM::is_result($photo_item)) {
3909 throw new InternalServerErrorException("problem with deleting items occured");
3911 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3912 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
3913 drop_item($photo_item[0]['id'], false);
3915 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
3916 return api_format_data("photo_delete", $type, array('$result' => $answer));
3918 throw new InternalServerErrorException("unknown error on deleting photo from database table");
3924 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3926 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3929 function api_fr_photo_detail($type)
3931 if (api_user() === false) {
3932 throw new ForbiddenException();
3934 if (!x($_REQUEST, 'photo_id')) {
3935 throw new BadRequestException("No photo id.");
3938 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3939 $photo_id = $_REQUEST['photo_id'];
3941 // prepare json/xml output with data from database for the requested photo
3942 $data = prepare_photo_data($type, $scale, $photo_id);
3944 return api_format_data("photo_detail", $type, $data);
3949 * @brief updates the profile image for the user (either a specified profile or the default profile)
3951 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3954 function api_account_update_profile_image($type)
3956 if (api_user() === false) {
3957 throw new ForbiddenException();
3960 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
3962 // error if image data is missing
3963 if (!x($_FILES, 'image')) {
3964 throw new BadRequestException("no media data submitted");
3967 // check if specified profile id is valid
3968 if ($profileid != 0) {
3970 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
3974 // error message if specified profile id is not in database
3975 if (!DBM::is_result($r)) {
3976 throw new BadRequestException("profile_id not available");
3978 $is_default_profile = $r['profile'];
3980 $is_default_profile = 1;
3983 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3985 if (x($_FILES, 'image')) {
3986 $media = $_FILES['image'];
3987 } elseif (x($_FILES, 'media')) {
3988 $media = $_FILES['media'];
3990 // save new profile image
3991 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
3994 if (is_array($media['type'])) {
3995 $filetype = $media['type'][0];
3997 $filetype = $media['type'];
3999 if ($filetype == "image/jpeg") {
4001 } elseif ($filetype == "image/png") {
4004 // change specified profile or all profiles to the new resource-id
4005 if ($is_default_profile) {
4007 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4008 dbesc($data['photo']['id']),
4009 intval(local_user())
4013 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
4014 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4015 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4016 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4017 intval(local_user())
4021 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4022 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4023 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4024 intval($_REQUEST['profile']),
4025 intval(local_user())
4029 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4030 // so that browsers will do a cache update unconditionally
4033 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4034 dbesc(datetime_convert()),
4035 intval(local_user())
4038 // Update global directory in background
4039 //$user = api_get_user(get_app());
4040 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4041 if ($url && strlen(Config::get('system', 'directory'))) {
4042 Worker::add(PRIORITY_LOW, "Directory", $url);
4045 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4047 // output for client
4049 return api_account_verify_credentials($type);
4051 // SaveMediaToDatabase failed for some reason
4052 throw new InternalServerErrorException("image upload failed");
4056 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4057 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4058 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4059 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4060 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4061 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4062 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4063 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4064 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4067 function check_acl_input($acl_string)
4069 if ($acl_string == null || $acl_string == " ") {
4072 $contact_not_found = false;
4074 // split <x><y><z> into array of cid's
4075 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4077 // check for each cid if it is available on server
4078 $cid_array = $array[0];
4079 foreach ($cid_array as $cid) {
4080 $cid = str_replace("<", "", $cid);
4081 $cid = str_replace(">", "", $cid);
4083 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4087 $contact_not_found |= !DBM::is_result($contact);
4089 return $contact_not_found;
4092 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)
4100 if (is_array($media)) {
4101 if (is_array($media['tmp_name'])) {
4102 $src = $media['tmp_name'][0];
4104 $src = $media['tmp_name'];
4106 if (is_array($media['name'])) {
4107 $filename = basename($media['name'][0]);
4109 $filename = basename($media['name']);
4111 if (is_array($media['size'])) {
4112 $filesize = intval($media['size'][0]);
4114 $filesize = intval($media['size']);
4116 if (is_array($media['type'])) {
4117 $filetype = $media['type'][0];
4119 $filetype = $media['type'];
4123 if ($filetype == "") {
4124 $filetype=Image::guessType($filename);
4126 $imagedata = getimagesize($src);
4128 $filetype = $imagedata['mime'];
4131 "File upload src: " . $src . " - filename: " . $filename .
4132 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG
4135 // check if there was a php upload error
4136 if ($filesize == 0 && $media['error'] == 1) {
4137 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4139 // check against max upload size within Friendica instance
4140 $maximagesize = Config::get('system', 'maximagesize');
4141 if (($maximagesize) && ($filesize > $maximagesize)) {
4142 $formattedBytes = formatBytes($maximagesize);
4143 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4146 // create Photo instance with the data of the image
4147 $imagedata = @file_get_contents($src);
4148 $Image = new Image($imagedata, $filetype);
4149 if (! $Image->isValid()) {
4150 throw new InternalServerErrorException("unable to process image data");
4153 // check orientation of image
4154 $Image->orient($src);
4157 // check max length of images on server
4158 $max_length = Config::get('system', 'max_image_length');
4159 if (! $max_length) {
4160 $max_length = MAX_IMAGE_LENGTH;
4162 if ($max_length > 0) {
4163 $Image->scaleDown($max_length);
4164 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4166 $width = $Image->getWidth();
4167 $height = $Image->getHeight();
4169 // create a new resource-id if not already provided
4170 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
4172 if ($mediatype == "photo") {
4173 // upload normal image (scales 0, 1, 2)
4174 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4176 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4178 logger("photo upload: image upload with scale 0 (original size) failed");
4180 if ($width > 640 || $height > 640) {
4181 $Image->scaleDown(640);
4182 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4184 logger("photo upload: image upload with scale 1 (640x640) failed");
4188 if ($width > 320 || $height > 320) {
4189 $Image->scaleDown(320);
4190 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4192 logger("photo upload: image upload with scale 2 (320x320) failed");
4195 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4196 } elseif ($mediatype == "profileimage") {
4197 // upload profile image (scales 4, 5, 6)
4198 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4200 if ($width > 175 || $height > 175) {
4201 $Image->scaleDown(175);
4202 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4204 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4208 if ($width > 80 || $height > 80) {
4209 $Image->scaleDown(80);
4210 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4212 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4216 if ($width > 48 || $height > 48) {
4217 $Image->scaleDown(48);
4218 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4220 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4223 $Image->__destruct();
4224 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4228 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4229 if ($photo_id == null && $mediatype == "photo") {
4230 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4232 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4233 return prepare_photo_data($type, false, $hash);
4235 throw new InternalServerErrorException("image upload failed");
4239 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4241 // get data about the api authenticated user
4242 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4243 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4246 $arr['guid'] = get_guid(32);
4247 $arr['uid'] = intval(api_user());
4249 $arr['parent-uri'] = $uri;
4250 $arr['type'] = 'photo';
4252 $arr['resource-id'] = $hash;
4253 $arr['contact-id'] = $owner_record[0]['id'];
4254 $arr['owner-name'] = $owner_record[0]['name'];
4255 $arr['owner-link'] = $owner_record[0]['url'];
4256 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4257 $arr['author-name'] = $owner_record[0]['name'];
4258 $arr['author-link'] = $owner_record[0]['url'];
4259 $arr['author-avatar'] = $owner_record[0]['thumb'];
4261 $arr['allow_cid'] = $allow_cid;
4262 $arr['allow_gid'] = $allow_gid;
4263 $arr['deny_cid'] = $deny_cid;
4264 $arr['deny_gid'] = $deny_gid;
4265 $arr['last-child'] = 1;
4266 $arr['visible'] = $visibility;
4270 'image/jpeg' => 'jpg',
4271 'image/png' => 'png',
4272 'image/gif' => 'gif'
4275 // adds link to the thumbnail scale photo
4276 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4277 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4280 // do the magic for storing the item in the database and trigger the federation to other contacts
4284 function prepare_photo_data($type, $scale, $photo_id)
4286 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4287 $data_sql = ($scale === false ? "" : "data, ");
4289 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4290 // clients needs to convert this in their way for further processing
4292 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4293 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4294 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4295 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4297 intval(local_user()),
4303 'image/jpeg' => 'jpg',
4304 'image/png' => 'png',
4305 'image/gif' => 'gif'
4308 // prepare output data for photo
4309 if (DBM::is_result($r)) {
4310 $data = array('photo' => $r[0]);
4311 $data['photo']['id'] = $data['photo']['resource-id'];
4312 if ($scale !== false) {
4313 $data['photo']['data'] = base64_encode($data['photo']['data']);
4315 unset($data['photo']['datasize']); //needed only with scale param
4317 if ($type == "xml") {
4318 $data['photo']['links'] = array();
4319 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4320 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4322 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4325 $data['photo']['link'] = array();
4326 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4328 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4329 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4333 unset($data['photo']['resource-id']);
4334 unset($data['photo']['minscale']);
4335 unset($data['photo']['maxscale']);
4337 throw new NotFoundException();
4340 // retrieve item element for getting activities (like, dislike etc.) related to photo
4342 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4343 intval(local_user()),
4346 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4348 // retrieve comments on photo
4350 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4351 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4352 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4353 `contact`.`id` AS `cid`
4355 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4356 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4357 WHERE `item`.`parent` = %d AND `item`.`visible`
4358 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4359 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4360 intval($item[0]['parent']),
4362 dbesc(ACTIVITY_POST)
4365 // prepare output of comments
4366 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4367 $comments = array();
4368 if ($type == "xml") {
4370 foreach ($commentData as $comment) {
4371 $comments[$k++ . ":comment"] = $comment;
4374 foreach ($commentData as $comment) {
4375 $comments[] = $comment;
4378 $data['photo']['friendica_comments'] = $comments;
4380 // include info if rights on photo and rights on item are mismatching
4381 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4382 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4383 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4384 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4385 $data['photo']['rights_mismatch'] = $rights_mismatch;
4392 * Similar as /mod/redir.php
4393 * redirect to 'url' after dfrn auth
4395 * Why this when there is mod/redir.php already?
4396 * This use api_user() and api_login()
4399 * c_url: url of remote contact to auth to
4400 * url: string, url to redirect after auth
4402 function api_friendica_remoteauth()
4404 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4405 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4407 if ($url === '' || $c_url === '') {
4408 throw new BadRequestException("Wrong parameters.");
4411 $c_url = normalise_link($c_url);
4416 "SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4421 if ((! DBM::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4422 throw new BadRequestException("Unknown contact");
4427 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4429 if ($r[0]['duplex'] && $r[0]['issued-id']) {
4430 $orig_id = $r[0]['issued-id'];
4431 $dfrn_id = '1:' . $orig_id;
4433 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4434 $orig_id = $r[0]['dfrn-id'];
4435 $dfrn_id = '0:' . $orig_id;
4438 $sec = random_string();
4441 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4442 VALUES( %d, %s, '%s', '%s', %d )",
4450 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4451 $dest = (($url) ? '&destination_url=' . $url : '');
4453 $r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4454 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4455 . '&type=profile&sec=' . $sec . $dest . $quiet
4458 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4461 * @brief Return the item shared, if the item contains only the [share] tag
4463 * @param array $item Sharer item
4464 * @return array Shared item or false if not a reshare
4466 function api_share_as_retweet(&$item)
4468 $body = trim($item["body"]);
4470 if (Diaspora::isReshare($body, false)===false) {
4474 /// @TODO "$1" should maybe mean '$1' ?
4475 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4477 * Skip if there is no shared message in there
4478 * we already checked this in diaspora::isReshare()
4479 * but better one more than one less...
4481 if ($body == $attributes) {
4486 // build the fake reshared item
4487 $reshared_item = $item;
4490 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4491 if ($matches[1] != "") {
4492 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4495 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4496 if ($matches[1] != "") {
4497 $author = $matches[1];
4501 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4502 if ($matches[1] != "") {
4503 $profile = $matches[1];
4506 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4507 if ($matches[1] != "") {
4508 $profile = $matches[1];
4512 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4513 if ($matches[1] != "") {
4514 $avatar = $matches[1];
4517 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4518 if ($matches[1] != "") {
4519 $avatar = $matches[1];
4523 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4524 if ($matches[1] != "") {
4525 $link = $matches[1];
4528 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4529 if ($matches[1] != "") {
4530 $link = $matches[1];
4534 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4535 if ($matches[1] != "")
4536 $posted = $matches[1];
4538 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4539 if ($matches[1] != "") {
4540 $posted = $matches[1];
4543 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4545 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4549 $reshared_item["body"] = $shared_body;
4550 $reshared_item["author-name"] = $author;
4551 $reshared_item["author-link"] = $profile;
4552 $reshared_item["author-avatar"] = $avatar;
4553 $reshared_item["plink"] = $link;
4554 $reshared_item["created"] = $posted;
4555 $reshared_item["edited"] = $posted;
4557 return $reshared_item;
4561 function api_get_nick($profile)
4564 - remove trailing junk from profile url
4565 - pump.io check has to check the website
4571 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4572 dbesc(normalise_link($profile))
4575 if (DBM::is_result($r)) {
4576 $nick = $r[0]["nick"];
4581 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4582 dbesc(normalise_link($profile))
4585 if (DBM::is_result($r)) {
4586 $nick = $r[0]["nick"];
4591 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4592 if ($friendica != $profile) {
4598 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4599 if ($diaspora != $profile) {
4605 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4606 if ($twitter != $profile) {
4613 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4614 if ($StatusnetHost != $profile) {
4615 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4616 if ($StatusnetUser != $profile) {
4617 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4618 $user = json_decode($UserData);
4620 $nick = $user->screen_name;
4626 // To-Do: look at the page if its really a pumpio site
4627 //if (!$nick == "") {
4628 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4629 // if ($pumpio != $profile)
4631 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4642 function api_in_reply_to($item)
4644 $in_reply_to = array();
4646 $in_reply_to['status_id'] = null;
4647 $in_reply_to['user_id'] = null;
4648 $in_reply_to['status_id_str'] = null;
4649 $in_reply_to['user_id_str'] = null;
4650 $in_reply_to['screen_name'] = null;
4652 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4653 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4654 intval($item['uid']),
4655 dbesc($item['thr-parent']));
4657 if (DBM::is_result($r)) {
4658 $in_reply_to['status_id'] = intval($r[0]['id']);
4660 $in_reply_to['status_id'] = intval($item['parent']);
4663 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4665 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4666 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4667 WHERE `item`.`id` = %d LIMIT 1",
4668 intval($in_reply_to['status_id'])
4671 if (DBM::is_result($r)) {
4672 if ($r[0]['nick'] == "") {
4673 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4676 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4677 $in_reply_to['user_id'] = intval($r[0]['id']);
4678 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4681 // There seems to be situation, where both fields are identical:
4682 // https://github.com/friendica/friendica/issues/1010
4683 // This is a bugfix for that.
4684 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4685 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4686 $in_reply_to['status_id'] = null;
4687 $in_reply_to['user_id'] = null;
4688 $in_reply_to['status_id_str'] = null;
4689 $in_reply_to['user_id_str'] = null;
4690 $in_reply_to['screen_name'] = null;
4694 return $in_reply_to;
4697 function api_clean_plain_items($Text)
4699 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4701 $Text = bb_CleanPictureLinks($Text);
4702 $URLSearchString = "^\[\]";
4704 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
4706 if ($include_entities == "true") {
4707 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
4710 // Simplify "attachment" element
4711 $Text = api_clean_attachments($Text);
4717 * @brief Removes most sharing information for API text export
4719 * @param string $body The original body
4721 * @return string Cleaned body
4723 function api_clean_attachments($body)
4725 $data = get_attachment_data($body);
4732 if (isset($data["text"]))
4733 $body = $data["text"];
4735 if (($body == "") && (isset($data["title"])))
4736 $body = $data["title"];
4738 if (isset($data["url"]))
4739 $body .= "\n".$data["url"];
4741 $body .= $data["after"];
4746 function api_best_nickname(&$contacts)
4748 $best_contact = array();
4750 if (count($contact) == 0)
4753 foreach ($contacts as $contact)
4754 if ($contact["network"] == "") {
4755 $contact["network"] = "dfrn";
4756 $best_contact = array($contact);
4759 if (sizeof($best_contact) == 0)
4760 foreach ($contacts as $contact)
4761 if ($contact["network"] == "dfrn")
4762 $best_contact = array($contact);
4764 if (sizeof($best_contact) == 0)
4765 foreach ($contacts as $contact)
4766 if ($contact["network"] == "dspr")
4767 $best_contact = array($contact);
4769 if (sizeof($best_contact) == 0)
4770 foreach ($contacts as $contact)
4771 if ($contact["network"] == "stat")
4772 $best_contact = array($contact);
4774 if (sizeof($best_contact) == 0)
4775 foreach ($contacts as $contact)
4776 if ($contact["network"] == "pump")
4777 $best_contact = array($contact);
4779 if (sizeof($best_contact) == 0)
4780 foreach ($contacts as $contact)
4781 if ($contact["network"] == "twit")
4782 $best_contact = array($contact);
4784 if (sizeof($best_contact) == 1) {
4785 $contacts = $best_contact;
4787 $contacts = array($contacts[0]);
4791 // return all or a specified group of the user with the containing contacts
4792 function api_friendica_group_show($type)
4796 if (api_user() === false) throw new ForbiddenException();
4799 $user_info = api_get_user($a);
4800 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4801 $uid = $user_info['uid'];
4803 // get data of the specified group id or all groups if not specified
4806 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4810 // error message if specified gid is not in database
4811 if (!DBM::is_result($r))
4812 throw new BadRequestException("gid not available");
4815 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4820 // loop through all groups and retrieve all members for adding data in the user array
4821 foreach ($r as $rr) {
4822 $members = Contact::getByGroupId($rr['id']);
4825 if ($type == "xml") {
4826 $user_element = "users";
4828 foreach ($members as $member) {
4829 $user = api_get_user($a, $member['nurl']);
4830 $users[$k++.":user"] = $user;
4833 $user_element = "user";
4834 foreach ($members as $member) {
4835 $user = api_get_user($a, $member['nurl']);
4839 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4841 return api_format_data("groups", $type, array('group' => $grps));
4843 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4846 // delete the specified group of the user
4847 function api_friendica_group_delete($type)
4851 if (api_user() === false) {
4852 throw new ForbiddenException();
4856 $user_info = api_get_user($a);
4857 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4858 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4859 $uid = $user_info['uid'];
4861 // error if no gid specified
4862 if ($gid == 0 || $name == "") {
4863 throw new BadRequestException('gid or name not specified');
4866 // get data of the specified group id
4868 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
4872 // error message if specified gid is not in database
4873 if (!DBM::is_result($r)) {
4874 throw new BadRequestException('gid not available');
4877 // get data of the specified group id and group name
4879 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
4884 // error message if specified gid is not in database
4885 if (!DBM::is_result($rname)) {
4886 throw new BadRequestException('wrong group name');
4890 $ret = Group::removeByName($uid, $name);
4893 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
4894 return api_format_data("group_delete", $type, array('result' => $success));
4896 throw new BadRequestException('other API error');
4899 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4902 // create the specified group with the posted array of contacts
4903 function api_friendica_group_create($type)
4907 if (api_user() === false) throw new ForbiddenException();
4910 $user_info = api_get_user($a);
4911 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4912 $uid = $user_info['uid'];
4913 $json = json_decode($_POST['json'], true);
4914 $users = $json['user'];
4916 // error if no name specified
4918 throw new BadRequestException('group name not specified');
4920 // get data of the specified group name
4922 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
4926 // error message if specified group name already exists
4927 if (DBM::is_result($rname))
4928 throw new BadRequestException('group name already exists');
4930 // check if specified group name is a deleted group
4932 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
4936 // error message if specified group name already exists
4937 if (DBM::is_result($rname))
4938 $reactivate_group = true;
4941 $ret = Group::create($uid, $name);
4943 $gid = Group::getIdByName($uid, $name);
4945 throw new BadRequestException('other API error');
4949 $erroraddinguser = false;
4950 $errorusers = array();
4951 foreach ($users as $user) {
4952 $cid = $user['cid'];
4953 // check if user really exists as contact
4955 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4959 if (count($contact))
4960 $result = Group::addMember($gid, $cid);
4962 $erroraddinguser = true;
4963 $errorusers[] = $cid;
4967 // return success message incl. missing users in array
4968 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
4969 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4970 return api_format_data("group_create", $type, array('result' => $success));
4972 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4975 // update the specified group with the posted array of contacts
4976 function api_friendica_group_update($type)
4980 if (api_user() === false) throw new ForbiddenException();
4983 $user_info = api_get_user($a);
4984 $uid = $user_info['uid'];
4985 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4986 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4987 $json = json_decode($_POST['json'], true);
4988 $users = $json['user'];
4990 // error if no name specified
4992 throw new BadRequestException('group name not specified');
4994 // error if no gid specified
4996 throw new BadRequestException('gid not specified');
4999 $members = Contact::getByGroupId($gid);
5000 foreach ($members as $member) {
5001 $cid = $member['id'];
5002 foreach ($users as $user) {
5003 $found = ($user['cid'] == $cid ? true : false);
5006 $ret = Group::removeMemberByName($uid, $name, $cid);
5011 $erroraddinguser = false;
5012 $errorusers = array();
5013 foreach ($users as $user) {
5014 $cid = $user['cid'];
5015 // check if user really exists as contact
5017 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5022 if (count($contact)) {
5023 $result = Group::addMember($gid, $cid);
5025 $erroraddinguser = true;
5026 $errorusers[] = $cid;
5030 // return success message incl. missing users in array
5031 $status = ($erroraddinguser ? "missing user" : "ok");
5032 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
5033 return api_format_data("group_update", $type, array('result' => $success));
5036 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5038 function api_friendica_activity($type)
5042 if (api_user() === false) throw new ForbiddenException();
5043 $verb = strtolower($a->argv[3]);
5044 $verb = preg_replace("|\..*$|", "", $verb);
5046 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5048 $res = do_like($id, $verb);
5051 if ($type == "xml") {
5056 return api_format_data('ok', $type, array('ok' => $ok));
5058 throw new BadRequestException('Error adding activity');
5062 /// @TODO move to top of file or somwhere better
5063 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5064 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5065 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5066 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5067 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5068 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5069 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5070 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5071 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5072 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5075 * @brief Returns notifications
5077 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5080 function api_friendica_notification($type)
5084 if (api_user() === false) throw new ForbiddenException();
5085 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
5086 $nm = new NotificationsManager();
5088 $notes = $nm->getAll(array(), "+seen -date", 50);
5090 if ($type == "xml") {
5091 $xmlnotes = array();
5092 foreach ($notes as $note)
5093 $xmlnotes[] = array("@attributes" => $note);
5098 return api_format_data("notes", $type, array('note' => $notes));
5102 * @brief Set notification as seen and returns associated item (if possible)
5104 * POST request with 'id' param as notification id
5106 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5109 function api_friendica_notification_seen($type)
5113 if (api_user() === false) throw new ForbiddenException();
5114 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
5116 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5118 $nm = new NotificationsManager();
5119 $note = $nm->getByID($id);
5120 if (is_null($note)) throw new BadRequestException("Invalid argument");
5122 $nm->setSeen($note);
5123 if ($note['otype']=='item') {
5124 // would be really better with an ItemsManager and $im->getByID() :-P
5126 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5127 intval($note['iid']),
5128 intval(local_user())
5131 // we found the item, return it to the user
5132 $user_info = api_get_user($a);
5133 $ret = api_format_items($r, $user_info, false, $type);
5134 $data = array('status' => $ret);
5135 return api_format_data("status", $type, $data);
5137 // the item can't be found, but we set the note as seen, so we count this as a success
5139 return api_format_data('result', $type, array('result' => "success"));
5142 /// @TODO move to top of file or somwhere better
5143 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5144 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5147 * @brief update a direct_message to seen state
5149 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5150 * @return string (success result=ok, error result=error with error message)
5152 function api_friendica_direct_messages_setseen($type)
5155 if (api_user() === false) {
5156 throw new ForbiddenException();
5160 $user_info = api_get_user($a);
5161 $uid = $user_info['uid'];
5162 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5164 // return error if id is zero
5166 $answer = array('result' => 'error', 'message' => 'message id not specified');
5167 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5170 // get data of the specified message id
5172 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5177 // error message if specified id is not in database
5178 if (!DBM::is_result($r)) {
5179 $answer = array('result' => 'error', 'message' => 'message id not in database');
5180 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5183 // update seen indicator
5185 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5192 $answer = array('result' => 'ok', 'message' => 'message set to seen');
5193 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
5195 $answer = array('result' => 'error', 'message' => 'unknown error');
5196 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5200 /// @TODO move to top of file or somwhere better
5201 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5204 * @brief search for direct_messages containing a searchstring through api
5206 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5207 * @return string (success: success=true if found and search_result contains found messages
5208 * success=false if nothing was found, search_result='nothing found',
5209 * error: result=error with error message)
5211 function api_friendica_direct_messages_search($type)
5215 if (api_user() === false) {
5216 throw new ForbiddenException();
5220 $user_info = api_get_user($a);
5221 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5222 $uid = $user_info['uid'];
5224 // error if no searchstring specified
5225 if ($searchstring == "") {
5226 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
5227 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
5230 // get data for the specified searchstring
5232 "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",
5234 dbesc('%'.$searchstring.'%')
5237 $profile_url = $user_info["url"];
5239 // message if nothing was found
5240 if (!DBM::is_result($r)) {
5241 $success = array('success' => false, 'search_results' => 'problem with query');
5242 } elseif (count($r) == 0) {
5243 $success = array('success' => false, 'search_results' => 'nothing found');
5246 foreach ($r as $item) {
5247 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5248 $recipient = $user_info;
5249 $sender = api_get_user($a, normalise_link($item['contact-url']));
5250 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5251 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5252 $sender = $user_info;
5255 $ret[] = api_format_messages($item, $recipient, $sender);
5257 $success = array('success' => true, 'search_results' => $ret);
5260 return api_format_data("direct_message_search", $type, array('$result' => $success));
5263 /// @TODO move to top of file or somwhere better
5264 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5267 * @brief return data of all the profiles a user has to the client
5269 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5272 function api_friendica_profile_show($type)
5276 if (api_user() === false) {
5277 throw new ForbiddenException();
5281 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5283 // retrieve general information about profiles for user
5284 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5285 $directory = Config::get('system', 'directory');
5287 // get data of the specified profile id or all profiles of the user if not specified
5288 if ($profileid != 0) {
5290 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5295 // error message if specified gid is not in database
5296 if (!DBM::is_result($r)) {
5297 throw new BadRequestException("profile_id not available");
5301 "SELECT * FROM `profile` WHERE `uid` = %d",
5305 // loop through all returned profiles and retrieve data and users
5307 foreach ($r as $rr) {
5308 $profile = api_format_items_profiles($rr, $type);
5310 // select all users from contact table, loop and prepare standard return for user data
5313 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5315 intval($rr['profile_id'])
5318 foreach ($r as $rr) {
5319 $user = api_get_user($a, $rr['nurl']);
5320 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5322 $profile['users'] = $users;
5324 // add prepared profile data to array for final return
5325 if ($type == "xml") {
5326 $profiles[$k++ . ":profile"] = $profile;
5328 $profiles[] = $profile;
5332 // return settings, authenticated user and profiles data
5333 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5335 $result = array('multi_profiles' => $multi_profiles ? true : false,
5336 'global_dir' => $directory,
5337 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5338 'profiles' => $profiles);
5339 return api_format_data("friendica_profiles", $type, array('$result' => $result));
5341 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5344 @TODO Maybe open to implement?
5346 [pagename] => api/1.1/statuses/lookup.json
5347 [id] => 605138389168451584
5348 [include_cards] => true
5349 [cards_platform] => Android-12
5350 [include_entities] => true
5351 [include_my_retweet] => 1
5353 [include_reply_count] => true
5354 [include_descendent_reply_count] => true
5358 Not implemented by now:
5359 statuses/retweets_of_me
5364 account/update_location
5365 account/update_profile_background_image
5368 friendica/profile/update
5369 friendica/profile/create
5370 friendica/profile/delete
5372 Not implemented in status.net:
5373 statuses/retweeted_to_me
5374 statuses/retweeted_by_me
5375 direct_messages/destroy
5377 account/update_delivery_device
5378 notifications/follow