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\Worker;
14 use Friendica\Database\DBM;
15 use Friendica\Model\Contact;
16 use Friendica\Model\Group;
17 use Friendica\Model\Photo;
18 use Friendica\Model\User;
19 use Friendica\Network\FKOAuth1;
20 use Friendica\Network\HTTPException;
21 use Friendica\Network\HTTPException\BadRequestException;
22 use Friendica\Network\HTTPException\ForbiddenException;
23 use Friendica\Network\HTTPException\InternalServerErrorException;
24 use Friendica\Network\HTTPException\MethodNotAllowedException;
25 use Friendica\Network\HTTPException\NotFoundException;
26 use Friendica\Network\HTTPException\NotImplementedException;
27 use Friendica\Network\HTTPException\UnauthorizedException;
28 use Friendica\Network\HTTPException\TooManyRequestsException;
29 use Friendica\Object\Image;
30 use Friendica\Protocol\Diaspora;
31 use Friendica\Util\XML;
33 require_once 'include/bbcode.php';
34 require_once 'include/datetime.php';
35 require_once 'include/conversation.php';
36 require_once 'include/html2plain.php';
37 require_once 'mod/share.php';
38 require_once 'mod/item.php';
39 require_once 'include/security.php';
40 require_once 'include/contact_selectors.php';
41 require_once 'include/html2bbcode.php';
42 require_once 'mod/wall_upload.php';
43 require_once 'mod/proxy.php';
44 require_once 'include/message.php';
45 require_once 'include/like.php';
46 require_once 'include/plaintext.php';
48 define('API_METHOD_ANY', '*');
49 define('API_METHOD_GET', 'GET');
50 define('API_METHOD_POST', 'POST,PUT');
51 define('API_METHOD_DELETE', 'POST,DELETE');
57 * @brief Auth API user
59 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
60 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
61 * into a page, and visitors will post something without noticing it).
65 if (x($_SESSION, 'allow_api')) {
73 * @brief Get source name from API client
75 * Clients can send 'source' parameter to be show in post metadata
76 * as "sent via <source>".
77 * Some clients doesn't send a source param, we support ones we know
81 * Client source name, default to "api" if unset/unknown
85 if (requestdata('source')) {
86 return requestdata('source');
89 // Support for known clients that doesn't send a source name
90 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
94 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
100 * @brief Format date for API
102 * @param string $str Source date, as UTC
103 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
105 function api_date($str)
107 // Wed May 23 06:01:13 +0000 2007
108 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y");
112 * @brief Register API endpoint
114 * Register a function to be the endpont for defined API path.
116 * @param string $path API URL path, relative to System::baseUrl()
117 * @param string $func Function name to call on path request
118 * @param bool $auth API need logged user
119 * @param string $method HTTP method reqiured to call this endpoint.
120 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
121 * Default to API_METHOD_ANY
123 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
133 // Workaround for hotot
134 $path = str_replace("api/", "api/1.1/", $path);
144 * @brief Login API user
146 * Log in user via OAuth1 or Simple HTTP Auth.
147 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
149 * @param object $a App
150 * @hook 'authenticate'
152 * 'username' => username from login form
153 * 'password' => password from login form
154 * 'authenticated' => return status,
155 * 'user_record' => return authenticated user record
157 * array $user logged user record
159 function api_login(App $a)
161 $oauth1 = new FKOAuth1();
164 list($consumer, $token) = $oauth1->verify_request(OAuthRequest::from_request());
165 if (!is_null($token)) {
166 $oauth1->loginUser($token->uid);
167 call_hooks('logged_in', $a->user);
170 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
171 var_dump($consumer, $token);
173 } catch (Exception $e) {
177 // workaround for HTTP-auth in CGI mode
178 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
179 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
180 if (strlen($userpass)) {
181 list($name, $password) = explode(':', $userpass);
182 $_SERVER['PHP_AUTH_USER'] = $name;
183 $_SERVER['PHP_AUTH_PW'] = $password;
187 if (!x($_SERVER, 'PHP_AUTH_USER')) {
188 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
189 header('WWW-Authenticate: Basic realm="Friendica"');
190 throw new UnauthorizedException("This API requires login");
193 $user = $_SERVER['PHP_AUTH_USER'];
194 $password = $_SERVER['PHP_AUTH_PW'];
196 // allow "user@server" login (but ignore 'server' part)
197 $at = strstr($user, "@", true);
202 // next code from mod/auth.php. needs better solution
206 'username' => trim($user),
207 'password' => trim($password),
208 'authenticated' => 0,
209 'user_record' => null,
213 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
214 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
215 * and later plugins should not interfere with an earlier one that succeeded.
217 call_hooks('authenticate', $addon_auth);
219 if (($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
220 $record = $addon_auth['user_record'];
222 $user_id = User::authenticate(trim($user), trim($password));
224 $record = dba::select('user', [], ['uid' => $user_id], ['limit' => 1]);
228 if ((! $record) || (! count($record))) {
229 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
230 header('WWW-Authenticate: Basic realm="Friendica"');
231 //header('HTTP/1.0 401 Unauthorized');
232 //die('This api requires login');
233 throw new UnauthorizedException("This API requires login");
236 authenticate_success($record);
238 $_SESSION["allow_api"] = true;
240 call_hooks('logged_in', $a->user);
244 * @brief Check HTTP method of called API
246 * API endpoints can define which HTTP method to accept when called.
247 * This function check the current HTTP method agains endpoint
250 * @param string $method Required methods, uppercase, separated by comma
253 function api_check_method($method)
255 if ($method == "*") {
258 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
262 * @brief Main API entry point
264 * Authenticate user, call registered API function, set HTTP headers
266 * @param object $a App
267 * @return string API call result
269 function api_call(App $a)
271 global $API, $called_api;
274 if (strpos($a->query_string, ".xml") > 0) {
277 if (strpos($a->query_string, ".json") > 0) {
280 if (strpos($a->query_string, ".rss") > 0) {
283 if (strpos($a->query_string, ".atom") > 0) {
288 foreach ($API as $p => $info) {
289 if (strpos($a->query_string, $p) === 0) {
290 if (!api_check_method($info['method'])) {
291 throw new MethodNotAllowedException();
294 $called_api = explode("/", $p);
295 //unset($_SERVER['PHP_AUTH_USER']);
297 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
298 if ($info['auth'] === true && api_user() === false) {
302 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
303 logger('API parameters: ' . print_r($_REQUEST, true));
305 $stamp = microtime(true);
306 $r = call_user_func($info['func'], $type);
307 $duration = (float) (microtime(true) - $stamp);
308 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
310 if (Config::get("system", "profiler")) {
311 $duration = microtime(true)-$a->performance["start"];
313 /// @TODO round() really everywhere?
315 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
316 "Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
317 round($a->performance["database"] - $a->performance["database_write"], 3),
318 round($a->performance["database_write"], 3),
319 round($a->performance["network"], 2),
320 round($a->performance["file"], 2),
321 round($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
327 if (Config::get("rendertime", "callstack")) {
328 $o = "Database Read:\n";
329 foreach ($a->callstack["database"] as $func => $time) {
330 $time = round($time, 3);
332 $o .= $func . ": " . $time . "\n";
335 $o .= "\nDatabase Write:\n";
336 foreach ($a->callstack["database_write"] as $func => $time) {
337 $time = round($time, 3);
339 $o .= $func . ": " . $time . "\n";
343 $o .= "\nNetwork:\n";
344 foreach ($a->callstack["network"] as $func => $time) {
345 $time = round($time, 3);
347 $o .= $func . ": " . $time . "\n";
350 logger($o, LOGGER_DEBUG);
356 * api function returned false withour throw an
357 * exception. This should not happend, throw a 500
359 throw new InternalServerErrorException();
364 header("Content-Type: text/xml");
368 header("Content-Type: application/json");
370 $json = json_encode($rr);
371 if (x($_GET, 'callback')) {
372 $json = $_GET['callback'] . "(" . $json . ")";
377 header("Content-Type: application/rss+xml");
378 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
381 header("Content-Type: application/atom+xml");
382 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
388 logger('API call not implemented: ' . $a->query_string);
389 throw new NotImplementedException();
390 } catch (HTTPException $e) {
391 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
392 return api_error($type, $e);
397 * @brief Format API error string
399 * @param string $type Return type (xml, json, rss, as)
400 * @param object $e HTTPException Error object
401 * @return strin error message formatted as $type
403 function api_error($type, $e)
407 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
408 /// @TODO: https://dev.twitter.com/overview/api/response-codes
410 $error = array("error" => $error,
411 "code" => $e->httpcode . " " . $e->httpdesc,
412 "request" => $a->query_string);
414 $ret = api_format_data('status', $type, array('status' => $error));
418 header("Content-Type: text/xml");
422 header("Content-Type: application/json");
423 return json_encode($ret);
426 header("Content-Type: application/rss+xml");
430 header("Content-Type: application/atom+xml");
437 * @brief Set values for RSS template
440 * @param array $arr Array to be passed to template
441 * @param array $user_info User info
443 * @todo find proper type-hints
445 function api_rss_extra(App $a, $arr, $user_info)
447 if (is_null($user_info)) {
448 $user_info = api_get_user($a);
451 $arr['$user'] = $user_info;
452 $arr['$rss'] = array(
453 'alternate' => $user_info['url'],
454 'self' => System::baseUrl() . "/" . $a->query_string,
455 'base' => System::baseUrl(),
456 'updated' => api_date(null),
457 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
458 'language' => $user_info['language'],
459 'logo' => System::baseUrl() . "/images/friendica-32.png",
467 * @brief Unique contact to contact url.
469 * @param int $id Contact id
470 * @return bool|string
471 * Contact url or False if contact id is unknown
473 function api_unique_id_to_nurl($id)
475 $r = dba::select('contact', array('nurl'), array('uid' => 0, 'id' => $id), array('limit' => 1));
477 if (DBM::is_result($r)) {
485 * @brief Get user info array.
487 * @param object $a App
488 * @param int|string $contact_id Contact ID or URL
490 function api_get_user(App $a, $contact_id = null)
499 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
501 // Searching for contact URL
502 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
503 $user = dbesc(normalise_link($contact_id));
505 $extra_query = "AND `contact`.`nurl` = '%s' ";
506 if (api_user() !== false) {
507 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
511 // Searching for contact id with uid = 0
512 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
513 $user = dbesc(api_unique_id_to_nurl($contact_id));
516 throw new BadRequestException("User not found.");
520 $extra_query = "AND `contact`.`nurl` = '%s' ";
521 if (api_user() !== false) {
522 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
526 if (is_null($user) && x($_GET, 'user_id')) {
527 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
530 throw new BadRequestException("User not found.");
534 $extra_query = "AND `contact`.`nurl` = '%s' ";
535 if (api_user() !== false) {
536 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
539 if (is_null($user) && x($_GET, 'screen_name')) {
540 $user = dbesc($_GET['screen_name']);
542 $extra_query = "AND `contact`.`nick` = '%s' ";
543 if (api_user() !== false) {
544 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
548 if (is_null($user) && x($_GET, 'profileurl')) {
549 $user = dbesc(normalise_link($_GET['profileurl']));
551 $extra_query = "AND `contact`.`nurl` = '%s' ";
552 if (api_user() !== false) {
553 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
557 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
558 $argid = count($called_api);
559 list($user, $null) = explode(".", $a->argv[$argid]);
560 if (is_numeric($user)) {
561 $user = dbesc(api_unique_id_to_nurl($user));
568 $extra_query = "AND `contact`.`nurl` = '%s' ";
569 if (api_user() !== false) {
570 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
573 $user = dbesc($user);
575 $extra_query = "AND `contact`.`nick` = '%s' ";
576 if (api_user() !== false) {
577 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
582 logger("api_get_user: user ".$user, LOGGER_DEBUG);
585 if (api_user() === false) {
589 $user = $_SESSION['uid'];
590 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
594 logger('api_user: ' . $extra_query . ', user: ' . $user);
598 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
604 // Selecting the id by priority, friendica first
605 api_best_nickname($uinfo);
607 // if the contact wasn't found, fetch it from the contacts with uid = 0
608 if (!DBM::is_result($uinfo)) {
612 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
615 if (DBM::is_result($r)) {
616 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
618 // If no nick where given, extract it from the address
619 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
620 $r[0]['nick'] = api_get_nick($r[0]["url"]);
625 'id_str' => (string) $r[0]["id"],
626 'name' => $r[0]["name"],
627 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
628 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
629 'description' => $r[0]["about"],
630 'profile_image_url' => $r[0]["micro"],
631 'profile_image_url_https' => $r[0]["micro"],
632 'url' => $r[0]["url"],
633 'protected' => false,
634 'followers_count' => 0,
635 'friends_count' => 0,
637 'created_at' => api_date($r[0]["created"]),
638 'favourites_count' => 0,
640 'time_zone' => 'UTC',
641 'geo_enabled' => false,
643 'statuses_count' => 0,
645 'contributors_enabled' => false,
646 'is_translator' => false,
647 'is_translation_enabled' => false,
648 'following' => false,
649 'follow_request_sent' => false,
650 'statusnet_blocking' => false,
651 'notifications' => false,
652 'statusnet_profile_url' => $r[0]["url"],
654 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
656 'network' => $r[0]["network"],
661 throw new BadRequestException("User not found.");
665 if ($uinfo[0]['self']) {
666 if ($uinfo[0]['network'] == "") {
667 $uinfo[0]['network'] = NETWORK_DFRN;
671 "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
675 "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
679 /// @TODO old-lost code? (twice)
680 // Counting is deactivated by now, due to performance issues
681 // count public wall messages
682 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
683 // intval($uinfo[0]['uid'])
685 //$countitms = $r[0]['count'];
688 // Counting is deactivated by now, due to performance issues
689 //$r = q("SELECT count(*) as `count` FROM `item`
690 // WHERE `contact-id` = %d",
691 // intval($uinfo[0]['id'])
693 //$countitms = $r[0]['count'];
697 /// @TODO old-lost code? (twice)
699 // Counting is deactivated by now, due to performance issues
701 $r = q("SELECT count(*) as `count` FROM `contact`
702 WHERE `uid` = %d AND `rel` IN ( %d, %d )
703 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
704 intval($uinfo[0]['uid']),
705 intval(CONTACT_IS_SHARING),
706 intval(CONTACT_IS_FRIEND)
708 $countfriends = $r[0]['count'];
710 $r = q("SELECT count(*) as `count` FROM `contact`
711 WHERE `uid` = %d AND `rel` IN ( %d, %d )
712 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
713 intval($uinfo[0]['uid']),
714 intval(CONTACT_IS_FOLLOWER),
715 intval(CONTACT_IS_FRIEND)
717 $countfollowers = $r[0]['count'];
719 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
720 intval($uinfo[0]['uid'])
722 $starred = $r[0]['count'];
725 if (! $uinfo[0]['self']) {
735 // Add a nick if it isn't present there
736 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
737 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
740 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
742 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
745 'id' => intval($pcontact_id),
746 'id_str' => (string) intval($pcontact_id),
747 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
748 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
749 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
750 'description' => (($profile) ? $profile[0]['pdesc'] : null),
751 'profile_image_url' => $uinfo[0]['micro'],
752 'profile_image_url_https' => $uinfo[0]['micro'],
753 'url' => $uinfo[0]['url'],
754 'protected' => false,
755 'followers_count' => intval($countfollowers),
756 'friends_count' => intval($countfriends),
758 'created_at' => api_date($uinfo[0]['created']),
759 'favourites_count' => intval($starred),
761 'time_zone' => 'UTC',
762 'geo_enabled' => false,
764 'statuses_count' => intval($countitms),
766 'contributors_enabled' => false,
767 'is_translator' => false,
768 'is_translation_enabled' => false,
769 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
770 'follow_request_sent' => false,
771 'statusnet_blocking' => false,
772 'notifications' => false,
774 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
775 'statusnet_profile_url' => $uinfo[0]['url'],
776 'uid' => intval($uinfo[0]['uid']),
777 'cid' => intval($uinfo[0]['cid']),
778 'self' => $uinfo[0]['self'],
779 'network' => $uinfo[0]['network'],
786 * @brief return api-formatted array for item's author and owner
788 * @param object $a App
789 * @param array $item item from db
790 * @return array(array:author, array:owner)
792 function api_item_get_user(App $a, $item)
794 $status_user = api_get_user($a, $item["author-link"]);
796 $status_user["protected"] = (($item["allow_cid"] != "") ||
797 ($item["allow_gid"] != "") ||
798 ($item["deny_cid"] != "") ||
799 ($item["deny_gid"] != "") ||
802 if ($item['thr-parent'] == $item['uri']) {
803 $owner_user = api_get_user($a, $item["owner-link"]);
805 $owner_user = $status_user;
808 return (array($status_user, $owner_user));
812 * @brief walks recursively through an array with the possibility to change value and key
814 * @param array $array The array to walk through
815 * @param string $callback The callback function
817 * @return array the transformed array
819 function api_walk_recursive(array &$array, callable $callback)
821 $new_array = array();
823 foreach ($array as $k => $v) {
825 if ($callback($v, $k)) {
826 $new_array[$k] = api_walk_recursive($v, $callback);
829 if ($callback($v, $k)) {
840 * @brief Callback function to transform the array in an array that can be transformed in a XML file
842 * @param mixed $item Array item value
843 * @param string $key Array key
845 * @return boolean Should the array item be deleted?
847 function api_reformat_xml(&$item, &$key)
849 if (is_bool($item)) {
850 $item = ($item ? "true" : "false");
853 if (substr($key, 0, 10) == "statusnet_") {
854 $key = "statusnet:".substr($key, 10);
855 } elseif (substr($key, 0, 10) == "friendica_") {
856 $key = "friendica:".substr($key, 10);
858 /// @TODO old-lost code?
860 // $key = "default:".$key;
866 * @brief Creates the XML from a JSON style array
868 * @param array $data JSON style array
869 * @param string $root_element Name of the root element
871 * @return string The XML data
873 function api_create_xml($data, $root_element)
875 $childname = key($data);
876 $data2 = array_pop($data);
879 $namespaces = array("" => "http://api.twitter.com",
880 "statusnet" => "http://status.net/schema/api/1/",
881 "friendica" => "http://friendi.ca/schema/api/1/",
882 "georss" => "http://www.georss.org/georss");
884 /// @todo Auto detection of needed namespaces
885 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
886 $namespaces = array();
889 if (is_array($data2)) {
890 api_walk_recursive($data2, "api_reformat_xml");
897 foreach ($data2 as $item) {
898 $data4[$i++.":".$childname] = $item;
904 $data3 = array($root_element => $data2);
906 $ret = XML::fromArray($data3, $xml, false, $namespaces);
911 * @brief Formats the data according to the data type
913 * @param string $root_element Name of the root element
914 * @param string $type Return type (atom, rss, xml, json)
915 * @param array $data JSON style array
917 * @return (string|object) XML data or JSON data
919 function api_format_data($root_element, $type, $data)
927 $ret = api_create_xml($data, $root_element);
942 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
943 * returns a 401 status code and an error message if not.
944 * http://developer.twitter.com/doc/get/account/verify_credentials
946 function api_account_verify_credentials($type)
951 if (api_user() === false) {
952 throw new ForbiddenException();
955 unset($_REQUEST["user_id"]);
956 unset($_GET["user_id"]);
958 unset($_REQUEST["screen_name"]);
959 unset($_GET["screen_name"]);
961 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
963 $user_info = api_get_user($a);
965 // "verified" isn't used here in the standard
966 unset($user_info["verified"]);
968 // - Adding last status
970 $user_info["status"] = api_status_show("raw");
971 if (!count($user_info["status"])) {
972 unset($user_info["status"]);
974 unset($user_info["status"]["user"]);
978 // "uid" and "self" are only needed for some internal stuff, so remove it from here
979 unset($user_info["uid"]);
980 unset($user_info["self"]);
982 return api_format_data("user", $type, array('user' => $user_info));
985 /// @TODO move to top of file or somwhere better
986 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
989 * Get data from $_POST or $_GET
991 function requestdata($k)
1002 /*Waitman Gobble Mod*/
1003 function api_statuses_mediap($type)
1007 if (api_user() === false) {
1008 logger('api_statuses_update: no user');
1009 throw new ForbiddenException();
1011 $user_info = api_get_user($a);
1013 $_REQUEST['type'] = 'wall';
1014 $_REQUEST['profile_uid'] = api_user();
1015 $_REQUEST['api_source'] = true;
1016 $txt = requestdata('status');
1017 /// @TODO old-lost code?
1018 //$txt = urldecode(requestdata('status'));
1020 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1021 $txt = html2bb_video($txt);
1022 $config = HTMLPurifier_Config::createDefault();
1023 $config->set('Cache.DefinitionImpl', null);
1024 $purifier = new HTMLPurifier($config);
1025 $txt = $purifier->purify($txt);
1027 $txt = html2bbcode($txt);
1029 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1031 // tell wall_upload function to return img info instead of echo
1032 $_REQUEST['hush'] = 'yeah';
1033 $bebop = wall_upload_post($a);
1035 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1036 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1039 // this should output the last post (the one we just posted).
1040 return api_status_show($type);
1043 /// @TODO move this to top of file or somewhere better!
1044 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1046 function api_statuses_update($type)
1051 if (api_user() === false) {
1052 logger('api_statuses_update: no user');
1053 throw new ForbiddenException();
1056 $user_info = api_get_user($a);
1058 // convert $_POST array items to the form we use for web posts.
1060 // logger('api_post: ' . print_r($_POST,true));
1062 if (requestdata('htmlstatus')) {
1063 $txt = requestdata('htmlstatus');
1064 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1065 $txt = html2bb_video($txt);
1067 $config = HTMLPurifier_Config::createDefault();
1068 $config->set('Cache.DefinitionImpl', null);
1070 $purifier = new HTMLPurifier($config);
1071 $txt = $purifier->purify($txt);
1073 $_REQUEST['body'] = html2bbcode($txt);
1076 $_REQUEST['body'] = requestdata('status');
1079 $_REQUEST['title'] = requestdata('title');
1081 $parent = requestdata('in_reply_to_status_id');
1083 // Twidere sends "-1" if it is no reply ...
1084 if ($parent == -1) {
1088 if (ctype_digit($parent)) {
1089 $_REQUEST['parent'] = $parent;
1091 $_REQUEST['parent_uri'] = $parent;
1094 if (requestdata('lat') && requestdata('long')) {
1095 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1097 $_REQUEST['profile_uid'] = api_user();
1100 $_REQUEST['type'] = 'net-comment';
1102 // Check for throttling (maximum posts per day, week and month)
1103 $throttle_day = Config::get('system', 'throttle_limit_day');
1104 if ($throttle_day > 0) {
1105 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1108 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1109 AND `created` > '%s' AND `id` = `parent`",
1114 if (DBM::is_result($r)) {
1115 $posts_day = $r[0]["posts_day"];
1120 if ($posts_day > $throttle_day) {
1121 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1122 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1123 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1127 $throttle_week = Config::get('system', 'throttle_limit_week');
1128 if ($throttle_week > 0) {
1129 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1132 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1133 AND `created` > '%s' AND `id` = `parent`",
1138 if (DBM::is_result($r)) {
1139 $posts_week = $r[0]["posts_week"];
1144 if ($posts_week > $throttle_week) {
1145 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1146 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1147 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1151 $throttle_month = Config::get('system', 'throttle_limit_month');
1152 if ($throttle_month > 0) {
1153 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1156 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1157 AND `created` > '%s' AND `id` = `parent`",
1162 if (DBM::is_result($r)) {
1163 $posts_month = $r[0]["posts_month"];
1168 if ($posts_month > $throttle_month) {
1169 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1170 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1171 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1175 $_REQUEST['type'] = 'wall';
1178 if (x($_FILES, 'media')) {
1179 // upload the image if we have one
1180 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1181 $media = wall_upload_post($a);
1182 if (strlen($media) > 0) {
1183 $_REQUEST['body'] .= "\n\n" . $media;
1187 // To-Do: Multiple IDs
1188 if (requestdata('media_ids')) {
1190 "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",
1191 intval(requestdata('media_ids')),
1194 if (DBM::is_result($r)) {
1195 $phototypes = Image::supportedTypes();
1196 $ext = $phototypes[$r[0]['type']];
1197 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1198 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1202 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1204 $_REQUEST['api_source'] = true;
1206 if (!x($_REQUEST, "source")) {
1207 $_REQUEST["source"] = api_source();
1210 // call out normal post function
1213 // this should output the last post (the one we just posted).
1214 return api_status_show($type);
1217 /// @TODO move to top of file or somwhere better
1218 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1219 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1221 function api_media_upload($type)
1225 if (api_user() === false) {
1227 throw new ForbiddenException();
1230 $user_info = api_get_user($a);
1232 if (!x($_FILES, 'media')) {
1234 throw new BadRequestException("No media.");
1237 $media = wall_upload_post($a, false);
1240 throw new InternalServerErrorException();
1243 $returndata = array();
1244 $returndata["media_id"] = $media["id"];
1245 $returndata["media_id_string"] = (string)$media["id"];
1246 $returndata["size"] = $media["size"];
1247 $returndata["image"] = array("w" => $media["width"],
1248 "h" => $media["height"],
1249 "image_type" => $media["type"]);
1251 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1253 return array("media" => $returndata);
1256 /// @TODO move to top of file or somwhere better
1257 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1259 function api_status_show($type)
1263 $user_info = api_get_user($a);
1265 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1267 if ($type == "raw") {
1268 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1273 // get last public wall message
1277 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1278 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1279 AND `item`.`type` != 'activity' $privacy_sql
1280 ORDER BY `item`.`id` DESC
1282 intval($user_info['cid']),
1284 dbesc($user_info['url']),
1285 dbesc(normalise_link($user_info['url'])),
1286 dbesc($user_info['url']),
1287 dbesc(normalise_link($user_info['url']))
1290 if (DBM::is_result($lastwall)) {
1291 $lastwall = $lastwall[0];
1293 $in_reply_to = api_in_reply_to($lastwall);
1295 $converted = api_convert_item($lastwall);
1297 if ($type == "xml") {
1298 $geo = "georss:point";
1303 $status_info = array(
1304 'created_at' => api_date($lastwall['created']),
1305 'id' => intval($lastwall['id']),
1306 'id_str' => (string) $lastwall['id'],
1307 'text' => $converted["text"],
1308 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1309 'truncated' => false,
1310 'in_reply_to_status_id' => $in_reply_to['status_id'],
1311 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1312 'in_reply_to_user_id' => $in_reply_to['user_id'],
1313 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1314 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1315 'user' => $user_info,
1317 'coordinates' => "",
1319 'contributors' => "",
1320 'is_quote_status' => false,
1321 'retweet_count' => 0,
1322 'favorite_count' => 0,
1323 'favorited' => $lastwall['starred'] ? true : false,
1324 'retweeted' => false,
1325 'possibly_sensitive' => false,
1327 'statusnet_html' => $converted["html"],
1328 'statusnet_conversation_id' => $lastwall['parent'],
1329 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1332 if (count($converted["attachments"]) > 0) {
1333 $status_info["attachments"] = $converted["attachments"];
1336 if (count($converted["entities"]) > 0) {
1337 $status_info["entities"] = $converted["entities"];
1340 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1341 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1342 } elseif (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1343 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1346 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1347 unset($status_info["user"]["uid"]);
1348 unset($status_info["user"]["self"]);
1351 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1353 if ($type == "raw") {
1354 return $status_info;
1357 return api_format_data("statuses", $type, array('status' => $status_info));
1361 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1362 * The author's most recent status will be returned inline.
1363 * http://developer.twitter.com/doc/get/users/show
1365 function api_users_show($type)
1369 $user_info = api_get_user($a);
1373 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1374 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1375 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1376 AND `type`!='activity'
1377 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1381 dbesc(ACTIVITY_POST),
1382 intval($user_info['cid']),
1383 dbesc($user_info['url']),
1384 dbesc(normalise_link($user_info['url'])),
1385 dbesc($user_info['url']),
1386 dbesc(normalise_link($user_info['url']))
1389 if (DBM::is_result($lastwall)) {
1390 $lastwall = $lastwall[0];
1392 $in_reply_to = api_in_reply_to($lastwall);
1394 $converted = api_convert_item($lastwall);
1396 if ($type == "xml") {
1397 $geo = "georss:point";
1402 $user_info['status'] = array(
1403 'text' => $converted["text"],
1404 'truncated' => false,
1405 'created_at' => api_date($lastwall['created']),
1406 'in_reply_to_status_id' => $in_reply_to['status_id'],
1407 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1408 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1409 'id' => intval($lastwall['contact-id']),
1410 'id_str' => (string) $lastwall['contact-id'],
1411 'in_reply_to_user_id' => $in_reply_to['user_id'],
1412 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1413 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1415 'favorited' => $lastwall['starred'] ? true : false,
1416 'statusnet_html' => $converted["html"],
1417 'statusnet_conversation_id' => $lastwall['parent'],
1418 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1421 if (count($converted["attachments"]) > 0) {
1422 $user_info["status"]["attachments"] = $converted["attachments"];
1425 if (count($converted["entities"]) > 0) {
1426 $user_info["status"]["entities"] = $converted["entities"];
1429 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1430 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1433 if (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1434 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
1438 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1439 unset($user_info["uid"]);
1440 unset($user_info["self"]);
1442 return api_format_data("user", $type, array('user' => $user_info));
1445 /// @TODO move to top of file or somewhere better
1446 api_register_func('api/users/show', 'api_users_show');
1447 api_register_func('api/externalprofile/show', 'api_users_show');
1449 function api_users_search($type)
1453 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1455 $userlist = array();
1457 if (x($_GET, 'q')) {
1458 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1460 if (!DBM::is_result($r)) {
1461 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1464 if (DBM::is_result($r)) {
1466 foreach ($r as $user) {
1467 $user_info = api_get_user($a, $user["id"], "json");
1469 if ($type == "xml") {
1470 $userlist[$k++.":user"] = $user_info;
1472 $userlist[] = $user_info;
1475 $userlist = array("users" => $userlist);
1477 throw new BadRequestException("User not found.");
1480 throw new BadRequestException("User not found.");
1482 return api_format_data("users", $type, $userlist);
1485 /// @TODO move to top of file or somewhere better
1486 api_register_func('api/users/search', 'api_users_search');
1489 * Returns statuses that match a specified query.
1491 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1493 * @param string $type Return format: json, xml, atom, rss
1495 * @return array|string
1496 * @throws UnauthorizedException
1497 * @throws BadRequestException
1499 function api_search($type)
1503 if (x($_REQUEST, 'q')) {
1504 if (x($_REQUEST, 'rpp')) {
1505 $count = $_REQUEST['rpp'];
1506 } elseif (x($_REQUEST, 'count')) {
1507 $count = $_REQUEST['count'];
1512 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1513 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1514 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1516 $start = $page * $count;
1519 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1525 WHERE %s AND (`item`.`uid` = 0 OR (`item`.`uid` = %s AND NOT `item`.`global`))
1526 AND `item`.`body` REGEXP '%s'
1529 GROUP BY `item`.`uri`, `item`.`id`
1530 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1534 intval(local_user()),
1535 dbesc(protect_sprintf(preg_quote($_REQUEST['q']))),
1541 $data['status'] = api_format_items($r, api_get_user(get_app()));
1543 throw new BadRequestException("q parameter is required.");
1546 return api_format_data("statuses", $type, $data);
1549 /// @TODO move to top of file or somewhere better
1550 api_register_func('api/search/tweets', 'api_search', true);
1551 api_register_func('api/search', 'api_search', true);
1555 * http://developer.twitter.com/doc/get/statuses/home_timeline
1557 * TODO: Optional parameters
1558 * TODO: Add reply info
1560 function api_statuses_home_timeline($type)
1564 if (api_user() === false) {
1565 throw new ForbiddenException();
1568 unset($_REQUEST["user_id"]);
1569 unset($_GET["user_id"]);
1571 unset($_REQUEST["screen_name"]);
1572 unset($_GET["screen_name"]);
1574 $user_info = api_get_user($a);
1575 // get last newtork messages
1578 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1579 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1583 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1584 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1585 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1586 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1587 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1589 $start = $page * $count;
1593 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1595 if ($exclude_replies > 0) {
1596 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1598 if ($conversation_id > 0) {
1599 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1603 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1604 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1605 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1606 `contact`.`id` AS `cid`
1608 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1609 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1610 WHERE `item`.`uid` = %d AND `verb` = '%s'
1611 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1614 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1616 dbesc(ACTIVITY_POST),
1622 $ret = api_format_items($r, $user_info, false, $type);
1624 // Set all posts from the query above to seen
1626 foreach ($r as $item) {
1627 $idarray[] = intval($item["id"]);
1630 $idlist = implode(",", $idarray);
1632 if ($idlist != "") {
1633 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1636 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1640 $data = array('status' => $ret);
1644 $data = api_rss_extra($a, $data, $user_info);
1648 return api_format_data("statuses", $type, $data);
1651 /// @TODO move to top of file or somewhere better
1652 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1653 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1655 function api_statuses_public_timeline($type)
1659 if (api_user() === false) {
1660 throw new ForbiddenException();
1663 $user_info = api_get_user($a);
1664 // get last newtork messages
1667 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1668 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1672 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1673 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1674 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1675 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1676 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1678 $start = $page * $count;
1680 if ($exclude_replies && !$conversation_id) {
1682 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1685 $r = dba::p("SELECT " . item_fieldlists() . "
1687 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1688 " . item_joins() . "
1689 STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1690 AND NOT `user`.`hidewall`
1692 AND NOT `thread`.`private`
1694 AND `thread`.`visible`
1695 AND NOT `thread`.`deleted`
1696 AND NOT `thread`.`moderated`
1697 AND `thread`.`iid` > ?
1699 ORDER BY `thread`.`iid` DESC
1700 LIMIT " . intval($start) . ", " . intval($count),
1705 $r = dba::inArray($r);
1708 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1710 if ($conversation_id > 0) {
1711 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1714 $r = dba::p("SELECT " . item_fieldlists() . "
1716 " . item_joins() . "
1717 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1718 AND NOT `user`.`hidewall`
1720 AND NOT `item`.`private`
1722 AND `item`.`visible`
1723 AND NOT `item`.`deleted`
1724 AND NOT `item`.`moderated`
1727 ORDER BY `item`.`id` DESC
1728 LIMIT " . intval($start) . ", " . intval($count),
1733 $r = dba::inArray($r);
1736 $ret = api_format_items($r, $user_info, false, $type);
1738 $data = array('status' => $ret);
1742 $data = api_rss_extra($a, $data, $user_info);
1746 return api_format_data("statuses", $type, $data);
1749 /// @TODO move to top of file or somewhere better
1750 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1753 * @brief Returns the list of public federated posts this node knows about
1755 * @param string $type Return format: json, xml, atom, rss
1756 * @return array|string
1757 * @throws ForbiddenException
1759 function api_statuses_networkpublic_timeline($type)
1763 if (api_user() === false) {
1764 throw new ForbiddenException();
1767 $user_info = api_get_user($a);
1769 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1770 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1773 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1774 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1778 $start = ($page - 1) * $count;
1782 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1785 $r = dba::p("SELECT " . item_fieldlists() . "
1787 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1788 " . item_joins() . "
1789 WHERE `thread`.`uid` = 0
1791 AND NOT `thread`.`private`
1792 AND `thread`.`visible`
1793 AND NOT `thread`.`deleted`
1794 AND NOT `thread`.`moderated`
1795 AND `thread`.`iid` > ?
1797 ORDER BY `thread`.`iid` DESC
1798 LIMIT " . intval($start) . ", " . intval($count),
1803 $r = dba::inArray($r);
1805 $ret = api_format_items($r, $user_info, false, $type);
1807 $data = array('status' => $ret);
1811 $data = api_rss_extra($a, $data, $user_info);
1815 return api_format_data("statuses", $type, $data);
1818 /// @TODO move to top of file or somewhere better
1819 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1822 * @TODO nothing to say?
1824 function api_statuses_show($type)
1828 if (api_user() === false) {
1829 throw new ForbiddenException();
1832 $user_info = api_get_user($a);
1835 $id = intval($a->argv[3]);
1838 $id = intval($_REQUEST["id"]);
1843 $id = intval($a->argv[4]);
1846 logger('API: api_statuses_show: ' . $id);
1848 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1851 if ($conversation) {
1852 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1854 $sql_extra .= " AND `item`.`id` = %d";
1858 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1859 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1860 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1861 `contact`.`id` AS `cid`
1863 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1864 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1865 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1866 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1869 dbesc(ACTIVITY_POST),
1873 /// @TODO How about copying this to above methods which don't check $r ?
1874 if (!DBM::is_result($r)) {
1875 throw new BadRequestException("There is no status with this id.");
1878 $ret = api_format_items($r, $user_info, false, $type);
1880 if ($conversation) {
1881 $data = array('status' => $ret);
1882 return api_format_data("statuses", $type, $data);
1884 $data = array('status' => $ret[0]);
1885 return api_format_data("status", $type, $data);
1889 /// @TODO move to top of file or somewhere better
1890 api_register_func('api/statuses/show', 'api_statuses_show', true);
1893 * @TODO nothing to say?
1895 function api_conversation_show($type)
1899 if (api_user() === false) {
1900 throw new ForbiddenException();
1903 $user_info = api_get_user($a);
1906 $id = intval($a->argv[3]);
1907 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1908 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1912 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1913 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1915 $start = $page*$count;
1918 $id = intval($_REQUEST["id"]);
1923 $id = intval($a->argv[4]);
1926 logger('API: api_conversation_show: '.$id);
1928 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1929 if (DBM::is_result($r)) {
1930 $id = $r[0]["parent"];
1936 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1939 // Not sure why this query was so complicated. We should keep it here for a while,
1940 // just to make sure that we really don't need it.
1941 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1942 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1945 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1946 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1947 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1948 `contact`.`id` AS `cid`
1950 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1951 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1952 WHERE `item`.`parent` = %d AND `item`.`visible`
1953 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1954 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1955 AND `item`.`id`>%d $sql_extra
1956 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1957 intval($id), intval(api_user()),
1958 dbesc(ACTIVITY_POST),
1960 intval($start), intval($count)
1963 if (!DBM::is_result($r)) {
1964 throw new BadRequestException("There is no status with this id.");
1967 $ret = api_format_items($r, $user_info, false, $type);
1969 $data = array('status' => $ret);
1970 return api_format_data("statuses", $type, $data);
1973 /// @TODO move to top of file or somewhere better
1974 api_register_func('api/conversation/show', 'api_conversation_show', true);
1975 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1978 * @TODO nothing to say?
1980 function api_statuses_repeat($type)
1986 if (api_user() === false) {
1987 throw new ForbiddenException();
1990 $user_info = api_get_user($a);
1993 $id = intval($a->argv[3]);
1996 $id = intval($_REQUEST["id"]);
2001 $id = intval($a->argv[4]);
2004 logger('API: api_statuses_repeat: '.$id);
2007 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2008 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2009 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2010 `contact`.`id` AS `cid`
2012 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2013 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2014 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2015 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2016 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2018 AND `item`.`id`=%d",
2022 /// @TODO other style than above functions!
2023 if (DBM::is_result($r) && $r[0]['body'] != "") {
2024 if (strpos($r[0]['body'], "[/share]") !== false) {
2025 $pos = strpos($r[0]['body'], "[share");
2026 $post = substr($r[0]['body'], $pos);
2028 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2030 $post .= $r[0]['body'];
2031 $post .= "[/share]";
2033 $_REQUEST['body'] = $post;
2034 $_REQUEST['profile_uid'] = api_user();
2035 $_REQUEST['type'] = 'wall';
2036 $_REQUEST['api_source'] = true;
2038 if (!x($_REQUEST, "source")) {
2039 $_REQUEST["source"] = api_source();
2044 throw new ForbiddenException();
2047 // this should output the last post (the one we just posted).
2049 return api_status_show($type);
2052 /// @TODO move to top of file or somewhere better
2053 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2056 * @TODO nothing to say?
2058 function api_statuses_destroy($type)
2062 if (api_user() === false) {
2063 throw new ForbiddenException();
2066 $user_info = api_get_user($a);
2069 $id = intval($a->argv[3]);
2072 $id = intval($_REQUEST["id"]);
2077 $id = intval($a->argv[4]);
2080 logger('API: api_statuses_destroy: '.$id);
2082 $ret = api_statuses_show($type);
2084 drop_item($id, false);
2089 /// @TODO move to top of file or somewhere better
2090 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2093 * @TODO Nothing more than an URL to say?
2094 * http://developer.twitter.com/doc/get/statuses/mentions
2096 function api_statuses_mentions($type)
2100 if (api_user() === false) {
2101 throw new ForbiddenException();
2104 unset($_REQUEST["user_id"]);
2105 unset($_GET["user_id"]);
2107 unset($_REQUEST["screen_name"]);
2108 unset($_GET["screen_name"]);
2110 $user_info = api_get_user($a);
2111 // get last newtork messages
2115 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2116 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2120 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2121 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2122 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2124 $start = $page * $count;
2126 // Ugly code - should be changed
2127 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2128 $myurl = substr($myurl, strpos($myurl, '://') + 3);
2129 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
2130 $myurl = str_replace('www.', '', $myurl);
2131 $diasp_url = str_replace('/profile/', '/u/', $myurl);
2134 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2138 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2139 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2140 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2141 `contact`.`id` AS `cid`
2142 FROM `item` FORCE INDEX (`uid_id`)
2143 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2144 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2145 WHERE `item`.`uid` = %d AND `verb` = '%s'
2146 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2147 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2148 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2151 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2153 dbesc(ACTIVITY_POST),
2154 dbesc(protect_sprintf($myurl)),
2155 dbesc(protect_sprintf($myurl)),
2162 $ret = api_format_items($r, $user_info, false, $type);
2164 $data = array('status' => $ret);
2168 $data = api_rss_extra($a, $data, $user_info);
2172 return api_format_data("statuses", $type, $data);
2175 /// @TODO move to top of file or somewhere better
2176 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2177 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2180 * @brief Returns a user's public timeline
2182 * @param string $type Either "json" or "xml"
2183 * @return string|array
2184 * @throws ForbiddenException
2186 function api_statuses_user_timeline($type)
2190 if (api_user() === false) {
2191 throw new ForbiddenException();
2194 $user_info = api_get_user($a);
2197 "api_statuses_user_timeline: api_user: ". api_user() .
2198 "\nuser_info: ".print_r($user_info, true) .
2199 "\n_REQUEST: ".print_r($_REQUEST, true),
2203 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2204 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2205 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2206 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2209 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2210 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2214 $start = ($page - 1) * $count;
2217 if ($user_info['self'] == 1) {
2218 $sql_extra .= " AND `item`.`wall` = 1 ";
2221 if ($exclude_replies > 0) {
2222 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2225 if ($conversation_id > 0) {
2226 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2230 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2234 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2235 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2236 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2237 `contact`.`id` AS `cid`
2238 FROM `item` FORCE INDEX (`uid_contactid_id`)
2239 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2240 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2241 WHERE `item`.`uid` = %d AND `verb` = '%s'
2242 AND `item`.`contact-id` = %d
2243 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2245 AND `item`.`id` > %d
2246 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2248 dbesc(ACTIVITY_POST),
2249 intval($user_info['cid']),
2255 $ret = api_format_items($r, $user_info, true, $type);
2257 $data = array('status' => $ret);
2261 $data = api_rss_extra($a, $data, $user_info);
2265 return api_format_data("statuses", $type, $data);
2268 /// @TODO move to top of file or somwhere better
2269 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2272 * Star/unstar an item
2273 * param: id : id of the item
2275 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2277 function api_favorites_create_destroy($type)
2281 if (api_user() === false) {
2282 throw new ForbiddenException();
2285 // for versioned api.
2286 /// @TODO We need a better global soluton
2287 $action_argv_id = 2;
2288 if ($a->argv[1] == "1.1") {
2289 $action_argv_id = 3;
2292 if ($a->argc <= $action_argv_id) {
2293 throw new BadRequestException("Invalid request.");
2295 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2296 if ($a->argc == $action_argv_id + 2) {
2297 $itemid = intval($a->argv[$action_argv_id + 1]);
2299 /// @TODO use x() to check if _REQUEST contains 'id'
2300 $itemid = intval($_REQUEST['id']);
2303 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2305 if (!DBM::is_result($item) || count($item) == 0) {
2306 throw new BadRequestException("Invalid item.");
2311 $item[0]['starred'] = 1;
2314 $item[0]['starred'] = 0;
2317 throw new BadRequestException("Invalid action ".$action);
2320 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2322 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2325 throw new InternalServerErrorException("DB error");
2329 $user_info = api_get_user($a);
2330 $rets = api_format_items($item, $user_info, false, $type);
2333 $data = array('status' => $ret);
2337 $data = api_rss_extra($a, $data, $user_info);
2340 return api_format_data("status", $type, $data);
2343 /// @TODO move to top of file or somwhere better
2344 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2345 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2347 function api_favorites($type)
2353 if (api_user() === false) {
2354 throw new ForbiddenException();
2357 $called_api = array();
2359 $user_info = api_get_user($a);
2361 // in friendica starred item are private
2362 // return favorites only for self
2363 logger('api_favorites: self:' . $user_info['self']);
2365 if ($user_info['self'] == 0) {
2371 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2372 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2373 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2374 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2379 $start = $page*$count;
2382 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2386 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2387 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2388 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2389 `contact`.`id` AS `cid`
2390 FROM `item`, `contact`
2391 WHERE `item`.`uid` = %d
2392 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2393 AND `item`.`starred` = 1
2394 AND `contact`.`id` = `item`.`contact-id`
2395 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2398 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2405 $ret = api_format_items($r, $user_info, false, $type);
2408 $data = array('status' => $ret);
2412 $data = api_rss_extra($a, $data, $user_info);
2415 return api_format_data("statuses", $type, $data);
2418 /// @TODO move to top of file or somwhere better
2419 api_register_func('api/favorites', 'api_favorites', true);
2421 function api_format_messages($item, $recipient, $sender)
2423 // standard meta information
2425 'id' => $item['id'],
2426 'sender_id' => $sender['id'] ,
2428 'recipient_id' => $recipient['id'],
2429 'created_at' => api_date($item['created']),
2430 'sender_screen_name' => $sender['screen_name'],
2431 'recipient_screen_name' => $recipient['screen_name'],
2432 'sender' => $sender,
2433 'recipient' => $recipient,
2435 'friendica_seen' => $item['seen'],
2436 'friendica_parent_uri' => $item['parent-uri'],
2439 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2440 unset($ret["sender"]["uid"]);
2441 unset($ret["sender"]["self"]);
2442 unset($ret["recipient"]["uid"]);
2443 unset($ret["recipient"]["self"]);
2445 //don't send title to regular StatusNET requests to avoid confusing these apps
2446 if (x($_GET, 'getText')) {
2447 $ret['title'] = $item['title'];
2448 if ($_GET['getText'] == 'html') {
2449 $ret['text'] = bbcode($item['body'], false, false);
2450 } elseif ($_GET['getText'] == 'plain') {
2451 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2452 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2455 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2457 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2458 unset($ret['sender']);
2459 unset($ret['recipient']);
2465 function api_convert_item($item)
2467 $body = $item['body'];
2468 $attachments = api_get_attachments($body);
2470 // Workaround for ostatus messages where the title is identically to the body
2471 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2472 $statusbody = trim(html2plain($html, 0));
2474 // handle data: images
2475 $statusbody = api_format_items_embeded_images($item, $statusbody);
2477 $statustitle = trim($item['title']);
2479 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2480 $statustext = trim($statusbody);
2482 $statustext = trim($statustitle."\n\n".$statusbody);
2485 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2486 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2489 $statushtml = trim(bbcode($body, false, false));
2491 // Workaround for clients with limited HTML parser functionality
2492 $search = array("<br>", "<blockquote>", "</blockquote>",
2493 "<h1>", "</h1>", "<h2>", "</h2>",
2494 "<h3>", "</h3>", "<h4>", "</h4>",
2495 "<h5>", "</h5>", "<h6>", "</h6>");
2496 $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2497 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2498 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2499 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2500 $statushtml = str_replace($search, $replace, $statushtml);
2502 if ($item['title'] != "") {
2503 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2507 $oldtext = $statushtml;
2508 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2509 } while ($oldtext != $statushtml);
2511 if (substr($statushtml, 0, 4) == '<br>') {
2512 $statushtml = substr($statushtml, 4);
2515 if (substr($statushtml, 0, -4) == '<br>') {
2516 $statushtml = substr($statushtml, -4);
2519 // feeds without body should contain the link
2520 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2521 $statushtml .= bbcode($item['plink']);
2524 $entities = api_get_entitities($statustext, $body);
2527 "text" => $statustext,
2528 "html" => $statushtml,
2529 "attachments" => $attachments,
2530 "entities" => $entities
2534 function api_get_attachments(&$body)
2537 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2539 $URLSearchString = "^\[\]";
2540 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2546 $attachments = array();
2548 foreach ($images[1] as $image) {
2549 $imagedata = Image::getInfoFromURL($image);
2552 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2556 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2557 foreach ($images[0] as $orig) {
2558 $body = str_replace($orig, "", $body);
2562 return $attachments;
2565 function api_get_entitities(&$text, $bbcode)
2569 * Links at the first character of the post
2574 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2576 if ($include_entities != "true") {
2577 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2579 foreach ($images[1] as $image) {
2580 $replace = proxy_url($image);
2581 $text = str_replace($image, $replace, $text);
2586 $bbcode = bb_CleanPictureLinks($bbcode);
2588 // Change pure links in text to bbcode uris
2589 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2591 $entities = array();
2592 $entities["hashtags"] = array();
2593 $entities["symbols"] = array();
2594 $entities["urls"] = array();
2595 $entities["user_mentions"] = array();
2597 $URLSearchString = "^\[\]";
2599 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2601 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2602 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2603 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2605 $bbcode = preg_replace(
2606 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2607 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2610 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2612 $bbcode = preg_replace(
2613 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2614 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2617 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2619 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2621 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2622 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2624 $ordered_urls = array();
2625 foreach ($urls[1] as $id => $url) {
2626 //$start = strpos($text, $url, $offset);
2627 $start = iconv_strpos($text, $url, 0, "UTF-8");
2628 if (!($start === false)) {
2629 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2633 ksort($ordered_urls);
2636 //foreach ($urls[1] AS $id=>$url) {
2637 foreach ($ordered_urls as $url) {
2638 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2639 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2641 $display_url = $url["title"];
2643 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2644 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2646 if (strlen($display_url) > 26)
2647 $display_url = substr($display_url, 0, 25)."…";
2650 //$start = strpos($text, $url, $offset);
2651 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2652 if (!($start === false)) {
2653 $entities["urls"][] = array("url" => $url["url"],
2654 "expanded_url" => $url["url"],
2655 "display_url" => $display_url,
2656 "indices" => array($start, $start+strlen($url["url"])));
2657 $offset = $start + 1;
2661 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2662 $ordered_images = array();
2663 foreach ($images[1] as $image) {
2664 //$start = strpos($text, $url, $offset);
2665 $start = iconv_strpos($text, $image, 0, "UTF-8");
2666 if (!($start === false))
2667 $ordered_images[$start] = $image;
2669 //$entities["media"] = array();
2672 foreach ($ordered_images as $url) {
2673 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2674 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2676 if (strlen($display_url) > 26)
2677 $display_url = substr($display_url, 0, 25)."…";
2679 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2680 if (!($start === false)) {
2681 $image = Image::getInfoFromURL($url);
2683 // If image cache is activated, then use the following sizes:
2684 // thumb (150), small (340), medium (600) and large (1024)
2685 if (!Config::get("system", "proxy_disabled")) {
2686 $media_url = proxy_url($url);
2689 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2690 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2692 if (($image[0] > 150) || ($image[1] > 150)) {
2693 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2694 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2697 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2698 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2700 if (($image[0] > 600) || ($image[1] > 600)) {
2701 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2702 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2706 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2709 $entities["media"][] = array(
2711 "id_str" => (string)$start+1,
2712 "indices" => array($start, $start+strlen($url)),
2713 "media_url" => normalise_link($media_url),
2714 "media_url_https" => $media_url,
2716 "display_url" => $display_url,
2717 "expanded_url" => $url,
2721 $offset = $start + 1;
2727 function api_format_items_embeded_images(&$item, $text)
2729 $text = preg_replace_callback(
2730 "|data:image/([^;]+)[^=]+=*|m",
2731 function ($match) use ($item) {
2732 return System::baseUrl()."/display/".$item['guid'];
2741 * @brief return <a href='url'>name</a> as array
2743 * @param string $txt text
2748 function api_contactlink_to_array($txt)
2751 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2752 if ($r && count($match)==3) {
2754 'name' => $match[2],
2768 * @brief return likes, dislikes and attend status for item
2770 * @param array $item array
2772 * likes => int count
2773 * dislikes => int count
2775 function api_format_items_activities(&$item, $type = "json")
2779 $activities = array(
2781 'dislike' => array(),
2782 'attendyes' => array(),
2783 'attendno' => array(),
2784 'attendmaybe' => array(),
2789 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2790 intval($item['uid']),
2794 foreach ($items as $i) {
2795 // not used as result should be structured like other user data
2796 //builtin_activity_puller($i, $activities);
2798 // get user data and add it to the array of the activity
2799 $user = api_get_user($a, $i['author-link']);
2800 switch ($i['verb']) {
2802 $activities['like'][] = $user;
2804 case ACTIVITY_DISLIKE:
2805 $activities['dislike'][] = $user;
2807 case ACTIVITY_ATTEND:
2808 $activities['attendyes'][] = $user;
2810 case ACTIVITY_ATTENDNO:
2811 $activities['attendno'][] = $user;
2813 case ACTIVITY_ATTENDMAYBE:
2814 $activities['attendmaybe'][] = $user;
2821 if ($type == "xml") {
2822 $xml_activities = array();
2823 foreach ($activities as $k => $v) {
2824 // change xml element from "like" to "friendica:like"
2825 $xml_activities["friendica:".$k] = $v;
2826 // add user data into xml output
2828 foreach ($v as $user)
2829 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2831 $activities = $xml_activities;
2839 * @brief return data from profiles
2841 * @param array $profile array containing data from db table 'profile'
2842 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2845 function api_format_items_profiles(&$profile = null, $type = "json")
2847 if ($profile != null) {
2848 $profile = array('profile_id' => $profile['id'],
2849 'profile_name' => $profile['profile-name'],
2850 'is_default' => $profile['is-default'] ? true : false,
2851 'hide_friends'=> $profile['hide-friends'] ? true : false,
2852 'profile_photo' => $profile['photo'],
2853 'profile_thumb' => $profile['thumb'],
2854 'publish' => $profile['publish'] ? true : false,
2855 'net_publish' => $profile['net-publish'] ? true : false,
2856 'description' => $profile['pdesc'],
2857 'date_of_birth' => $profile['dob'],
2858 'address' => $profile['address'],
2859 'city' => $profile['locality'],
2860 'region' => $profile['region'],
2861 'postal_code' => $profile['postal-code'],
2862 'country' => $profile['country-name'],
2863 'hometown' => $profile['hometown'],
2864 'gender' => $profile['gender'],
2865 'marital' => $profile['marital'],
2866 'marital_with' => $profile['with'],
2867 'marital_since' => $profile['howlong'],
2868 'sexual' => $profile['sexual'],
2869 'politic' => $profile['politic'],
2870 'religion' => $profile['religion'],
2871 'public_keywords' => $profile['pub_keywords'],
2872 'private_keywords' => $profile['prv_keywords'],
2873 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2874 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2875 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2876 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2877 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2878 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2879 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2880 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2881 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2882 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2883 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2884 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2885 'homepage' => $profile['homepage'],
2892 * @brief format items to be returned by api
2894 * @param array $r array of items
2895 * @param array $user_info
2896 * @param bool $filter_user filter items by $user_info
2898 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2904 foreach ($r as $item) {
2905 localize_item($item);
2906 list($status_user, $owner_user) = api_item_get_user($a, $item);
2908 // Look if the posts are matching if they should be filtered by user id
2909 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2913 $in_reply_to = api_in_reply_to($item);
2915 $converted = api_convert_item($item);
2917 if ($type == "xml") {
2918 $geo = "georss:point";
2924 'text' => $converted["text"],
2925 'truncated' => false,
2926 'created_at'=> api_date($item['created']),
2927 'in_reply_to_status_id' => $in_reply_to['status_id'],
2928 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2929 'source' => (($item['app']) ? $item['app'] : 'web'),
2930 'id' => intval($item['id']),
2931 'id_str' => (string) intval($item['id']),
2932 'in_reply_to_user_id' => $in_reply_to['user_id'],
2933 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2934 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2936 'favorited' => $item['starred'] ? true : false,
2937 'user' => $status_user ,
2938 'friendica_owner' => $owner_user,
2939 //'entities' => NULL,
2940 'statusnet_html' => $converted["html"],
2941 'statusnet_conversation_id' => $item['parent'],
2942 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2943 'friendica_activities' => api_format_items_activities($item, $type),
2946 if (count($converted["attachments"]) > 0) {
2947 $status["attachments"] = $converted["attachments"];
2950 if (count($converted["entities"]) > 0) {
2951 $status["entities"] = $converted["entities"];
2954 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
2955 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2956 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2957 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2961 // Retweets are only valid for top postings
2962 // It doesn't work reliable with the link if its a feed
2963 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2965 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
2968 if ($item["id"] == $item["parent"]) {
2969 $retweeted_item = api_share_as_retweet($item);
2970 if ($retweeted_item !== false) {
2971 $retweeted_status = $status;
2973 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
2974 } catch (BadRequestException $e) {
2975 // user not found. should be found?
2976 /// @todo check if the user should be always found
2977 $retweeted_status["user"] = array();
2980 $rt_converted = api_convert_item($retweeted_item);
2982 $retweeted_status['text'] = $rt_converted["text"];
2983 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2984 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2985 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2986 $status['retweeted_status'] = $retweeted_status;
2990 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2991 unset($status["user"]["uid"]);
2992 unset($status["user"]["self"]);
2994 if ($item["coord"] != "") {
2995 $coords = explode(' ', $item["coord"]);
2996 if (count($coords) == 2) {
2997 if ($type == "json")
2998 $status["geo"] = array('type' => 'Point',
2999 'coordinates' => array((float) $coords[0],
3000 (float) $coords[1]));
3001 else // Not sure if this is the official format - if someone founds a documentation we can check
3002 $status["georss:point"] = $item["coord"];
3010 function api_account_rate_limit_status($type)
3012 if ($type == "xml") {
3014 'remaining-hits' => '150',
3015 '@attributes' => array("type" => "integer"),
3016 'hourly-limit' => '150',
3017 '@attributes2' => array("type" => "integer"),
3018 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
3019 '@attributes3' => array("type" => "datetime"),
3020 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3021 '@attributes4' => array("type" => "integer"),
3025 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3026 'remaining_hits' => '150',
3027 'hourly_limit' => '150',
3028 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
3032 return api_format_data('hash', $type, array('hash' => $hash));
3035 /// @TODO move to top of file or somwhere better
3036 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3038 function api_help_test($type)
3040 if ($type == 'xml') {
3046 return api_format_data('ok', $type, array("ok" => $ok));
3049 /// @TODO move to top of file or somwhere better
3050 api_register_func('api/help/test', 'api_help_test', false);
3052 function api_lists($type)
3055 /// @TODO $ret is not filled here?
3056 return api_format_data('lists', $type, array("lists_list" => $ret));
3059 /// @TODO move to top of file or somwhere better
3060 api_register_func('api/lists', 'api_lists', true);
3062 function api_lists_list($type)
3065 /// @TODO $ret is not filled here?
3066 return api_format_data('lists', $type, array("lists_list" => $ret));
3069 /// @TODO move to top of file or somwhere better
3070 api_register_func('api/lists/list', 'api_lists_list', true);
3073 * @brief Returns either the friends of the follower list
3075 * Note: Considers friends and followers lists to be private and won't return
3076 * anything if any user_id parameter is passed.
3078 * @param string $qtype Either "friends" or "followers"
3079 * @return boolean|array
3080 * @throws ForbiddenException
3082 function api_statuses_f($qtype)
3086 if (api_user() === false) {
3087 throw new ForbiddenException();
3091 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3092 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3096 $start = ($page - 1) * $count;
3098 $user_info = api_get_user($a);
3100 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3101 /* this is to stop Hotot to load friends multiple times
3102 * I'm not sure if I'm missing return something or
3103 * is a bug in hotot. Workaround, meantime
3107 return array('$users' => $ret);*/
3111 if ($qtype == 'friends') {
3112 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3114 if ($qtype == 'followers') {
3115 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3118 // friends and followers only for self
3119 if ($user_info['self'] == 0) {
3120 $sql_extra = " AND false ";
3128 AND (NOT `blocked` OR `pending`)
3138 foreach ($r as $cid) {
3139 $user = api_get_user($a, $cid['nurl']);
3140 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3141 unset($user["uid"]);
3142 unset($user["self"]);
3149 return array('user' => $ret);
3154 * @brief Returns the list of friends of the provided user
3156 * @deprecated By Twitter API in favor of friends/list
3158 * @param string $type Either "json" or "xml"
3159 * @return boolean|string|array
3161 function api_statuses_friends($type)
3163 $data = api_statuses_f("friends");
3164 if ($data === false) {
3167 return api_format_data("users", $type, $data);
3171 * @brief Returns the list of friends of the provided user
3173 * @deprecated By Twitter API in favor of friends/list
3175 * @param string $type Either "json" or "xml"
3176 * @return boolean|string|array
3178 function api_statuses_followers($type)
3180 $data = api_statuses_f("followers");
3181 if ($data === false) {
3184 return api_format_data("users", $type, $data);
3187 /// @TODO move to top of file or somewhere better
3188 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3189 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3191 function api_statusnet_config($type)
3195 $name = $a->config['sitename'];
3196 $server = $a->get_hostname();
3197 $logo = System::baseUrl() . '/images/friendica-64.png';
3198 $email = $a->config['admin_email'];
3199 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3200 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3201 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3202 if ($a->config['api_import_size']) {
3203 $texlimit = string($a->config['api_import_size']);
3205 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3206 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3209 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3210 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3211 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3212 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3213 'shorturllength' => '30',
3214 'friendica' => array(
3215 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3216 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3217 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3218 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3223 return api_format_data('config', $type, array('config' => $config));
3226 /// @TODO move to top of file or somewhere better
3227 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3228 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3230 function api_statusnet_version($type)
3233 $fake_statusnet_version = "0.9.7";
3235 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
3238 /// @TODO move to top of file or somewhere better
3239 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3240 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3243 * @todo use api_format_data() to return data
3245 function api_ff_ids($type,$qtype)
3250 throw new ForbiddenException();
3253 $user_info = api_get_user($a);
3255 if ($qtype == 'friends') {
3256 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3258 if ($qtype == 'followers') {
3259 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3262 if (!$user_info["self"]) {
3263 $sql_extra = " AND false ";
3266 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3269 "SELECT `pcontact`.`id` FROM `contact`
3270 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3271 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3275 if (!DBM::is_result($r)) {
3280 foreach ($r as $rr) {
3281 if ($stringify_ids) {
3284 $ids[] = intval($rr['id']);
3288 return api_format_data("ids", $type, array('id' => $ids));
3291 function api_friends_ids($type)
3293 return api_ff_ids($type, 'friends');
3296 function api_followers_ids($type)
3298 return api_ff_ids($type, 'followers');
3301 /// @TODO move to top of file or somewhere better
3302 api_register_func('api/friends/ids', 'api_friends_ids', true);
3303 api_register_func('api/followers/ids', 'api_followers_ids', true);
3305 function api_direct_messages_new($type)
3310 if (api_user() === false) throw new ForbiddenException();
3312 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) return;
3314 $sender = api_get_user($a);
3316 if ($_POST['screen_name']) {
3318 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3320 dbesc($_POST['screen_name'])
3323 // Selecting the id by priority, friendica first
3324 api_best_nickname($r);
3326 $recipient = api_get_user($a, $r[0]['nurl']);
3328 $recipient = api_get_user($a, $_POST['user_id']);
3333 if (x($_REQUEST, 'replyto')) {
3335 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3337 intval($_REQUEST['replyto'])
3339 $replyto = $r[0]['parent-uri'];
3340 $sub = $r[0]['title'];
3342 if (x($_REQUEST, 'title')) {
3343 $sub = $_REQUEST['title'];
3345 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3349 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3352 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3353 $ret = api_format_messages($r[0], $recipient, $sender);
3355 $ret = array("error"=>$id);
3358 $data = array('direct_message'=>$ret);
3363 $data = api_rss_extra($a, $data, $user_info);
3366 return api_format_data("direct-messages", $type, $data);
3370 /// @TODO move to top of file or somewhere better
3371 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3374 * @brief delete a direct_message from mail table through api
3376 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3379 function api_direct_messages_destroy($type)
3383 if (api_user() === false) {
3384 throw new ForbiddenException();
3388 $user_info = api_get_user($a);
3390 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3392 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3393 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3394 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3396 $uid = $user_info['uid'];
3397 // error if no id or parenturi specified (for clients posting parent-uri as well)
3398 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3399 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3400 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3403 // BadRequestException if no id specified (for clients using Twitter API)
3405 throw new BadRequestException('Message id not specified');
3408 // add parent-uri to sql command if specified by calling app
3409 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3411 // get data of the specified message id
3413 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3418 // error message if specified id is not in database
3419 if (!DBM::is_result($r)) {
3420 if ($verbose == "true") {
3421 $answer = array('result' => 'error', 'message' => 'message id not in database');
3422 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3424 /// @todo BadRequestException ok for Twitter API clients?
3425 throw new BadRequestException('message id not in database');
3430 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3435 if ($verbose == "true") {
3438 $answer = array('result' => 'ok', 'message' => 'message deleted');
3439 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3441 $answer = array('result' => 'error', 'message' => 'unknown error');
3442 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3445 /// @todo return JSON data like Twitter API not yet implemented
3449 /// @TODO move to top of file or somewhere better
3450 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3452 function api_direct_messages_box($type, $box, $verbose)
3456 if (api_user() === false) {
3457 throw new ForbiddenException();
3461 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3462 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3467 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3468 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3470 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3471 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3474 unset($_REQUEST["user_id"]);
3475 unset($_GET["user_id"]);
3477 unset($_REQUEST["screen_name"]);
3478 unset($_GET["screen_name"]);
3480 $user_info = api_get_user($a);
3481 $profile_url = $user_info["url"];
3484 $start = $page * $count;
3487 if ($box=="sentbox") {
3488 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3489 } elseif ($box == "conversation") {
3490 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3491 } elseif ($box == "all") {
3492 $sql_extra = "true";
3493 } elseif ($box == "inbox") {
3494 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3498 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3501 if ($user_id != "") {
3502 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3503 } elseif ($screen_name !="") {
3504 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3508 "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",
3514 if ($verbose == "true" && !DBM::is_result($r)) {
3515 $answer = array('result' => 'error', 'message' => 'no mails available');
3516 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3520 foreach ($r as $item) {
3521 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3522 $recipient = $user_info;
3523 $sender = api_get_user($a, normalise_link($item['contact-url']));
3524 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3525 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3526 $sender = $user_info;
3529 $ret[] = api_format_messages($item, $recipient, $sender);
3533 $data = array('direct_message' => $ret);
3537 $data = api_rss_extra($a, $data, $user_info);
3540 return api_format_data("direct-messages", $type, $data);
3543 function api_direct_messages_sentbox($type)
3545 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3546 return api_direct_messages_box($type, "sentbox", $verbose);
3549 function api_direct_messages_inbox($type)
3551 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3552 return api_direct_messages_box($type, "inbox", $verbose);
3555 function api_direct_messages_all($type)
3557 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3558 return api_direct_messages_box($type, "all", $verbose);
3561 function api_direct_messages_conversation($type)
3563 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3564 return api_direct_messages_box($type, "conversation", $verbose);
3567 /// @TODO move to top of file or somewhere better
3568 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3569 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3570 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3571 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3573 function api_oauth_request_token($type)
3575 $oauth1 = new FKOAuth1();
3577 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3578 } catch (Exception $e) {
3579 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3586 function api_oauth_access_token($type)
3588 $oauth1 = new FKOAuth1();
3590 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3591 } catch (Exception $e) {
3592 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3599 /// @TODO move to top of file or somewhere better
3600 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3601 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3605 * @brief delete a complete photoalbum with all containing photos from database through api
3607 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3610 function api_fr_photoalbum_delete($type)
3612 if (api_user() === false) {
3613 throw new ForbiddenException();
3616 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3618 // we do not allow calls without album string
3620 throw new BadRequestException("no albumname specified");
3622 // check if album is existing
3624 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3628 if (!DBM::is_result($r))
3629 throw new BadRequestException("album not available");
3631 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3632 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3633 foreach ($r as $rr) {
3635 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3636 intval(local_user()),
3637 dbesc($rr['resource-id'])
3640 if (!DBM::is_result($photo_item)) {
3641 throw new InternalServerErrorException("problem with deleting items occured");
3643 drop_item($photo_item[0]['id'], false);
3646 // now let's delete all photos from the album
3647 $result = dba::delete('photo', array('uid' => api_user(), 'album' => $album));
3649 // return success of deletion or error message
3651 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3652 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3654 throw new InternalServerErrorException("unknown error - deleting from database failed");
3659 * @brief update the name of the album for all photos of an album
3661 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3664 function api_fr_photoalbum_update($type)
3666 if (api_user() === false) {
3667 throw new ForbiddenException();
3670 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3671 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3673 // we do not allow calls without album string
3675 throw new BadRequestException("no albumname specified");
3677 if ($album_new == "") {
3678 throw new BadRequestException("no new albumname specified");
3680 // check if album is existing
3682 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3686 if (!DBM::is_result($r)) {
3687 throw new BadRequestException("album not available");
3689 // now let's update all photos to the albumname
3691 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3697 // return success of updating or error message
3699 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3700 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3702 throw new InternalServerErrorException("unknown error - updating in database failed");
3708 * @brief list all photos of the authenticated user
3710 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3713 function api_fr_photos_list($type)
3715 if (api_user() === false) {
3716 throw new ForbiddenException();
3719 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3720 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3721 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3722 intval(local_user())
3725 'image/jpeg' => 'jpg',
3726 'image/png' => 'png',
3727 'image/gif' => 'gif'
3729 $data = array('photo'=>array());
3730 if (DBM::is_result($r)) {
3731 foreach ($r as $rr) {
3733 $photo['id'] = $rr['resource-id'];
3734 $photo['album'] = $rr['album'];
3735 $photo['filename'] = $rr['filename'];
3736 $photo['type'] = $rr['type'];
3737 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3738 $photo['created'] = $rr['created'];
3739 $photo['edited'] = $rr['edited'];
3740 $photo['desc'] = $rr['desc'];
3742 if ($type == "xml") {
3743 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3745 $photo['thumb'] = $thumb;
3746 $data['photo'][] = $photo;
3750 return api_format_data("photos", $type, $data);
3754 * @brief upload a new photo or change an existing photo
3756 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3759 function api_fr_photo_create_update($type)
3761 if (api_user() === false) {
3762 throw new ForbiddenException();
3765 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3766 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3767 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3768 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3769 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3770 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3771 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3772 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3773 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3775 // do several checks on input parameters
3776 // we do not allow calls without album string
3777 if ($album == null) {
3778 throw new BadRequestException("no albumname specified");
3780 // if photo_id == null --> we are uploading a new photo
3781 if ($photo_id == null) {
3784 // error if no media posted in create-mode
3785 if (!x($_FILES, 'media')) {
3787 throw new BadRequestException("no media data submitted");
3790 // album_new will be ignored in create-mode
3795 // check if photo is existing in database
3797 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3802 if (!DBM::is_result($r)) {
3803 throw new BadRequestException("photo not available");
3807 // checks on acl strings provided by clients
3808 $acl_input_error = false;
3809 $acl_input_error |= check_acl_input($allow_cid);
3810 $acl_input_error |= check_acl_input($deny_cid);
3811 $acl_input_error |= check_acl_input($allow_gid);
3812 $acl_input_error |= check_acl_input($deny_gid);
3813 if ($acl_input_error) {
3814 throw new BadRequestException("acl data invalid");
3816 // now let's upload the new media in create-mode
3817 if ($mode == "create") {
3818 $media = $_FILES['media'];
3819 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3821 // return success of updating or error message
3822 if (!is_null($data)) {
3823 return api_format_data("photo_create", $type, $data);
3825 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3829 // now let's do the changes in update-mode
3830 if ($mode == "update") {
3833 if (!is_null($desc)) {
3834 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3837 if (!is_null($album_new)) {
3838 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3841 if (!is_null($allow_cid)) {
3842 $allow_cid = trim($allow_cid);
3843 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3846 if (!is_null($deny_cid)) {
3847 $deny_cid = trim($deny_cid);
3848 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3851 if (!is_null($allow_gid)) {
3852 $allow_gid = trim($allow_gid);
3853 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3856 if (!is_null($deny_gid)) {
3857 $deny_gid = trim($deny_gid);
3858 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3862 if ($sql_extra != "") {
3863 $nothingtodo = false;
3865 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3867 datetime_convert(), // update edited timestamp
3873 $nothingtodo = true;
3876 if (x($_FILES, 'media')) {
3877 $nothingtodo = false;
3878 $media = $_FILES['media'];
3879 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3880 if (!is_null($data)) {
3881 return api_format_data("photo_update", $type, $data);
3885 // return success of updating or error message
3887 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
3888 return api_format_data("photo_update", $type, array('$result' => $answer));
3891 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
3892 return api_format_data("photo_update", $type, array('$result' => $answer));
3894 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3897 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3902 * @brief delete a single photo from the database through api
3904 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3907 function api_fr_photo_delete($type)
3909 if (api_user() === false) {
3910 throw new ForbiddenException();
3913 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3915 // do several checks on input parameters
3916 // we do not allow calls without photo id
3917 if ($photo_id == null) {
3918 throw new BadRequestException("no photo_id specified");
3920 // check if photo is existing in database
3922 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3926 if (!DBM::is_result($r)) {
3927 throw new BadRequestException("photo not available");
3929 // now we can perform on the deletion of the photo
3930 $result = dba::delete('photo', array('uid' => api_user(), 'resource-id' => $photo_id));
3932 // return success of deletion or error message
3934 // retrieve the id of the parent element (the photo element)
3936 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3937 intval(local_user()),
3941 if (!DBM::is_result($photo_item)) {
3942 throw new InternalServerErrorException("problem with deleting items occured");
3944 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3945 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
3946 drop_item($photo_item[0]['id'], false);
3948 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
3949 return api_format_data("photo_delete", $type, array('$result' => $answer));
3951 throw new InternalServerErrorException("unknown error on deleting photo from database table");
3957 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3959 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3962 function api_fr_photo_detail($type)
3964 if (api_user() === false) {
3965 throw new ForbiddenException();
3967 if (!x($_REQUEST, 'photo_id')) {
3968 throw new BadRequestException("No photo id.");
3971 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3972 $photo_id = $_REQUEST['photo_id'];
3974 // prepare json/xml output with data from database for the requested photo
3975 $data = prepare_photo_data($type, $scale, $photo_id);
3977 return api_format_data("photo_detail", $type, $data);
3982 * @brief updates the profile image for the user (either a specified profile or the default profile)
3984 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3987 function api_account_update_profile_image($type)
3989 if (api_user() === false) {
3990 throw new ForbiddenException();
3993 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
3995 // error if image data is missing
3996 if (!x($_FILES, 'image')) {
3997 throw new BadRequestException("no media data submitted");
4000 // check if specified profile id is valid
4001 if ($profileid != 0) {
4003 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4007 // error message if specified profile id is not in database
4008 if (!DBM::is_result($r)) {
4009 throw new BadRequestException("profile_id not available");
4011 $is_default_profile = $r['profile'];
4013 $is_default_profile = 1;
4016 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4018 if (x($_FILES, 'image')) {
4019 $media = $_FILES['image'];
4020 } elseif (x($_FILES, 'media')) {
4021 $media = $_FILES['media'];
4023 // save new profile image
4024 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4027 if (is_array($media['type'])) {
4028 $filetype = $media['type'][0];
4030 $filetype = $media['type'];
4032 if ($filetype == "image/jpeg") {
4034 } elseif ($filetype == "image/png") {
4037 // change specified profile or all profiles to the new resource-id
4038 if ($is_default_profile) {
4040 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4041 dbesc($data['photo']['id']),
4042 intval(local_user())
4046 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
4047 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4048 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4049 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4050 intval(local_user())
4054 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4055 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4056 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4057 intval($_REQUEST['profile']),
4058 intval(local_user())
4062 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4063 // so that browsers will do a cache update unconditionally
4066 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4067 dbesc(datetime_convert()),
4068 intval(local_user())
4071 // Update global directory in background
4072 //$user = api_get_user(get_app());
4073 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4074 if ($url && strlen(Config::get('system', 'directory'))) {
4075 Worker::add(PRIORITY_LOW, "Directory", $url);
4078 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4080 // output for client
4082 return api_account_verify_credentials($type);
4084 // SaveMediaToDatabase failed for some reason
4085 throw new InternalServerErrorException("image upload failed");
4089 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4090 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4091 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4092 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4093 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4094 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4095 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4096 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4097 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4100 function check_acl_input($acl_string)
4102 if ($acl_string == null || $acl_string == " ") {
4105 $contact_not_found = false;
4107 // split <x><y><z> into array of cid's
4108 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4110 // check for each cid if it is available on server
4111 $cid_array = $array[0];
4112 foreach ($cid_array as $cid) {
4113 $cid = str_replace("<", "", $cid);
4114 $cid = str_replace(">", "", $cid);
4116 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4120 $contact_not_found |= !DBM::is_result($contact);
4122 return $contact_not_found;
4125 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)
4133 if (is_array($media)) {
4134 if (is_array($media['tmp_name'])) {
4135 $src = $media['tmp_name'][0];
4137 $src = $media['tmp_name'];
4139 if (is_array($media['name'])) {
4140 $filename = basename($media['name'][0]);
4142 $filename = basename($media['name']);
4144 if (is_array($media['size'])) {
4145 $filesize = intval($media['size'][0]);
4147 $filesize = intval($media['size']);
4149 if (is_array($media['type'])) {
4150 $filetype = $media['type'][0];
4152 $filetype = $media['type'];
4156 if ($filetype == "") {
4157 $filetype=Image::guessType($filename);
4159 $imagedata = getimagesize($src);
4161 $filetype = $imagedata['mime'];
4164 "File upload src: " . $src . " - filename: " . $filename .
4165 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG
4168 // check if there was a php upload error
4169 if ($filesize == 0 && $media['error'] == 1) {
4170 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4172 // check against max upload size within Friendica instance
4173 $maximagesize = Config::get('system', 'maximagesize');
4174 if (($maximagesize) && ($filesize > $maximagesize)) {
4175 $formattedBytes = formatBytes($maximagesize);
4176 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4179 // create Photo instance with the data of the image
4180 $imagedata = @file_get_contents($src);
4181 $Image = new Image($imagedata, $filetype);
4182 if (! $Image->isValid()) {
4183 throw new InternalServerErrorException("unable to process image data");
4186 // check orientation of image
4187 $Image->orient($src);
4190 // check max length of images on server
4191 $max_length = Config::get('system', 'max_image_length');
4192 if (! $max_length) {
4193 $max_length = MAX_IMAGE_LENGTH;
4195 if ($max_length > 0) {
4196 $Image->scaleDown($max_length);
4197 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4199 $width = $Image->getWidth();
4200 $height = $Image->getHeight();
4202 // create a new resource-id if not already provided
4203 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
4205 if ($mediatype == "photo") {
4206 // upload normal image (scales 0, 1, 2)
4207 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4209 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4211 logger("photo upload: image upload with scale 0 (original size) failed");
4213 if ($width > 640 || $height > 640) {
4214 $Image->scaleDown(640);
4215 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4217 logger("photo upload: image upload with scale 1 (640x640) failed");
4221 if ($width > 320 || $height > 320) {
4222 $Image->scaleDown(320);
4223 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4225 logger("photo upload: image upload with scale 2 (320x320) failed");
4228 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4229 } elseif ($mediatype == "profileimage") {
4230 // upload profile image (scales 4, 5, 6)
4231 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4233 if ($width > 175 || $height > 175) {
4234 $Image->scaleDown(175);
4235 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4237 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4241 if ($width > 80 || $height > 80) {
4242 $Image->scaleDown(80);
4243 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4245 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4249 if ($width > 48 || $height > 48) {
4250 $Image->scaleDown(48);
4251 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4253 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4256 $Image->__destruct();
4257 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4261 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4262 if ($photo_id == null && $mediatype == "photo") {
4263 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4265 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4266 return prepare_photo_data($type, false, $hash);
4268 throw new InternalServerErrorException("image upload failed");
4272 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4274 // get data about the api authenticated user
4275 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4276 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4279 $arr['guid'] = get_guid(32);
4280 $arr['uid'] = intval(api_user());
4282 $arr['parent-uri'] = $uri;
4283 $arr['type'] = 'photo';
4285 $arr['resource-id'] = $hash;
4286 $arr['contact-id'] = $owner_record[0]['id'];
4287 $arr['owner-name'] = $owner_record[0]['name'];
4288 $arr['owner-link'] = $owner_record[0]['url'];
4289 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4290 $arr['author-name'] = $owner_record[0]['name'];
4291 $arr['author-link'] = $owner_record[0]['url'];
4292 $arr['author-avatar'] = $owner_record[0]['thumb'];
4294 $arr['allow_cid'] = $allow_cid;
4295 $arr['allow_gid'] = $allow_gid;
4296 $arr['deny_cid'] = $deny_cid;
4297 $arr['deny_gid'] = $deny_gid;
4298 $arr['last-child'] = 1;
4299 $arr['visible'] = $visibility;
4303 'image/jpeg' => 'jpg',
4304 'image/png' => 'png',
4305 'image/gif' => 'gif'
4308 // adds link to the thumbnail scale photo
4309 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4310 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4313 // do the magic for storing the item in the database and trigger the federation to other contacts
4317 function prepare_photo_data($type, $scale, $photo_id)
4319 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4320 $data_sql = ($scale === false ? "" : "data, ");
4322 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4323 // clients needs to convert this in their way for further processing
4325 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4326 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4327 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4328 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4330 intval(local_user()),
4336 'image/jpeg' => 'jpg',
4337 'image/png' => 'png',
4338 'image/gif' => 'gif'
4341 // prepare output data for photo
4342 if (DBM::is_result($r)) {
4343 $data = array('photo' => $r[0]);
4344 $data['photo']['id'] = $data['photo']['resource-id'];
4345 if ($scale !== false) {
4346 $data['photo']['data'] = base64_encode($data['photo']['data']);
4348 unset($data['photo']['datasize']); //needed only with scale param
4350 if ($type == "xml") {
4351 $data['photo']['links'] = array();
4352 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4353 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4355 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4358 $data['photo']['link'] = array();
4359 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4361 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4362 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4366 unset($data['photo']['resource-id']);
4367 unset($data['photo']['minscale']);
4368 unset($data['photo']['maxscale']);
4370 throw new NotFoundException();
4373 // retrieve item element for getting activities (like, dislike etc.) related to photo
4375 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4376 intval(local_user()),
4379 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4381 // retrieve comments on photo
4383 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4384 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4385 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4386 `contact`.`id` AS `cid`
4388 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4389 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4390 WHERE `item`.`parent` = %d AND `item`.`visible`
4391 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4392 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4393 intval($item[0]['parent']),
4395 dbesc(ACTIVITY_POST)
4398 // prepare output of comments
4399 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4400 $comments = array();
4401 if ($type == "xml") {
4403 foreach ($commentData as $comment) {
4404 $comments[$k++ . ":comment"] = $comment;
4407 foreach ($commentData as $comment) {
4408 $comments[] = $comment;
4411 $data['photo']['friendica_comments'] = $comments;
4413 // include info if rights on photo and rights on item are mismatching
4414 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4415 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4416 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4417 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4418 $data['photo']['rights_mismatch'] = $rights_mismatch;
4425 * Similar as /mod/redir.php
4426 * redirect to 'url' after dfrn auth
4428 * Why this when there is mod/redir.php already?
4429 * This use api_user() and api_login()
4432 * c_url: url of remote contact to auth to
4433 * url: string, url to redirect after auth
4435 function api_friendica_remoteauth()
4437 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4438 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4440 if ($url === '' || $c_url === '') {
4441 throw new BadRequestException("Wrong parameters.");
4444 $c_url = normalise_link($c_url);
4449 "SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4454 if ((! DBM::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4455 throw new BadRequestException("Unknown contact");
4460 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4462 if ($r[0]['duplex'] && $r[0]['issued-id']) {
4463 $orig_id = $r[0]['issued-id'];
4464 $dfrn_id = '1:' . $orig_id;
4466 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4467 $orig_id = $r[0]['dfrn-id'];
4468 $dfrn_id = '0:' . $orig_id;
4471 $sec = random_string();
4474 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4475 VALUES( %d, %s, '%s', '%s', %d )",
4483 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4484 $dest = (($url) ? '&destination_url=' . $url : '');
4486 $r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4487 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4488 . '&type=profile&sec=' . $sec . $dest . $quiet
4491 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4494 * @brief Return the item shared, if the item contains only the [share] tag
4496 * @param array $item Sharer item
4497 * @return array Shared item or false if not a reshare
4499 function api_share_as_retweet(&$item)
4501 $body = trim($item["body"]);
4503 if (Diaspora::isReshare($body, false)===false) {
4507 /// @TODO "$1" should maybe mean '$1' ?
4508 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4510 * Skip if there is no shared message in there
4511 * we already checked this in diaspora::isReshare()
4512 * but better one more than one less...
4514 if ($body == $attributes) {
4519 // build the fake reshared item
4520 $reshared_item = $item;
4523 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4524 if ($matches[1] != "") {
4525 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4528 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4529 if ($matches[1] != "") {
4530 $author = $matches[1];
4534 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4535 if ($matches[1] != "") {
4536 $profile = $matches[1];
4539 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4540 if ($matches[1] != "") {
4541 $profile = $matches[1];
4545 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4546 if ($matches[1] != "") {
4547 $avatar = $matches[1];
4550 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4551 if ($matches[1] != "") {
4552 $avatar = $matches[1];
4556 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4557 if ($matches[1] != "") {
4558 $link = $matches[1];
4561 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4562 if ($matches[1] != "") {
4563 $link = $matches[1];
4567 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4568 if ($matches[1] != "")
4569 $posted = $matches[1];
4571 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4572 if ($matches[1] != "") {
4573 $posted = $matches[1];
4576 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4578 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4582 $reshared_item["body"] = $shared_body;
4583 $reshared_item["author-name"] = $author;
4584 $reshared_item["author-link"] = $profile;
4585 $reshared_item["author-avatar"] = $avatar;
4586 $reshared_item["plink"] = $link;
4587 $reshared_item["created"] = $posted;
4588 $reshared_item["edited"] = $posted;
4590 return $reshared_item;
4594 function api_get_nick($profile)
4597 - remove trailing junk from profile url
4598 - pump.io check has to check the website
4604 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4605 dbesc(normalise_link($profile))
4608 if (DBM::is_result($r)) {
4609 $nick = $r[0]["nick"];
4614 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4615 dbesc(normalise_link($profile))
4618 if (DBM::is_result($r)) {
4619 $nick = $r[0]["nick"];
4624 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4625 if ($friendica != $profile) {
4631 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4632 if ($diaspora != $profile) {
4638 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4639 if ($twitter != $profile) {
4646 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4647 if ($StatusnetHost != $profile) {
4648 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4649 if ($StatusnetUser != $profile) {
4650 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4651 $user = json_decode($UserData);
4653 $nick = $user->screen_name;
4659 // To-Do: look at the page if its really a pumpio site
4660 //if (!$nick == "") {
4661 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4662 // if ($pumpio != $profile)
4664 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4675 function api_in_reply_to($item)
4677 $in_reply_to = array();
4679 $in_reply_to['status_id'] = null;
4680 $in_reply_to['user_id'] = null;
4681 $in_reply_to['status_id_str'] = null;
4682 $in_reply_to['user_id_str'] = null;
4683 $in_reply_to['screen_name'] = null;
4685 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4686 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4687 intval($item['uid']),
4688 dbesc($item['thr-parent']));
4690 if (DBM::is_result($r)) {
4691 $in_reply_to['status_id'] = intval($r[0]['id']);
4693 $in_reply_to['status_id'] = intval($item['parent']);
4696 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4698 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4699 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4700 WHERE `item`.`id` = %d LIMIT 1",
4701 intval($in_reply_to['status_id'])
4704 if (DBM::is_result($r)) {
4705 if ($r[0]['nick'] == "") {
4706 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4709 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4710 $in_reply_to['user_id'] = intval($r[0]['id']);
4711 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4714 // There seems to be situation, where both fields are identical:
4715 // https://github.com/friendica/friendica/issues/1010
4716 // This is a bugfix for that.
4717 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4718 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4719 $in_reply_to['status_id'] = null;
4720 $in_reply_to['user_id'] = null;
4721 $in_reply_to['status_id_str'] = null;
4722 $in_reply_to['user_id_str'] = null;
4723 $in_reply_to['screen_name'] = null;
4727 return $in_reply_to;
4730 function api_clean_plain_items($Text)
4732 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4734 $Text = bb_CleanPictureLinks($Text);
4735 $URLSearchString = "^\[\]";
4737 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
4739 if ($include_entities == "true") {
4740 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
4743 // Simplify "attachment" element
4744 $Text = api_clean_attachments($Text);
4750 * @brief Removes most sharing information for API text export
4752 * @param string $body The original body
4754 * @return string Cleaned body
4756 function api_clean_attachments($body)
4758 $data = get_attachment_data($body);
4765 if (isset($data["text"]))
4766 $body = $data["text"];
4768 if (($body == "") && (isset($data["title"])))
4769 $body = $data["title"];
4771 if (isset($data["url"]))
4772 $body .= "\n".$data["url"];
4774 $body .= $data["after"];
4779 function api_best_nickname(&$contacts)
4781 $best_contact = array();
4783 if (count($contact) == 0)
4786 foreach ($contacts as $contact)
4787 if ($contact["network"] == "") {
4788 $contact["network"] = "dfrn";
4789 $best_contact = array($contact);
4792 if (sizeof($best_contact) == 0)
4793 foreach ($contacts as $contact)
4794 if ($contact["network"] == "dfrn")
4795 $best_contact = array($contact);
4797 if (sizeof($best_contact) == 0)
4798 foreach ($contacts as $contact)
4799 if ($contact["network"] == "dspr")
4800 $best_contact = array($contact);
4802 if (sizeof($best_contact) == 0)
4803 foreach ($contacts as $contact)
4804 if ($contact["network"] == "stat")
4805 $best_contact = array($contact);
4807 if (sizeof($best_contact) == 0)
4808 foreach ($contacts as $contact)
4809 if ($contact["network"] == "pump")
4810 $best_contact = array($contact);
4812 if (sizeof($best_contact) == 0)
4813 foreach ($contacts as $contact)
4814 if ($contact["network"] == "twit")
4815 $best_contact = array($contact);
4817 if (sizeof($best_contact) == 1) {
4818 $contacts = $best_contact;
4820 $contacts = array($contacts[0]);
4824 // return all or a specified group of the user with the containing contacts
4825 function api_friendica_group_show($type)
4829 if (api_user() === false) throw new ForbiddenException();
4832 $user_info = api_get_user($a);
4833 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4834 $uid = $user_info['uid'];
4836 // get data of the specified group id or all groups if not specified
4839 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4843 // error message if specified gid is not in database
4844 if (!DBM::is_result($r))
4845 throw new BadRequestException("gid not available");
4848 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4853 // loop through all groups and retrieve all members for adding data in the user array
4854 foreach ($r as $rr) {
4855 $members = Contact::getByGroupId($rr['id']);
4858 if ($type == "xml") {
4859 $user_element = "users";
4861 foreach ($members as $member) {
4862 $user = api_get_user($a, $member['nurl']);
4863 $users[$k++.":user"] = $user;
4866 $user_element = "user";
4867 foreach ($members as $member) {
4868 $user = api_get_user($a, $member['nurl']);
4872 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4874 return api_format_data("groups", $type, array('group' => $grps));
4876 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4879 // delete the specified group of the user
4880 function api_friendica_group_delete($type)
4884 if (api_user() === false) {
4885 throw new ForbiddenException();
4889 $user_info = api_get_user($a);
4890 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4891 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4892 $uid = $user_info['uid'];
4894 // error if no gid specified
4895 if ($gid == 0 || $name == "") {
4896 throw new BadRequestException('gid or name not specified');
4899 // get data of the specified group id
4901 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
4905 // error message if specified gid is not in database
4906 if (!DBM::is_result($r)) {
4907 throw new BadRequestException('gid not available');
4910 // get data of the specified group id and group name
4912 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
4917 // error message if specified gid is not in database
4918 if (!DBM::is_result($rname)) {
4919 throw new BadRequestException('wrong group name');
4923 $ret = Group::removeByName($uid, $name);
4926 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
4927 return api_format_data("group_delete", $type, array('result' => $success));
4929 throw new BadRequestException('other API error');
4932 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4935 // create the specified group with the posted array of contacts
4936 function api_friendica_group_create($type)
4940 if (api_user() === false) throw new ForbiddenException();
4943 $user_info = api_get_user($a);
4944 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4945 $uid = $user_info['uid'];
4946 $json = json_decode($_POST['json'], true);
4947 $users = $json['user'];
4949 // error if no name specified
4951 throw new BadRequestException('group name not specified');
4953 // get data of the specified group name
4955 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
4959 // error message if specified group name already exists
4960 if (DBM::is_result($rname))
4961 throw new BadRequestException('group name already exists');
4963 // check if specified group name is a deleted group
4965 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
4969 // error message if specified group name already exists
4970 if (DBM::is_result($rname))
4971 $reactivate_group = true;
4974 $ret = Group::create($uid, $name);
4976 $gid = Group::getIdByName($uid, $name);
4978 throw new BadRequestException('other API error');
4982 $erroraddinguser = false;
4983 $errorusers = array();
4984 foreach ($users as $user) {
4985 $cid = $user['cid'];
4986 // check if user really exists as contact
4988 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4992 if (count($contact))
4993 $result = Group::addMember($gid, $cid);
4995 $erroraddinguser = true;
4996 $errorusers[] = $cid;
5000 // return success message incl. missing users in array
5001 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
5002 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
5003 return api_format_data("group_create", $type, array('result' => $success));
5005 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5008 // update the specified group with the posted array of contacts
5009 function api_friendica_group_update($type)
5013 if (api_user() === false) throw new ForbiddenException();
5016 $user_info = api_get_user($a);
5017 $uid = $user_info['uid'];
5018 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5019 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5020 $json = json_decode($_POST['json'], true);
5021 $users = $json['user'];
5023 // error if no name specified
5025 throw new BadRequestException('group name not specified');
5027 // error if no gid specified
5029 throw new BadRequestException('gid not specified');
5032 $members = Contact::getByGroupId($gid);
5033 foreach ($members as $member) {
5034 $cid = $member['id'];
5035 foreach ($users as $user) {
5036 $found = ($user['cid'] == $cid ? true : false);
5039 $ret = Group::removeMemberByName($uid, $name, $cid);
5044 $erroraddinguser = false;
5045 $errorusers = array();
5046 foreach ($users as $user) {
5047 $cid = $user['cid'];
5048 // check if user really exists as contact
5050 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5055 if (count($contact)) {
5056 $result = Group::addMember($gid, $cid);
5058 $erroraddinguser = true;
5059 $errorusers[] = $cid;
5063 // return success message incl. missing users in array
5064 $status = ($erroraddinguser ? "missing user" : "ok");
5065 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
5066 return api_format_data("group_update", $type, array('result' => $success));
5069 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5071 function api_friendica_activity($type)
5075 if (api_user() === false) throw new ForbiddenException();
5076 $verb = strtolower($a->argv[3]);
5077 $verb = preg_replace("|\..*$|", "", $verb);
5079 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5081 $res = do_like($id, $verb);
5084 if ($type == "xml") {
5089 return api_format_data('ok', $type, array('ok' => $ok));
5091 throw new BadRequestException('Error adding activity');
5095 /// @TODO move to top of file or somwhere better
5096 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5097 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5098 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5099 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5100 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5101 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5102 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5103 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5104 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5105 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5108 * @brief Returns notifications
5110 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5113 function api_friendica_notification($type)
5117 if (api_user() === false) throw new ForbiddenException();
5118 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
5119 $nm = new NotificationsManager();
5121 $notes = $nm->getAll(array(), "+seen -date", 50);
5123 if ($type == "xml") {
5124 $xmlnotes = array();
5125 foreach ($notes as $note)
5126 $xmlnotes[] = array("@attributes" => $note);
5131 return api_format_data("notes", $type, array('note' => $notes));
5135 * @brief Set notification as seen and returns associated item (if possible)
5137 * POST request with 'id' param as notification id
5139 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5142 function api_friendica_notification_seen($type)
5146 if (api_user() === false) throw new ForbiddenException();
5147 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
5149 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5151 $nm = new NotificationsManager();
5152 $note = $nm->getByID($id);
5153 if (is_null($note)) throw new BadRequestException("Invalid argument");
5155 $nm->setSeen($note);
5156 if ($note['otype']=='item') {
5157 // would be really better with an ItemsManager and $im->getByID() :-P
5159 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5160 intval($note['iid']),
5161 intval(local_user())
5164 // we found the item, return it to the user
5165 $user_info = api_get_user($a);
5166 $ret = api_format_items($r, $user_info, false, $type);
5167 $data = array('status' => $ret);
5168 return api_format_data("status", $type, $data);
5170 // the item can't be found, but we set the note as seen, so we count this as a success
5172 return api_format_data('result', $type, array('result' => "success"));
5175 /// @TODO move to top of file or somwhere better
5176 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5177 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5180 * @brief update a direct_message to seen state
5182 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5183 * @return string (success result=ok, error result=error with error message)
5185 function api_friendica_direct_messages_setseen($type)
5188 if (api_user() === false) {
5189 throw new ForbiddenException();
5193 $user_info = api_get_user($a);
5194 $uid = $user_info['uid'];
5195 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5197 // return error if id is zero
5199 $answer = array('result' => 'error', 'message' => 'message id not specified');
5200 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5203 // get data of the specified message id
5205 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5210 // error message if specified id is not in database
5211 if (!DBM::is_result($r)) {
5212 $answer = array('result' => 'error', 'message' => 'message id not in database');
5213 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5216 // update seen indicator
5218 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5225 $answer = array('result' => 'ok', 'message' => 'message set to seen');
5226 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
5228 $answer = array('result' => 'error', 'message' => 'unknown error');
5229 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5233 /// @TODO move to top of file or somwhere better
5234 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5237 * @brief search for direct_messages containing a searchstring through api
5239 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5240 * @return string (success: success=true if found and search_result contains found messages
5241 * success=false if nothing was found, search_result='nothing found',
5242 * error: result=error with error message)
5244 function api_friendica_direct_messages_search($type)
5248 if (api_user() === false) {
5249 throw new ForbiddenException();
5253 $user_info = api_get_user($a);
5254 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5255 $uid = $user_info['uid'];
5257 // error if no searchstring specified
5258 if ($searchstring == "") {
5259 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
5260 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
5263 // get data for the specified searchstring
5265 "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",
5267 dbesc('%'.$searchstring.'%')
5270 $profile_url = $user_info["url"];
5272 // message if nothing was found
5273 if (!DBM::is_result($r)) {
5274 $success = array('success' => false, 'search_results' => 'problem with query');
5275 } elseif (count($r) == 0) {
5276 $success = array('success' => false, 'search_results' => 'nothing found');
5279 foreach ($r as $item) {
5280 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5281 $recipient = $user_info;
5282 $sender = api_get_user($a, normalise_link($item['contact-url']));
5283 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5284 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5285 $sender = $user_info;
5288 $ret[] = api_format_messages($item, $recipient, $sender);
5290 $success = array('success' => true, 'search_results' => $ret);
5293 return api_format_data("direct_message_search", $type, array('$result' => $success));
5296 /// @TODO move to top of file or somwhere better
5297 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5300 * @brief return data of all the profiles a user has to the client
5302 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5305 function api_friendica_profile_show($type)
5309 if (api_user() === false) {
5310 throw new ForbiddenException();
5314 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5316 // retrieve general information about profiles for user
5317 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5318 $directory = Config::get('system', 'directory');
5320 // get data of the specified profile id or all profiles of the user if not specified
5321 if ($profileid != 0) {
5323 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5328 // error message if specified gid is not in database
5329 if (!DBM::is_result($r)) {
5330 throw new BadRequestException("profile_id not available");
5334 "SELECT * FROM `profile` WHERE `uid` = %d",
5338 // loop through all returned profiles and retrieve data and users
5340 foreach ($r as $rr) {
5341 $profile = api_format_items_profiles($rr, $type);
5343 // select all users from contact table, loop and prepare standard return for user data
5346 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5348 intval($rr['profile_id'])
5351 foreach ($r as $rr) {
5352 $user = api_get_user($a, $rr['nurl']);
5353 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5355 $profile['users'] = $users;
5357 // add prepared profile data to array for final return
5358 if ($type == "xml") {
5359 $profiles[$k++ . ":profile"] = $profile;
5361 $profiles[] = $profile;
5365 // return settings, authenticated user and profiles data
5366 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5368 $result = array('multi_profiles' => $multi_profiles ? true : false,
5369 'global_dir' => $directory,
5370 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5371 'profiles' => $profiles);
5372 return api_format_data("friendica_profiles", $type, array('$result' => $result));
5374 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5377 @TODO Maybe open to implement?
5379 [pagename] => api/1.1/statuses/lookup.json
5380 [id] => 605138389168451584
5381 [include_cards] => true
5382 [cards_platform] => Android-12
5383 [include_entities] => true
5384 [include_my_retweet] => 1
5386 [include_reply_count] => true
5387 [include_descendent_reply_count] => true
5391 Not implemented by now:
5392 statuses/retweets_of_me
5397 account/update_location
5398 account/update_profile_background_image
5401 friendica/profile/update
5402 friendica/profile/create
5403 friendica/profile/delete
5405 Not implemented in status.net:
5406 statuses/retweeted_to_me
5407 statuses/retweeted_by_me
5408 direct_messages/destroy
5410 account/update_delivery_device
5411 notifications/follow