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_url($id)
475 $r = dba::select('contact', array('url'), 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
489 * @param string $type Return type (for errors)
491 function api_get_user(App $a, $contact_id = null, $type = "json")
500 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
502 // Searching for contact URL
503 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
504 $user = dbesc(normalise_link($contact_id));
506 $extra_query = "AND `contact`.`nurl` = '%s' ";
507 if (api_user() !== false) {
508 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
512 // Searching for contact id with uid = 0
513 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
514 $user = dbesc(api_unique_id_to_url($contact_id));
517 throw new BadRequestException("User not found.");
521 $extra_query = "AND `contact`.`nurl` = '%s' ";
522 if (api_user() !== false) {
523 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
527 if (is_null($user) && x($_GET, 'user_id')) {
528 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
531 throw new BadRequestException("User not found.");
535 $extra_query = "AND `contact`.`nurl` = '%s' ";
536 if (api_user() !== false) {
537 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
540 if (is_null($user) && x($_GET, 'screen_name')) {
541 $user = dbesc($_GET['screen_name']);
543 $extra_query = "AND `contact`.`nick` = '%s' ";
544 if (api_user() !== false) {
545 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
549 if (is_null($user) && x($_GET, 'profileurl')) {
550 $user = dbesc(normalise_link($_GET['profileurl']));
552 $extra_query = "AND `contact`.`nurl` = '%s' ";
553 if (api_user() !== false) {
554 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
558 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
559 $argid = count($called_api);
560 list($user, $null) = explode(".", $a->argv[$argid]);
561 if (is_numeric($user)) {
562 $user = dbesc(api_unique_id_to_url($user));
569 $extra_query = "AND `contact`.`nurl` = '%s' ";
570 if (api_user() !== false) {
571 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
574 $user = dbesc($user);
576 $extra_query = "AND `contact`.`nick` = '%s' ";
577 if (api_user() !== false) {
578 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
583 logger("api_get_user: user ".$user, LOGGER_DEBUG);
586 if (api_user() === false) {
590 $user = $_SESSION['uid'];
591 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
595 logger('api_user: ' . $extra_query . ', user: ' . $user);
599 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
605 // Selecting the id by priority, friendica first
606 api_best_nickname($uinfo);
608 // if the contact wasn't found, fetch it from the contacts with uid = 0
609 if (!DBM::is_result($uinfo)) {
613 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
616 if (DBM::is_result($r)) {
617 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
619 // If no nick where given, extract it from the address
620 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
621 $r[0]['nick'] = api_get_nick($r[0]["url"]);
626 'id_str' => (string) $r[0]["id"],
627 'name' => $r[0]["name"],
628 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
629 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
630 'description' => $r[0]["about"],
631 'profile_image_url' => $r[0]["micro"],
632 'profile_image_url_https' => $r[0]["micro"],
633 'url' => $r[0]["url"],
634 'protected' => false,
635 'followers_count' => 0,
636 'friends_count' => 0,
638 'created_at' => api_date($r[0]["created"]),
639 'favourites_count' => 0,
641 'time_zone' => 'UTC',
642 'geo_enabled' => false,
644 'statuses_count' => 0,
646 'contributors_enabled' => false,
647 'is_translator' => false,
648 'is_translation_enabled' => false,
649 'following' => false,
650 'follow_request_sent' => false,
651 'statusnet_blocking' => false,
652 'notifications' => false,
653 'statusnet_profile_url' => $r[0]["url"],
655 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
657 'network' => $r[0]["network"],
662 throw new BadRequestException("User not found.");
666 if ($uinfo[0]['self']) {
667 if ($uinfo[0]['network'] == "") {
668 $uinfo[0]['network'] = NETWORK_DFRN;
672 "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
676 "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
680 /// @TODO old-lost code? (twice)
681 // Counting is deactivated by now, due to performance issues
682 // count public wall messages
683 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
684 // intval($uinfo[0]['uid'])
686 //$countitms = $r[0]['count'];
689 // Counting is deactivated by now, due to performance issues
690 //$r = q("SELECT count(*) as `count` FROM `item`
691 // WHERE `contact-id` = %d",
692 // intval($uinfo[0]['id'])
694 //$countitms = $r[0]['count'];
698 /// @TODO old-lost code? (twice)
700 // Counting is deactivated by now, due to performance issues
702 $r = q("SELECT count(*) as `count` FROM `contact`
703 WHERE `uid` = %d AND `rel` IN ( %d, %d )
704 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
705 intval($uinfo[0]['uid']),
706 intval(CONTACT_IS_SHARING),
707 intval(CONTACT_IS_FRIEND)
709 $countfriends = $r[0]['count'];
711 $r = q("SELECT count(*) as `count` FROM `contact`
712 WHERE `uid` = %d AND `rel` IN ( %d, %d )
713 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
714 intval($uinfo[0]['uid']),
715 intval(CONTACT_IS_FOLLOWER),
716 intval(CONTACT_IS_FRIEND)
718 $countfollowers = $r[0]['count'];
720 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
721 intval($uinfo[0]['uid'])
723 $starred = $r[0]['count'];
726 if (! $uinfo[0]['self']) {
736 // Add a nick if it isn't present there
737 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
738 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
741 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
743 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
746 'id' => intval($pcontact_id),
747 'id_str' => (string) intval($pcontact_id),
748 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
749 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
750 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
751 'description' => (($profile) ? $profile[0]['pdesc'] : null),
752 'profile_image_url' => $uinfo[0]['micro'],
753 'profile_image_url_https' => $uinfo[0]['micro'],
754 'url' => $uinfo[0]['url'],
755 'protected' => false,
756 'followers_count' => intval($countfollowers),
757 'friends_count' => intval($countfriends),
759 'created_at' => api_date($uinfo[0]['created']),
760 'favourites_count' => intval($starred),
762 'time_zone' => 'UTC',
763 'geo_enabled' => false,
765 'statuses_count' => intval($countitms),
767 'contributors_enabled' => false,
768 'is_translator' => false,
769 'is_translation_enabled' => false,
770 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
771 'follow_request_sent' => false,
772 'statusnet_blocking' => false,
773 'notifications' => false,
775 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
776 'statusnet_profile_url' => $uinfo[0]['url'],
777 'uid' => intval($uinfo[0]['uid']),
778 'cid' => intval($uinfo[0]['cid']),
779 'self' => $uinfo[0]['self'],
780 'network' => $uinfo[0]['network'],
787 * @brief return api-formatted array for item's author and owner
789 * @param object $a App
790 * @param array $item item from db
791 * @return array(array:author, array:owner)
793 function api_item_get_user(App $a, $item)
795 $status_user = api_get_user($a, $item["author-link"]);
797 $status_user["protected"] = (($item["allow_cid"] != "") ||
798 ($item["allow_gid"] != "") ||
799 ($item["deny_cid"] != "") ||
800 ($item["deny_gid"] != "") ||
803 if ($item['thr-parent'] == $item['uri']) {
804 $owner_user = api_get_user($a, $item["owner-link"]);
806 $owner_user = $status_user;
809 return (array($status_user, $owner_user));
813 * @brief walks recursively through an array with the possibility to change value and key
815 * @param array $array The array to walk through
816 * @param string $callback The callback function
818 * @return array the transformed array
820 function api_walk_recursive(array &$array, callable $callback)
822 $new_array = array();
824 foreach ($array as $k => $v) {
826 if ($callback($v, $k)) {
827 $new_array[$k] = api_walk_recursive($v, $callback);
830 if ($callback($v, $k)) {
841 * @brief Callback function to transform the array in an array that can be transformed in a XML file
843 * @param mixed $item Array item value
844 * @param string $key Array key
846 * @return boolean Should the array item be deleted?
848 function api_reformat_xml(&$item, &$key)
850 if (is_bool($item)) {
851 $item = ($item ? "true" : "false");
854 if (substr($key, 0, 10) == "statusnet_") {
855 $key = "statusnet:".substr($key, 10);
856 } elseif (substr($key, 0, 10) == "friendica_") {
857 $key = "friendica:".substr($key, 10);
859 /// @TODO old-lost code?
861 // $key = "default:".$key;
867 * @brief Creates the XML from a JSON style array
869 * @param array $data JSON style array
870 * @param string $root_element Name of the root element
872 * @return string The XML data
874 function api_create_xml($data, $root_element)
876 $childname = key($data);
877 $data2 = array_pop($data);
880 $namespaces = array("" => "http://api.twitter.com",
881 "statusnet" => "http://status.net/schema/api/1/",
882 "friendica" => "http://friendi.ca/schema/api/1/",
883 "georss" => "http://www.georss.org/georss");
885 /// @todo Auto detection of needed namespaces
886 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
887 $namespaces = array();
890 if (is_array($data2)) {
891 api_walk_recursive($data2, "api_reformat_xml");
898 foreach ($data2 as $item) {
899 $data4[$i++.":".$childname] = $item;
905 $data3 = array($root_element => $data2);
907 $ret = XML::fromArray($data3, $xml, false, $namespaces);
912 * @brief Formats the data according to the data type
914 * @param string $root_element Name of the root element
915 * @param string $type Return type (atom, rss, xml, json)
916 * @param array $data JSON style array
918 * @return (string|object) XML data or JSON data
920 function api_format_data($root_element, $type, $data)
928 $ret = api_create_xml($data, $root_element);
943 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
944 * returns a 401 status code and an error message if not.
945 * http://developer.twitter.com/doc/get/account/verify_credentials
947 function api_account_verify_credentials($type)
952 if (api_user() === false) {
953 throw new ForbiddenException();
956 unset($_REQUEST["user_id"]);
957 unset($_GET["user_id"]);
959 unset($_REQUEST["screen_name"]);
960 unset($_GET["screen_name"]);
962 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
964 $user_info = api_get_user($a);
966 // "verified" isn't used here in the standard
967 unset($user_info["verified"]);
969 // - Adding last status
971 $user_info["status"] = api_status_show("raw");
972 if (!count($user_info["status"])) {
973 unset($user_info["status"]);
975 unset($user_info["status"]["user"]);
979 // "uid" and "self" are only needed for some internal stuff, so remove it from here
980 unset($user_info["uid"]);
981 unset($user_info["self"]);
983 return api_format_data("user", $type, array('user' => $user_info));
986 /// @TODO move to top of file or somwhere better
987 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
990 * Get data from $_POST or $_GET
992 function requestdata($k)
1003 /*Waitman Gobble Mod*/
1004 function api_statuses_mediap($type)
1008 if (api_user() === false) {
1009 logger('api_statuses_update: no user');
1010 throw new ForbiddenException();
1012 $user_info = api_get_user($a);
1014 $_REQUEST['type'] = 'wall';
1015 $_REQUEST['profile_uid'] = api_user();
1016 $_REQUEST['api_source'] = true;
1017 $txt = requestdata('status');
1018 /// @TODO old-lost code?
1019 //$txt = urldecode(requestdata('status'));
1021 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1022 $txt = html2bb_video($txt);
1023 $config = HTMLPurifier_Config::createDefault();
1024 $config->set('Cache.DefinitionImpl', null);
1025 $purifier = new HTMLPurifier($config);
1026 $txt = $purifier->purify($txt);
1028 $txt = html2bbcode($txt);
1030 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1032 // tell wall_upload function to return img info instead of echo
1033 $_REQUEST['hush'] = 'yeah';
1034 $bebop = wall_upload_post($a);
1036 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1037 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1040 // this should output the last post (the one we just posted).
1041 return api_status_show($type);
1044 /// @TODO move this to top of file or somewhere better!
1045 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1047 function api_statuses_update($type)
1052 if (api_user() === false) {
1053 logger('api_statuses_update: no user');
1054 throw new ForbiddenException();
1057 $user_info = api_get_user($a);
1059 // convert $_POST array items to the form we use for web posts.
1061 // logger('api_post: ' . print_r($_POST,true));
1063 if (requestdata('htmlstatus')) {
1064 $txt = requestdata('htmlstatus');
1065 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1066 $txt = html2bb_video($txt);
1068 $config = HTMLPurifier_Config::createDefault();
1069 $config->set('Cache.DefinitionImpl', null);
1071 $purifier = new HTMLPurifier($config);
1072 $txt = $purifier->purify($txt);
1074 $_REQUEST['body'] = html2bbcode($txt);
1077 $_REQUEST['body'] = requestdata('status');
1080 $_REQUEST['title'] = requestdata('title');
1082 $parent = requestdata('in_reply_to_status_id');
1084 // Twidere sends "-1" if it is no reply ...
1085 if ($parent == -1) {
1089 if (ctype_digit($parent)) {
1090 $_REQUEST['parent'] = $parent;
1092 $_REQUEST['parent_uri'] = $parent;
1095 if (requestdata('lat') && requestdata('long')) {
1096 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1098 $_REQUEST['profile_uid'] = api_user();
1101 $_REQUEST['type'] = 'net-comment';
1103 // Check for throttling (maximum posts per day, week and month)
1104 $throttle_day = Config::get('system', 'throttle_limit_day');
1105 if ($throttle_day > 0) {
1106 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1109 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1110 AND `created` > '%s' AND `id` = `parent`",
1115 if (DBM::is_result($r)) {
1116 $posts_day = $r[0]["posts_day"];
1121 if ($posts_day > $throttle_day) {
1122 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1123 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1124 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1128 $throttle_week = Config::get('system', 'throttle_limit_week');
1129 if ($throttle_week > 0) {
1130 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1133 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1134 AND `created` > '%s' AND `id` = `parent`",
1139 if (DBM::is_result($r)) {
1140 $posts_week = $r[0]["posts_week"];
1145 if ($posts_week > $throttle_week) {
1146 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1147 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1148 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1152 $throttle_month = Config::get('system', 'throttle_limit_month');
1153 if ($throttle_month > 0) {
1154 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1157 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1158 AND `created` > '%s' AND `id` = `parent`",
1163 if (DBM::is_result($r)) {
1164 $posts_month = $r[0]["posts_month"];
1169 if ($posts_month > $throttle_month) {
1170 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1171 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1172 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1176 $_REQUEST['type'] = 'wall';
1179 if (x($_FILES, 'media')) {
1180 // upload the image if we have one
1181 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1182 $media = wall_upload_post($a);
1183 if (strlen($media) > 0) {
1184 $_REQUEST['body'] .= "\n\n" . $media;
1188 // To-Do: Multiple IDs
1189 if (requestdata('media_ids')) {
1191 "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",
1192 intval(requestdata('media_ids')),
1195 if (DBM::is_result($r)) {
1196 $phototypes = Image::supportedTypes();
1197 $ext = $phototypes[$r[0]['type']];
1198 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1199 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1203 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1205 $_REQUEST['api_source'] = true;
1207 if (!x($_REQUEST, "source")) {
1208 $_REQUEST["source"] = api_source();
1211 // call out normal post function
1214 // this should output the last post (the one we just posted).
1215 return api_status_show($type);
1218 /// @TODO move to top of file or somwhere better
1219 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1220 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1222 function api_media_upload($type)
1226 if (api_user() === false) {
1228 throw new ForbiddenException();
1231 $user_info = api_get_user($a);
1233 if (!x($_FILES, 'media')) {
1235 throw new BadRequestException("No media.");
1238 $media = wall_upload_post($a, false);
1241 throw new InternalServerErrorException();
1244 $returndata = array();
1245 $returndata["media_id"] = $media["id"];
1246 $returndata["media_id_string"] = (string)$media["id"];
1247 $returndata["size"] = $media["size"];
1248 $returndata["image"] = array("w" => $media["width"],
1249 "h" => $media["height"],
1250 "image_type" => $media["type"]);
1252 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1254 return array("media" => $returndata);
1257 /// @TODO move to top of file or somwhere better
1258 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1260 function api_status_show($type)
1264 $user_info = api_get_user($a);
1266 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1268 if ($type == "raw") {
1269 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1274 // get last public wall message
1278 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1279 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1280 AND `item`.`type` != 'activity' $privacy_sql
1281 ORDER BY `item`.`id` DESC
1283 intval($user_info['cid']),
1285 dbesc($user_info['url']),
1286 dbesc(normalise_link($user_info['url'])),
1287 dbesc($user_info['url']),
1288 dbesc(normalise_link($user_info['url']))
1291 if (DBM::is_result($lastwall)) {
1292 $lastwall = $lastwall[0];
1294 $in_reply_to = api_in_reply_to($lastwall);
1296 $converted = api_convert_item($lastwall);
1298 if ($type == "xml") {
1299 $geo = "georss:point";
1304 $status_info = array(
1305 'created_at' => api_date($lastwall['created']),
1306 'id' => intval($lastwall['id']),
1307 'id_str' => (string) $lastwall['id'],
1308 'text' => $converted["text"],
1309 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1310 'truncated' => false,
1311 'in_reply_to_status_id' => $in_reply_to['status_id'],
1312 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1313 'in_reply_to_user_id' => $in_reply_to['user_id'],
1314 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1315 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1316 'user' => $user_info,
1318 'coordinates' => "",
1320 'contributors' => "",
1321 'is_quote_status' => false,
1322 'retweet_count' => 0,
1323 'favorite_count' => 0,
1324 'favorited' => $lastwall['starred'] ? true : false,
1325 'retweeted' => false,
1326 'possibly_sensitive' => false,
1328 'statusnet_html' => $converted["html"],
1329 'statusnet_conversation_id' => $lastwall['parent'],
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'],
1420 if (count($converted["attachments"]) > 0) {
1421 $user_info["status"]["attachments"] = $converted["attachments"];
1424 if (count($converted["entities"]) > 0) {
1425 $user_info["status"]["entities"] = $converted["entities"];
1428 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1429 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1432 if (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1433 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
1437 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1438 unset($user_info["uid"]);
1439 unset($user_info["self"]);
1441 return api_format_data("user", $type, array('user' => $user_info));
1444 /// @TODO move to top of file or somewhere better
1445 api_register_func('api/users/show', 'api_users_show');
1446 api_register_func('api/externalprofile/show', 'api_users_show');
1448 function api_users_search($type)
1452 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1454 $userlist = array();
1456 if (x($_GET, 'q')) {
1457 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1459 if (!DBM::is_result($r)) {
1460 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1463 if (DBM::is_result($r)) {
1465 foreach ($r as $user) {
1466 $user_info = api_get_user($a, $user["id"], "json");
1468 if ($type == "xml") {
1469 $userlist[$k++.":user"] = $user_info;
1471 $userlist[] = $user_info;
1474 $userlist = array("users" => $userlist);
1476 throw new BadRequestException("User not found.");
1479 throw new BadRequestException("User not found.");
1481 return api_format_data("users", $type, $userlist);
1484 /// @TODO move to top of file or somewhere better
1485 api_register_func('api/users/search', 'api_users_search');
1489 * http://developer.twitter.com/doc/get/statuses/home_timeline
1491 * TODO: Optional parameters
1492 * TODO: Add reply info
1494 function api_statuses_home_timeline($type)
1498 if (api_user() === false) {
1499 throw new ForbiddenException();
1502 unset($_REQUEST["user_id"]);
1503 unset($_GET["user_id"]);
1505 unset($_REQUEST["screen_name"]);
1506 unset($_GET["screen_name"]);
1508 $user_info = api_get_user($a);
1509 // get last newtork messages
1512 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1513 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1517 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1518 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1519 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1520 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1521 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1523 $start = $page * $count;
1527 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1529 if ($exclude_replies > 0) {
1530 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1532 if ($conversation_id > 0) {
1533 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1537 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1538 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1539 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1540 `contact`.`id` AS `cid`
1542 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1543 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1544 WHERE `item`.`uid` = %d AND `verb` = '%s'
1545 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1548 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1550 dbesc(ACTIVITY_POST),
1556 $ret = api_format_items($r, $user_info, false, $type);
1558 // Set all posts from the query above to seen
1560 foreach ($r as $item) {
1561 $idarray[] = intval($item["id"]);
1564 $idlist = implode(",", $idarray);
1566 if ($idlist != "") {
1567 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1570 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1574 $data = array('status' => $ret);
1578 $data = api_rss_extra($a, $data, $user_info);
1582 return api_format_data("statuses", $type, $data);
1585 /// @TODO move to top of file or somewhere better
1586 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1587 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1589 function api_statuses_public_timeline($type)
1593 if (api_user() === false) {
1594 throw new ForbiddenException();
1597 $user_info = api_get_user($a);
1598 // get last newtork messages
1601 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1602 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1606 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1607 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1608 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1609 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1610 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1612 $start = $page * $count;
1615 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1617 if ($exclude_replies > 0) {
1618 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1620 if ($conversation_id > 0) {
1621 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1625 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1626 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1627 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1628 `contact`.`id` AS `cid`,
1629 `user`.`nickname`, `user`.`hidewall`
1631 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1632 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1633 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1634 AND NOT `user`.`hidewall`
1635 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1636 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1637 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1638 AND NOT `item`.`private` AND `item`.`wall`
1641 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1642 dbesc(ACTIVITY_POST),
1648 $ret = api_format_items($r, $user_info, false, $type);
1650 $data = array('status' => $ret);
1654 $data = api_rss_extra($a, $data, $user_info);
1658 return api_format_data("statuses", $type, $data);
1661 /// @TODO move to top of file or somewhere better
1662 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1665 * @brief Returns the list of public federated posts this node knows about
1667 * @param string $type Return format: json, xml, atom, rss
1668 * @return array|string
1669 * @throws ForbiddenException
1671 function api_statuses_networkpublic_timeline($type)
1675 if (api_user() === false) {
1676 throw new ForbiddenException();
1679 $user_info = api_get_user($a);
1681 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1682 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1685 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1686 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1690 $start = ($page - 1) * $count;
1694 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1697 $r = dba::p("SELECT " . item_fieldlists() . "
1699 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1700 " . item_joins() . "
1701 WHERE `thread`.`uid` = 0
1705 ORDER BY `thread`.`created` DESC
1706 LIMIT " . intval($start) . ", " . intval($count),
1711 $r = dba::inArray($r);
1713 $ret = api_format_items($r, $user_info, false, $type);
1715 $data = array('status' => $ret);
1719 $data = api_rss_extra($a, $data, $user_info);
1723 return api_format_data("statuses", $type, $data);
1726 /// @TODO move to top of file or somewhere better
1727 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1730 * @TODO nothing to say?
1732 function api_statuses_show($type)
1736 if (api_user() === false) {
1737 throw new ForbiddenException();
1740 $user_info = api_get_user($a);
1743 $id = intval($a->argv[3]);
1746 $id = intval($_REQUEST["id"]);
1751 $id = intval($a->argv[4]);
1754 logger('API: api_statuses_show: ' . $id);
1756 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1759 if ($conversation) {
1760 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1762 $sql_extra .= " AND `item`.`id` = %d";
1766 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1767 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1768 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1769 `contact`.`id` AS `cid`
1771 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1772 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1773 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1774 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1777 dbesc(ACTIVITY_POST),
1781 /// @TODO How about copying this to above methods which don't check $r ?
1782 if (!DBM::is_result($r)) {
1783 throw new BadRequestException("There is no status with this id.");
1786 $ret = api_format_items($r, $user_info, false, $type);
1788 if ($conversation) {
1789 $data = array('status' => $ret);
1790 return api_format_data("statuses", $type, $data);
1792 $data = array('status' => $ret[0]);
1793 return api_format_data("status", $type, $data);
1797 /// @TODO move to top of file or somewhere better
1798 api_register_func('api/statuses/show', 'api_statuses_show', true);
1801 * @TODO nothing to say?
1803 function api_conversation_show($type)
1807 if (api_user() === false) {
1808 throw new ForbiddenException();
1811 $user_info = api_get_user($a);
1814 $id = intval($a->argv[3]);
1815 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1816 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1820 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1821 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1823 $start = $page*$count;
1826 $id = intval($_REQUEST["id"]);
1831 $id = intval($a->argv[4]);
1834 logger('API: api_conversation_show: '.$id);
1836 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1837 if (DBM::is_result($r)) {
1838 $id = $r[0]["parent"];
1844 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1847 // Not sure why this query was so complicated. We should keep it here for a while,
1848 // just to make sure that we really don't need it.
1849 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1850 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1853 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1854 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1855 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1856 `contact`.`id` AS `cid`
1858 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1859 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1860 WHERE `item`.`parent` = %d AND `item`.`visible`
1861 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1862 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1863 AND `item`.`id`>%d $sql_extra
1864 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1865 intval($id), intval(api_user()),
1866 dbesc(ACTIVITY_POST),
1868 intval($start), intval($count)
1871 if (!DBM::is_result($r)) {
1872 throw new BadRequestException("There is no status with this id.");
1875 $ret = api_format_items($r, $user_info, false, $type);
1877 $data = array('status' => $ret);
1878 return api_format_data("statuses", $type, $data);
1881 /// @TODO move to top of file or somewhere better
1882 api_register_func('api/conversation/show', 'api_conversation_show', true);
1883 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1886 * @TODO nothing to say?
1888 function api_statuses_repeat($type)
1894 if (api_user() === false) {
1895 throw new ForbiddenException();
1898 $user_info = api_get_user($a);
1901 $id = intval($a->argv[3]);
1904 $id = intval($_REQUEST["id"]);
1909 $id = intval($a->argv[4]);
1912 logger('API: api_statuses_repeat: '.$id);
1915 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1916 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1917 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1918 `contact`.`id` AS `cid`
1920 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1921 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1922 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1923 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1924 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1926 AND `item`.`id`=%d",
1930 /// @TODO other style than above functions!
1931 if (DBM::is_result($r) && $r[0]['body'] != "") {
1932 if (strpos($r[0]['body'], "[/share]") !== false) {
1933 $pos = strpos($r[0]['body'], "[share");
1934 $post = substr($r[0]['body'], $pos);
1936 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1938 $post .= $r[0]['body'];
1939 $post .= "[/share]";
1941 $_REQUEST['body'] = $post;
1942 $_REQUEST['profile_uid'] = api_user();
1943 $_REQUEST['type'] = 'wall';
1944 $_REQUEST['api_source'] = true;
1946 if (!x($_REQUEST, "source")) {
1947 $_REQUEST["source"] = api_source();
1952 throw new ForbiddenException();
1955 // this should output the last post (the one we just posted).
1957 return api_status_show($type);
1960 /// @TODO move to top of file or somewhere better
1961 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1964 * @TODO nothing to say?
1966 function api_statuses_destroy($type)
1970 if (api_user() === false) {
1971 throw new ForbiddenException();
1974 $user_info = api_get_user($a);
1977 $id = intval($a->argv[3]);
1980 $id = intval($_REQUEST["id"]);
1985 $id = intval($a->argv[4]);
1988 logger('API: api_statuses_destroy: '.$id);
1990 $ret = api_statuses_show($type);
1992 drop_item($id, false);
1997 /// @TODO move to top of file or somewhere better
1998 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2001 * @TODO Nothing more than an URL to say?
2002 * http://developer.twitter.com/doc/get/statuses/mentions
2004 function api_statuses_mentions($type)
2008 if (api_user() === false) {
2009 throw new ForbiddenException();
2012 unset($_REQUEST["user_id"]);
2013 unset($_GET["user_id"]);
2015 unset($_REQUEST["screen_name"]);
2016 unset($_GET["screen_name"]);
2018 $user_info = api_get_user($a);
2019 // get last newtork messages
2023 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2024 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2028 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2029 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2030 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2032 $start = $page * $count;
2034 // Ugly code - should be changed
2035 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2036 $myurl = substr($myurl, strpos($myurl, '://') + 3);
2037 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
2038 $myurl = str_replace('www.', '', $myurl);
2039 $diasp_url = str_replace('/profile/', '/u/', $myurl);
2042 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2046 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2047 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2048 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2049 `contact`.`id` AS `cid`
2050 FROM `item` FORCE INDEX (`uid_id`)
2051 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2052 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2053 WHERE `item`.`uid` = %d AND `verb` = '%s'
2054 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2055 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2056 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2059 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2061 dbesc(ACTIVITY_POST),
2062 dbesc(protect_sprintf($myurl)),
2063 dbesc(protect_sprintf($myurl)),
2070 $ret = api_format_items($r, $user_info, false, $type);
2072 $data = array('status' => $ret);
2076 $data = api_rss_extra($a, $data, $user_info);
2080 return api_format_data("statuses", $type, $data);
2083 /// @TODO move to top of file or somewhere better
2084 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2085 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2088 * @brief Returns a user's public timeline
2090 * @param string $type Either "json" or "xml"
2091 * @return string|array
2092 * @throws ForbiddenException
2094 function api_statuses_user_timeline($type)
2098 if (api_user() === false) {
2099 throw new ForbiddenException();
2102 $user_info = api_get_user($a);
2105 "api_statuses_user_timeline: api_user: ". api_user() .
2106 "\nuser_info: ".print_r($user_info, true) .
2107 "\n_REQUEST: ".print_r($_REQUEST, true),
2111 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2112 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2113 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2114 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2117 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2118 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2122 $start = ($page - 1) * $count;
2125 if ($user_info['self'] == 1) {
2126 $sql_extra .= " AND `item`.`wall` = 1 ";
2129 if ($exclude_replies > 0) {
2130 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2133 if ($conversation_id > 0) {
2134 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2138 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2142 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2143 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2144 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2145 `contact`.`id` AS `cid`
2146 FROM `item` FORCE INDEX (`uid_contactid_id`)
2147 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2148 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2149 WHERE `item`.`uid` = %d AND `verb` = '%s'
2150 AND `item`.`contact-id` = %d
2151 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2153 AND `item`.`id` > %d
2154 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2156 dbesc(ACTIVITY_POST),
2157 intval($user_info['cid']),
2163 $ret = api_format_items($r, $user_info, true, $type);
2165 $data = array('status' => $ret);
2169 $data = api_rss_extra($a, $data, $user_info);
2173 return api_format_data("statuses", $type, $data);
2176 /// @TODO move to top of file or somwhere better
2177 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2180 * Star/unstar an item
2181 * param: id : id of the item
2183 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2185 function api_favorites_create_destroy($type)
2189 if (api_user() === false) {
2190 throw new ForbiddenException();
2193 // for versioned api.
2194 /// @TODO We need a better global soluton
2195 $action_argv_id = 2;
2196 if ($a->argv[1] == "1.1") {
2197 $action_argv_id = 3;
2200 if ($a->argc <= $action_argv_id) {
2201 throw new BadRequestException("Invalid request.");
2203 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2204 if ($a->argc == $action_argv_id + 2) {
2205 $itemid = intval($a->argv[$action_argv_id + 1]);
2207 /// @TODO use x() to check if _REQUEST contains 'id'
2208 $itemid = intval($_REQUEST['id']);
2211 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2213 if (!DBM::is_result($item) || count($item) == 0) {
2214 throw new BadRequestException("Invalid item.");
2219 $item[0]['starred'] = 1;
2222 $item[0]['starred'] = 0;
2225 throw new BadRequestException("Invalid action ".$action);
2228 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2230 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2233 throw new InternalServerErrorException("DB error");
2237 $user_info = api_get_user($a);
2238 $rets = api_format_items($item, $user_info, false, $type);
2241 $data = array('status' => $ret);
2245 $data = api_rss_extra($a, $data, $user_info);
2248 return api_format_data("status", $type, $data);
2251 /// @TODO move to top of file or somwhere better
2252 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2253 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2255 function api_favorites($type)
2261 if (api_user() === false) {
2262 throw new ForbiddenException();
2265 $called_api = array();
2267 $user_info = api_get_user($a);
2269 // in friendica starred item are private
2270 // return favorites only for self
2271 logger('api_favorites: self:' . $user_info['self']);
2273 if ($user_info['self'] == 0) {
2279 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2280 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2281 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2282 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2287 $start = $page*$count;
2290 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2294 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2295 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2296 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2297 `contact`.`id` AS `cid`
2298 FROM `item`, `contact`
2299 WHERE `item`.`uid` = %d
2300 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2301 AND `item`.`starred` = 1
2302 AND `contact`.`id` = `item`.`contact-id`
2303 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2306 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2313 $ret = api_format_items($r, $user_info, false, $type);
2316 $data = array('status' => $ret);
2320 $data = api_rss_extra($a, $data, $user_info);
2323 return api_format_data("statuses", $type, $data);
2326 /// @TODO move to top of file or somwhere better
2327 api_register_func('api/favorites', 'api_favorites', true);
2329 function api_format_messages($item, $recipient, $sender)
2331 // standard meta information
2333 'id' => $item['id'],
2334 'sender_id' => $sender['id'] ,
2336 'recipient_id' => $recipient['id'],
2337 'created_at' => api_date($item['created']),
2338 'sender_screen_name' => $sender['screen_name'],
2339 'recipient_screen_name' => $recipient['screen_name'],
2340 'sender' => $sender,
2341 'recipient' => $recipient,
2343 'friendica_seen' => $item['seen'],
2344 'friendica_parent_uri' => $item['parent-uri'],
2347 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2348 unset($ret["sender"]["uid"]);
2349 unset($ret["sender"]["self"]);
2350 unset($ret["recipient"]["uid"]);
2351 unset($ret["recipient"]["self"]);
2353 //don't send title to regular StatusNET requests to avoid confusing these apps
2354 if (x($_GET, 'getText')) {
2355 $ret['title'] = $item['title'];
2356 if ($_GET['getText'] == 'html') {
2357 $ret['text'] = bbcode($item['body'], false, false);
2358 } elseif ($_GET['getText'] == 'plain') {
2359 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2360 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2363 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2365 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2366 unset($ret['sender']);
2367 unset($ret['recipient']);
2373 function api_convert_item($item)
2375 $body = $item['body'];
2376 $attachments = api_get_attachments($body);
2378 // Workaround for ostatus messages where the title is identically to the body
2379 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2380 $statusbody = trim(html2plain($html, 0));
2382 // handle data: images
2383 $statusbody = api_format_items_embeded_images($item, $statusbody);
2385 $statustitle = trim($item['title']);
2387 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2388 $statustext = trim($statusbody);
2390 $statustext = trim($statustitle."\n\n".$statusbody);
2393 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2394 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2397 $statushtml = trim(bbcode($body, false, false));
2399 // Workaround for clients with limited HTML parser functionality
2400 $search = array("<br>", "<blockquote>", "</blockquote>",
2401 "<h1>", "</h1>", "<h2>", "</h2>",
2402 "<h3>", "</h3>", "<h4>", "</h4>",
2403 "<h5>", "</h5>", "<h6>", "</h6>");
2404 $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2405 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2406 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2407 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2408 $statushtml = str_replace($search, $replace, $statushtml);
2410 if ($item['title'] != "") {
2411 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2415 $oldtext = $statushtml;
2416 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2417 } while ($oldtext != $statushtml);
2419 if (substr($statushtml, 0, 4) == '<br>') {
2420 $statushtml = substr($statushtml, 4);
2423 if (substr($statushtml, 0, -4) == '<br>') {
2424 $statushtml = substr($statushtml, -4);
2427 // feeds without body should contain the link
2428 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2429 $statushtml .= bbcode($item['plink']);
2432 $entities = api_get_entitities($statustext, $body);
2435 "text" => $statustext,
2436 "html" => $statushtml,
2437 "attachments" => $attachments,
2438 "entities" => $entities
2442 function api_get_attachments(&$body)
2445 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2447 $URLSearchString = "^\[\]";
2448 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2454 $attachments = array();
2456 foreach ($images[1] as $image) {
2457 $imagedata = Image::getInfoFromURL($image);
2460 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2464 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2465 foreach ($images[0] as $orig) {
2466 $body = str_replace($orig, "", $body);
2470 return $attachments;
2473 function api_get_entitities(&$text, $bbcode)
2477 * Links at the first character of the post
2482 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2484 if ($include_entities != "true") {
2485 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2487 foreach ($images[1] as $image) {
2488 $replace = proxy_url($image);
2489 $text = str_replace($image, $replace, $text);
2494 $bbcode = bb_CleanPictureLinks($bbcode);
2496 // Change pure links in text to bbcode uris
2497 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2499 $entities = array();
2500 $entities["hashtags"] = array();
2501 $entities["symbols"] = array();
2502 $entities["urls"] = array();
2503 $entities["user_mentions"] = array();
2505 $URLSearchString = "^\[\]";
2507 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2509 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2510 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2511 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2513 $bbcode = preg_replace(
2514 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2515 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2518 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2520 $bbcode = preg_replace(
2521 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2522 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2525 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2527 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2529 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2530 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2532 $ordered_urls = array();
2533 foreach ($urls[1] as $id => $url) {
2534 //$start = strpos($text, $url, $offset);
2535 $start = iconv_strpos($text, $url, 0, "UTF-8");
2536 if (!($start === false)) {
2537 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2541 ksort($ordered_urls);
2544 //foreach ($urls[1] AS $id=>$url) {
2545 foreach ($ordered_urls as $url) {
2546 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2547 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2549 $display_url = $url["title"];
2551 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2552 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2554 if (strlen($display_url) > 26)
2555 $display_url = substr($display_url, 0, 25)."…";
2558 //$start = strpos($text, $url, $offset);
2559 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2560 if (!($start === false)) {
2561 $entities["urls"][] = array("url" => $url["url"],
2562 "expanded_url" => $url["url"],
2563 "display_url" => $display_url,
2564 "indices" => array($start, $start+strlen($url["url"])));
2565 $offset = $start + 1;
2569 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2570 $ordered_images = array();
2571 foreach ($images[1] as $image) {
2572 //$start = strpos($text, $url, $offset);
2573 $start = iconv_strpos($text, $image, 0, "UTF-8");
2574 if (!($start === false))
2575 $ordered_images[$start] = $image;
2577 //$entities["media"] = array();
2580 foreach ($ordered_images as $url) {
2581 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2582 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2584 if (strlen($display_url) > 26)
2585 $display_url = substr($display_url, 0, 25)."…";
2587 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2588 if (!($start === false)) {
2589 $image = Image::getInfoFromURL($url);
2591 // If image cache is activated, then use the following sizes:
2592 // thumb (150), small (340), medium (600) and large (1024)
2593 if (!Config::get("system", "proxy_disabled")) {
2594 $media_url = proxy_url($url);
2597 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2598 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2600 if (($image[0] > 150) || ($image[1] > 150)) {
2601 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2602 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2605 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2606 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2608 if (($image[0] > 600) || ($image[1] > 600)) {
2609 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2610 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2614 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2617 $entities["media"][] = array(
2619 "id_str" => (string)$start+1,
2620 "indices" => array($start, $start+strlen($url)),
2621 "media_url" => normalise_link($media_url),
2622 "media_url_https" => $media_url,
2624 "display_url" => $display_url,
2625 "expanded_url" => $url,
2629 $offset = $start + 1;
2635 function api_format_items_embeded_images(&$item, $text)
2637 $text = preg_replace_callback(
2638 "|data:image/([^;]+)[^=]+=*|m",
2639 function ($match) use ($item) {
2640 return System::baseUrl()."/display/".$item['guid'];
2649 * @brief return <a href='url'>name</a> as array
2651 * @param string $txt text
2656 function api_contactlink_to_array($txt)
2659 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2660 if ($r && count($match)==3) {
2662 'name' => $match[2],
2676 * @brief return likes, dislikes and attend status for item
2678 * @param array $item array
2680 * likes => int count
2681 * dislikes => int count
2683 function api_format_items_activities(&$item, $type = "json")
2687 $activities = array(
2689 'dislike' => array(),
2690 'attendyes' => array(),
2691 'attendno' => array(),
2692 'attendmaybe' => array(),
2697 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2698 intval($item['uid']),
2702 foreach ($items as $i) {
2703 // not used as result should be structured like other user data
2704 //builtin_activity_puller($i, $activities);
2706 // get user data and add it to the array of the activity
2707 $user = api_get_user($a, $i['author-link']);
2708 switch ($i['verb']) {
2710 $activities['like'][] = $user;
2712 case ACTIVITY_DISLIKE:
2713 $activities['dislike'][] = $user;
2715 case ACTIVITY_ATTEND:
2716 $activities['attendyes'][] = $user;
2718 case ACTIVITY_ATTENDNO:
2719 $activities['attendno'][] = $user;
2721 case ACTIVITY_ATTENDMAYBE:
2722 $activities['attendmaybe'][] = $user;
2729 if ($type == "xml") {
2730 $xml_activities = array();
2731 foreach ($activities as $k => $v) {
2732 // change xml element from "like" to "friendica:like"
2733 $xml_activities["friendica:".$k] = $v;
2734 // add user data into xml output
2736 foreach ($v as $user)
2737 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2739 $activities = $xml_activities;
2747 * @brief return data from profiles
2749 * @param array $profile array containing data from db table 'profile'
2750 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2753 function api_format_items_profiles(&$profile = null, $type = "json")
2755 if ($profile != null) {
2756 $profile = array('profile_id' => $profile['id'],
2757 'profile_name' => $profile['profile-name'],
2758 'is_default' => $profile['is-default'] ? true : false,
2759 'hide_friends'=> $profile['hide-friends'] ? true : false,
2760 'profile_photo' => $profile['photo'],
2761 'profile_thumb' => $profile['thumb'],
2762 'publish' => $profile['publish'] ? true : false,
2763 'net_publish' => $profile['net-publish'] ? true : false,
2764 'description' => $profile['pdesc'],
2765 'date_of_birth' => $profile['dob'],
2766 'address' => $profile['address'],
2767 'city' => $profile['locality'],
2768 'region' => $profile['region'],
2769 'postal_code' => $profile['postal-code'],
2770 'country' => $profile['country-name'],
2771 'hometown' => $profile['hometown'],
2772 'gender' => $profile['gender'],
2773 'marital' => $profile['marital'],
2774 'marital_with' => $profile['with'],
2775 'marital_since' => $profile['howlong'],
2776 'sexual' => $profile['sexual'],
2777 'politic' => $profile['politic'],
2778 'religion' => $profile['religion'],
2779 'public_keywords' => $profile['pub_keywords'],
2780 'private_keywords' => $profile['prv_keywords'],
2781 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2782 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2783 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2784 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2785 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2786 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2787 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2788 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2789 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2790 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2791 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2792 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2793 'homepage' => $profile['homepage'],
2800 * @brief format items to be returned by api
2802 * @param array $r array of items
2803 * @param array $user_info
2804 * @param bool $filter_user filter items by $user_info
2806 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2812 foreach ($r as $item) {
2813 localize_item($item);
2814 list($status_user, $owner_user) = api_item_get_user($a, $item);
2816 // Look if the posts are matching if they should be filtered by user id
2817 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2821 $in_reply_to = api_in_reply_to($item);
2823 $converted = api_convert_item($item);
2825 if ($type == "xml") {
2826 $geo = "georss:point";
2832 'text' => $converted["text"],
2833 'truncated' => false,
2834 'created_at'=> api_date($item['created']),
2835 'in_reply_to_status_id' => $in_reply_to['status_id'],
2836 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2837 'source' => (($item['app']) ? $item['app'] : 'web'),
2838 'id' => intval($item['id']),
2839 'id_str' => (string) intval($item['id']),
2840 'in_reply_to_user_id' => $in_reply_to['user_id'],
2841 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2842 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2844 'favorited' => $item['starred'] ? true : false,
2845 'user' => $status_user ,
2846 'friendica_owner' => $owner_user,
2847 //'entities' => NULL,
2848 'statusnet_html' => $converted["html"],
2849 'statusnet_conversation_id' => $item['parent'],
2850 'friendica_activities' => api_format_items_activities($item, $type),
2853 if (count($converted["attachments"]) > 0) {
2854 $status["attachments"] = $converted["attachments"];
2857 if (count($converted["entities"]) > 0) {
2858 $status["entities"] = $converted["entities"];
2861 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
2862 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2863 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2864 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2868 // Retweets are only valid for top postings
2869 // It doesn't work reliable with the link if its a feed
2870 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2872 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
2875 if ($item["id"] == $item["parent"]) {
2876 $retweeted_item = api_share_as_retweet($item);
2877 if ($retweeted_item !== false) {
2878 $retweeted_status = $status;
2880 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
2881 } catch (BadRequestException $e) {
2882 // user not found. should be found?
2883 /// @todo check if the user should be always found
2884 $retweeted_status["user"] = array();
2887 $rt_converted = api_convert_item($retweeted_item);
2889 $retweeted_status['text'] = $rt_converted["text"];
2890 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2891 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2892 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2893 $status['retweeted_status'] = $retweeted_status;
2897 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2898 unset($status["user"]["uid"]);
2899 unset($status["user"]["self"]);
2901 if ($item["coord"] != "") {
2902 $coords = explode(' ', $item["coord"]);
2903 if (count($coords) == 2) {
2904 if ($type == "json")
2905 $status["geo"] = array('type' => 'Point',
2906 'coordinates' => array((float) $coords[0],
2907 (float) $coords[1]));
2908 else // Not sure if this is the official format - if someone founds a documentation we can check
2909 $status["georss:point"] = $item["coord"];
2917 function api_account_rate_limit_status($type)
2919 if ($type == "xml") {
2921 'remaining-hits' => '150',
2922 '@attributes' => array("type" => "integer"),
2923 'hourly-limit' => '150',
2924 '@attributes2' => array("type" => "integer"),
2925 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
2926 '@attributes3' => array("type" => "datetime"),
2927 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2928 '@attributes4' => array("type" => "integer"),
2932 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2933 'remaining_hits' => '150',
2934 'hourly_limit' => '150',
2935 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
2939 return api_format_data('hash', $type, array('hash' => $hash));
2942 /// @TODO move to top of file or somwhere better
2943 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
2945 function api_help_test($type)
2947 if ($type == 'xml') {
2953 return api_format_data('ok', $type, array("ok" => $ok));
2956 /// @TODO move to top of file or somwhere better
2957 api_register_func('api/help/test', 'api_help_test', false);
2959 function api_lists($type)
2962 /// @TODO $ret is not filled here?
2963 return api_format_data('lists', $type, array("lists_list" => $ret));
2966 /// @TODO move to top of file or somwhere better
2967 api_register_func('api/lists', 'api_lists', true);
2969 function api_lists_list($type)
2972 /// @TODO $ret is not filled here?
2973 return api_format_data('lists', $type, array("lists_list" => $ret));
2976 /// @TODO move to top of file or somwhere better
2977 api_register_func('api/lists/list', 'api_lists_list', true);
2980 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2981 * This function is deprecated by Twitter
2982 * returns: json, xml
2984 function api_statuses_f($type, $qtype)
2988 if (api_user() === false) {
2989 throw new ForbiddenException();
2992 $user_info = api_get_user($a);
2994 if (x($_GET, 'cursor') && $_GET['cursor']=='undefined') {
2995 /* this is to stop Hotot to load friends multiple times
2996 * I'm not sure if I'm missing return something or
2997 * is a bug in hotot. Workaround, meantime
3001 return array('$users' => $ret);*/
3005 if ($qtype == 'friends') {
3006 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3008 if ($qtype == 'followers') {
3009 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3012 // friends and followers only for self
3013 if ($user_info['self'] == 0) {
3014 $sql_extra = " AND false ";
3018 "SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra ORDER BY `nick`",
3023 foreach ($r as $cid) {
3024 $user = api_get_user($a, $cid['nurl']);
3025 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3026 unset($user["uid"]);
3027 unset($user["self"]);
3034 return array('user' => $ret);
3038 function api_statuses_friends($type)
3040 $data = api_statuses_f($type, "friends");
3041 if ($data === false) {
3044 return api_format_data("users", $type, $data);
3047 function api_statuses_followers($type)
3049 $data = api_statuses_f($type, "followers");
3050 if ($data === false) {
3053 return api_format_data("users", $type, $data);
3056 /// @TODO move to top of file or somewhere better
3057 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3058 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3060 function api_statusnet_config($type)
3064 $name = $a->config['sitename'];
3065 $server = $a->get_hostname();
3066 $logo = System::baseUrl() . '/images/friendica-64.png';
3067 $email = $a->config['admin_email'];
3068 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3069 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3070 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3071 if ($a->config['api_import_size']) {
3072 $texlimit = string($a->config['api_import_size']);
3074 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3075 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3078 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3079 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3080 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3081 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3082 'shorturllength' => '30',
3083 'friendica' => array(
3084 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3085 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3086 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3087 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3092 return api_format_data('config', $type, array('config' => $config));
3095 /// @TODO move to top of file or somewhere better
3096 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3097 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3099 function api_statusnet_version($type)
3102 $fake_statusnet_version = "0.9.7";
3104 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
3107 /// @TODO move to top of file or somewhere better
3108 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3109 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3112 * @todo use api_format_data() to return data
3114 function api_ff_ids($type,$qtype)
3119 throw new ForbiddenException();
3122 $user_info = api_get_user($a);
3124 if ($qtype == 'friends') {
3125 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3127 if ($qtype == 'followers') {
3128 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3131 if (!$user_info["self"]) {
3132 $sql_extra = " AND false ";
3135 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3138 "SELECT `pcontact`.`id` FROM `contact`
3139 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3140 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3144 if (!DBM::is_result($r)) {
3149 foreach ($r as $rr) {
3150 if ($stringify_ids) {
3153 $ids[] = intval($rr['id']);
3157 return api_format_data("ids", $type, array('id' => $ids));
3160 function api_friends_ids($type)
3162 return api_ff_ids($type, 'friends');
3165 function api_followers_ids($type)
3167 return api_ff_ids($type, 'followers');
3170 /// @TODO move to top of file or somewhere better
3171 api_register_func('api/friends/ids', 'api_friends_ids', true);
3172 api_register_func('api/followers/ids', 'api_followers_ids', true);
3174 function api_direct_messages_new($type)
3179 if (api_user() === false) throw new ForbiddenException();
3181 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) return;
3183 $sender = api_get_user($a);
3185 if ($_POST['screen_name']) {
3187 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3189 dbesc($_POST['screen_name'])
3192 // Selecting the id by priority, friendica first
3193 api_best_nickname($r);
3195 $recipient = api_get_user($a, $r[0]['nurl']);
3197 $recipient = api_get_user($a, $_POST['user_id']);
3202 if (x($_REQUEST, 'replyto')) {
3204 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3206 intval($_REQUEST['replyto'])
3208 $replyto = $r[0]['parent-uri'];
3209 $sub = $r[0]['title'];
3211 if (x($_REQUEST, 'title')) {
3212 $sub = $_REQUEST['title'];
3214 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3218 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3221 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3222 $ret = api_format_messages($r[0], $recipient, $sender);
3224 $ret = array("error"=>$id);
3227 $data = array('direct_message'=>$ret);
3232 $data = api_rss_extra($a, $data, $user_info);
3235 return api_format_data("direct-messages", $type, $data);
3239 /// @TODO move to top of file or somewhere better
3240 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3243 * @brief delete a direct_message from mail table through api
3245 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3248 function api_direct_messages_destroy($type)
3252 if (api_user() === false) {
3253 throw new ForbiddenException();
3257 $user_info = api_get_user($a);
3259 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3261 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3262 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3263 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3265 $uid = $user_info['uid'];
3266 // error if no id or parenturi specified (for clients posting parent-uri as well)
3267 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3268 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3269 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3272 // BadRequestException if no id specified (for clients using Twitter API)
3274 throw new BadRequestException('Message id not specified');
3277 // add parent-uri to sql command if specified by calling app
3278 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3280 // get data of the specified message id
3282 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3287 // error message if specified id is not in database
3288 if (!DBM::is_result($r)) {
3289 if ($verbose == "true") {
3290 $answer = array('result' => 'error', 'message' => 'message id not in database');
3291 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3293 /// @todo BadRequestException ok for Twitter API clients?
3294 throw new BadRequestException('message id not in database');
3299 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3304 if ($verbose == "true") {
3307 $answer = array('result' => 'ok', 'message' => 'message deleted');
3308 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3310 $answer = array('result' => 'error', 'message' => 'unknown error');
3311 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3314 /// @todo return JSON data like Twitter API not yet implemented
3318 /// @TODO move to top of file or somewhere better
3319 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3321 function api_direct_messages_box($type, $box, $verbose)
3325 if (api_user() === false) {
3326 throw new ForbiddenException();
3330 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3331 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3336 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3337 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3339 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3340 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3343 unset($_REQUEST["user_id"]);
3344 unset($_GET["user_id"]);
3346 unset($_REQUEST["screen_name"]);
3347 unset($_GET["screen_name"]);
3349 $user_info = api_get_user($a);
3350 $profile_url = $user_info["url"];
3353 $start = $page * $count;
3356 if ($box=="sentbox") {
3357 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3358 } elseif ($box == "conversation") {
3359 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3360 } elseif ($box == "all") {
3361 $sql_extra = "true";
3362 } elseif ($box == "inbox") {
3363 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3367 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3370 if ($user_id != "") {
3371 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3372 } elseif ($screen_name !="") {
3373 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3377 "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",
3383 if ($verbose == "true" && !DBM::is_result($r)) {
3384 $answer = array('result' => 'error', 'message' => 'no mails available');
3385 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3389 foreach ($r as $item) {
3390 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3391 $recipient = $user_info;
3392 $sender = api_get_user($a, normalise_link($item['contact-url']));
3393 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3394 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3395 $sender = $user_info;
3398 $ret[] = api_format_messages($item, $recipient, $sender);
3402 $data = array('direct_message' => $ret);
3406 $data = api_rss_extra($a, $data, $user_info);
3409 return api_format_data("direct-messages", $type, $data);
3412 function api_direct_messages_sentbox($type)
3414 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3415 return api_direct_messages_box($type, "sentbox", $verbose);
3418 function api_direct_messages_inbox($type)
3420 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3421 return api_direct_messages_box($type, "inbox", $verbose);
3424 function api_direct_messages_all($type)
3426 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3427 return api_direct_messages_box($type, "all", $verbose);
3430 function api_direct_messages_conversation($type)
3432 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3433 return api_direct_messages_box($type, "conversation", $verbose);
3436 /// @TODO move to top of file or somewhere better
3437 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3438 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3439 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3440 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3442 function api_oauth_request_token($type)
3444 $oauth1 = new FKOAuth1();
3446 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3447 } catch (Exception $e) {
3448 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3455 function api_oauth_access_token($type)
3457 $oauth1 = new FKOAuth1();
3459 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3460 } catch (Exception $e) {
3461 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3468 /// @TODO move to top of file or somewhere better
3469 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3470 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3474 * @brief delete a complete photoalbum with all containing photos from database through api
3476 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3479 function api_fr_photoalbum_delete($type)
3481 if (api_user() === false) {
3482 throw new ForbiddenException();
3485 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3487 // we do not allow calls without album string
3489 throw new BadRequestException("no albumname specified");
3491 // check if album is existing
3493 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3497 if (!DBM::is_result($r))
3498 throw new BadRequestException("album not available");
3500 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3501 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3502 foreach ($r as $rr) {
3504 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3505 intval(local_user()),
3506 dbesc($rr['resource-id'])
3509 if (!DBM::is_result($photo_item)) {
3510 throw new InternalServerErrorException("problem with deleting items occured");
3512 drop_item($photo_item[0]['id'], false);
3515 // now let's delete all photos from the album
3516 $result = dba::delete('photo', array('uid' => api_user(), 'album' => $album));
3518 // return success of deletion or error message
3520 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3521 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3523 throw new InternalServerErrorException("unknown error - deleting from database failed");
3528 * @brief update the name of the album for all photos of an album
3530 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3533 function api_fr_photoalbum_update($type)
3535 if (api_user() === false) {
3536 throw new ForbiddenException();
3539 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3540 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3542 // we do not allow calls without album string
3544 throw new BadRequestException("no albumname specified");
3546 if ($album_new == "") {
3547 throw new BadRequestException("no new albumname specified");
3549 // check if album is existing
3551 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3555 if (!DBM::is_result($r)) {
3556 throw new BadRequestException("album not available");
3558 // now let's update all photos to the albumname
3560 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3566 // return success of updating or error message
3568 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3569 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3571 throw new InternalServerErrorException("unknown error - updating in database failed");
3577 * @brief list all photos of the authenticated user
3579 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3582 function api_fr_photos_list($type)
3584 if (api_user() === false) {
3585 throw new ForbiddenException();
3588 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3589 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3590 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3591 intval(local_user())
3594 'image/jpeg' => 'jpg',
3595 'image/png' => 'png',
3596 'image/gif' => 'gif'
3598 $data = array('photo'=>array());
3599 if (DBM::is_result($r)) {
3600 foreach ($r as $rr) {
3602 $photo['id'] = $rr['resource-id'];
3603 $photo['album'] = $rr['album'];
3604 $photo['filename'] = $rr['filename'];
3605 $photo['type'] = $rr['type'];
3606 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3607 $photo['created'] = $rr['created'];
3608 $photo['edited'] = $rr['edited'];
3609 $photo['desc'] = $rr['desc'];
3611 if ($type == "xml") {
3612 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3614 $photo['thumb'] = $thumb;
3615 $data['photo'][] = $photo;
3619 return api_format_data("photos", $type, $data);
3623 * @brief upload a new photo or change an existing photo
3625 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3628 function api_fr_photo_create_update($type)
3630 if (api_user() === false) {
3631 throw new ForbiddenException();
3634 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3635 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3636 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3637 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3638 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3639 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3640 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3641 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3642 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3644 // do several checks on input parameters
3645 // we do not allow calls without album string
3646 if ($album == null) {
3647 throw new BadRequestException("no albumname specified");
3649 // if photo_id == null --> we are uploading a new photo
3650 if ($photo_id == null) {
3653 // error if no media posted in create-mode
3654 if (!x($_FILES, 'media')) {
3656 throw new BadRequestException("no media data submitted");
3659 // album_new will be ignored in create-mode
3664 // check if photo is existing in database
3666 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3671 if (!DBM::is_result($r)) {
3672 throw new BadRequestException("photo not available");
3676 // checks on acl strings provided by clients
3677 $acl_input_error = false;
3678 $acl_input_error |= check_acl_input($allow_cid);
3679 $acl_input_error |= check_acl_input($deny_cid);
3680 $acl_input_error |= check_acl_input($allow_gid);
3681 $acl_input_error |= check_acl_input($deny_gid);
3682 if ($acl_input_error) {
3683 throw new BadRequestException("acl data invalid");
3685 // now let's upload the new media in create-mode
3686 if ($mode == "create") {
3687 $media = $_FILES['media'];
3688 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3690 // return success of updating or error message
3691 if (!is_null($data)) {
3692 return api_format_data("photo_create", $type, $data);
3694 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3698 // now let's do the changes in update-mode
3699 if ($mode == "update") {
3702 if (!is_null($desc)) {
3703 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3706 if (!is_null($album_new)) {
3707 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3710 if (!is_null($allow_cid)) {
3711 $allow_cid = trim($allow_cid);
3712 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3715 if (!is_null($deny_cid)) {
3716 $deny_cid = trim($deny_cid);
3717 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3720 if (!is_null($allow_gid)) {
3721 $allow_gid = trim($allow_gid);
3722 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3725 if (!is_null($deny_gid)) {
3726 $deny_gid = trim($deny_gid);
3727 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3731 if ($sql_extra != "") {
3732 $nothingtodo = false;
3734 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3736 datetime_convert(), // update edited timestamp
3742 $nothingtodo = true;
3745 if (x($_FILES, 'media')) {
3746 $nothingtodo = false;
3747 $media = $_FILES['media'];
3748 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3749 if (!is_null($data)) {
3750 return api_format_data("photo_update", $type, $data);
3754 // return success of updating or error message
3756 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
3757 return api_format_data("photo_update", $type, array('$result' => $answer));
3760 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
3761 return api_format_data("photo_update", $type, array('$result' => $answer));
3763 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3766 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3771 * @brief delete a single photo from the database through api
3773 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3776 function api_fr_photo_delete($type)
3778 if (api_user() === false) {
3779 throw new ForbiddenException();
3782 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3784 // do several checks on input parameters
3785 // we do not allow calls without photo id
3786 if ($photo_id == null) {
3787 throw new BadRequestException("no photo_id specified");
3789 // check if photo is existing in database
3791 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3795 if (!DBM::is_result($r)) {
3796 throw new BadRequestException("photo not available");
3798 // now we can perform on the deletion of the photo
3799 $result = dba::delete('photo', array('uid' => api_user(), 'resource-id' => $photo_id));
3801 // return success of deletion or error message
3803 // retrieve the id of the parent element (the photo element)
3805 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3806 intval(local_user()),
3810 if (!DBM::is_result($photo_item)) {
3811 throw new InternalServerErrorException("problem with deleting items occured");
3813 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3814 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
3815 drop_item($photo_item[0]['id'], false);
3817 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
3818 return api_format_data("photo_delete", $type, array('$result' => $answer));
3820 throw new InternalServerErrorException("unknown error on deleting photo from database table");
3826 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3828 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3831 function api_fr_photo_detail($type)
3833 if (api_user() === false) {
3834 throw new ForbiddenException();
3836 if (!x($_REQUEST, 'photo_id')) {
3837 throw new BadRequestException("No photo id.");
3840 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3841 $photo_id = $_REQUEST['photo_id'];
3843 // prepare json/xml output with data from database for the requested photo
3844 $data = prepare_photo_data($type, $scale, $photo_id);
3846 return api_format_data("photo_detail", $type, $data);
3851 * @brief updates the profile image for the user (either a specified profile or the default profile)
3853 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3856 function api_account_update_profile_image($type)
3858 if (api_user() === false) {
3859 throw new ForbiddenException();
3862 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
3864 // error if image data is missing
3865 if (!x($_FILES, 'image')) {
3866 throw new BadRequestException("no media data submitted");
3869 // check if specified profile id is valid
3870 if ($profileid != 0) {
3872 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
3876 // error message if specified profile id is not in database
3877 if (!DBM::is_result($r)) {
3878 throw new BadRequestException("profile_id not available");
3880 $is_default_profile = $r['profile'];
3882 $is_default_profile = 1;
3885 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3887 if (x($_FILES, 'image')) {
3888 $media = $_FILES['image'];
3889 } elseif (x($_FILES, 'media')) {
3890 $media = $_FILES['media'];
3892 // save new profile image
3893 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
3896 if (is_array($media['type'])) {
3897 $filetype = $media['type'][0];
3899 $filetype = $media['type'];
3901 if ($filetype == "image/jpeg") {
3903 } elseif ($filetype == "image/png") {
3906 // change specified profile or all profiles to the new resource-id
3907 if ($is_default_profile) {
3909 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
3910 dbesc($data['photo']['id']),
3911 intval(local_user())
3915 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
3916 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
3917 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
3918 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
3919 intval(local_user())
3923 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
3924 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
3925 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
3926 intval($_REQUEST['profile']),
3927 intval(local_user())
3931 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
3932 // so that browsers will do a cache update unconditionally
3935 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
3936 dbesc(datetime_convert()),
3937 intval(local_user())
3940 // Update global directory in background
3941 //$user = api_get_user(get_app());
3942 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
3943 if ($url && strlen(Config::get('system', 'directory'))) {
3944 Worker::add(PRIORITY_LOW, "Directory", $url);
3947 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
3949 // output for client
3951 return api_account_verify_credentials($type);
3953 // SaveMediaToDatabase failed for some reason
3954 throw new InternalServerErrorException("image upload failed");
3958 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3959 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
3960 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
3961 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3962 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3963 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3964 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
3965 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3966 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3969 function check_acl_input($acl_string)
3971 if ($acl_string == null || $acl_string == " ") {
3974 $contact_not_found = false;
3976 // split <x><y><z> into array of cid's
3977 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3979 // check for each cid if it is available on server
3980 $cid_array = $array[0];
3981 foreach ($cid_array as $cid) {
3982 $cid = str_replace("<", "", $cid);
3983 $cid = str_replace(">", "", $cid);
3985 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3989 $contact_not_found |= !DBM::is_result($contact);
3991 return $contact_not_found;
3994 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)
4002 if (is_array($media)) {
4003 if (is_array($media['tmp_name'])) {
4004 $src = $media['tmp_name'][0];
4006 $src = $media['tmp_name'];
4008 if (is_array($media['name'])) {
4009 $filename = basename($media['name'][0]);
4011 $filename = basename($media['name']);
4013 if (is_array($media['size'])) {
4014 $filesize = intval($media['size'][0]);
4016 $filesize = intval($media['size']);
4018 if (is_array($media['type'])) {
4019 $filetype = $media['type'][0];
4021 $filetype = $media['type'];
4025 if ($filetype == "") {
4026 $filetype=Image::guessType($filename);
4028 $imagedata = getimagesize($src);
4030 $filetype = $imagedata['mime'];
4033 "File upload src: " . $src . " - filename: " . $filename .
4034 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG
4037 // check if there was a php upload error
4038 if ($filesize == 0 && $media['error'] == 1) {
4039 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4041 // check against max upload size within Friendica instance
4042 $maximagesize = Config::get('system', 'maximagesize');
4043 if (($maximagesize) && ($filesize > $maximagesize)) {
4044 $formattedBytes = formatBytes($maximagesize);
4045 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4048 // create Photo instance with the data of the image
4049 $imagedata = @file_get_contents($src);
4050 $Image = new Image($imagedata, $filetype);
4051 if (! $Image->isValid()) {
4052 throw new InternalServerErrorException("unable to process image data");
4055 // check orientation of image
4056 $Image->orient($src);
4059 // check max length of images on server
4060 $max_length = Config::get('system', 'max_image_length');
4061 if (! $max_length) {
4062 $max_length = MAX_IMAGE_LENGTH;
4064 if ($max_length > 0) {
4065 $Image->scaleDown($max_length);
4066 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4068 $width = $Image->getWidth();
4069 $height = $Image->getHeight();
4071 // create a new resource-id if not already provided
4072 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
4074 if ($mediatype == "photo") {
4075 // upload normal image (scales 0, 1, 2)
4076 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4078 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4080 logger("photo upload: image upload with scale 0 (original size) failed");
4082 if ($width > 640 || $height > 640) {
4083 $Image->scaleDown(640);
4084 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4086 logger("photo upload: image upload with scale 1 (640x640) failed");
4090 if ($width > 320 || $height > 320) {
4091 $Image->scaleDown(320);
4092 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4094 logger("photo upload: image upload with scale 2 (320x320) failed");
4097 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4098 } elseif ($mediatype == "profileimage") {
4099 // upload profile image (scales 4, 5, 6)
4100 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4102 if ($width > 175 || $height > 175) {
4103 $Image->scaleDown(175);
4104 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4106 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4110 if ($width > 80 || $height > 80) {
4111 $Image->scaleDown(80);
4112 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4114 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4118 if ($width > 48 || $height > 48) {
4119 $Image->scaleDown(48);
4120 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4122 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4125 $Image->__destruct();
4126 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4130 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4131 if ($photo_id == null && $mediatype == "photo") {
4132 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4134 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4135 return prepare_photo_data($type, false, $hash);
4137 throw new InternalServerErrorException("image upload failed");
4141 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4143 // get data about the api authenticated user
4144 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4145 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4148 $arr['guid'] = get_guid(32);
4149 $arr['uid'] = intval(api_user());
4151 $arr['parent-uri'] = $uri;
4152 $arr['type'] = 'photo';
4154 $arr['resource-id'] = $hash;
4155 $arr['contact-id'] = $owner_record[0]['id'];
4156 $arr['owner-name'] = $owner_record[0]['name'];
4157 $arr['owner-link'] = $owner_record[0]['url'];
4158 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4159 $arr['author-name'] = $owner_record[0]['name'];
4160 $arr['author-link'] = $owner_record[0]['url'];
4161 $arr['author-avatar'] = $owner_record[0]['thumb'];
4163 $arr['allow_cid'] = $allow_cid;
4164 $arr['allow_gid'] = $allow_gid;
4165 $arr['deny_cid'] = $deny_cid;
4166 $arr['deny_gid'] = $deny_gid;
4167 $arr['last-child'] = 1;
4168 $arr['visible'] = $visibility;
4172 'image/jpeg' => 'jpg',
4173 'image/png' => 'png',
4174 'image/gif' => 'gif'
4177 // adds link to the thumbnail scale photo
4178 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4179 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4182 // do the magic for storing the item in the database and trigger the federation to other contacts
4186 function prepare_photo_data($type, $scale, $photo_id)
4188 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4189 $data_sql = ($scale === false ? "" : "data, ");
4191 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4192 // clients needs to convert this in their way for further processing
4194 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4195 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4196 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4197 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4199 intval(local_user()),
4205 'image/jpeg' => 'jpg',
4206 'image/png' => 'png',
4207 'image/gif' => 'gif'
4210 // prepare output data for photo
4211 if (DBM::is_result($r)) {
4212 $data = array('photo' => $r[0]);
4213 $data['photo']['id'] = $data['photo']['resource-id'];
4214 if ($scale !== false) {
4215 $data['photo']['data'] = base64_encode($data['photo']['data']);
4217 unset($data['photo']['datasize']); //needed only with scale param
4219 if ($type == "xml") {
4220 $data['photo']['links'] = array();
4221 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4222 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4224 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4227 $data['photo']['link'] = array();
4228 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4230 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4231 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4235 unset($data['photo']['resource-id']);
4236 unset($data['photo']['minscale']);
4237 unset($data['photo']['maxscale']);
4239 throw new NotFoundException();
4242 // retrieve item element for getting activities (like, dislike etc.) related to photo
4244 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4245 intval(local_user()),
4248 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4250 // retrieve comments on photo
4252 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4253 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4254 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4255 `contact`.`id` AS `cid`
4257 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4258 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4259 WHERE `item`.`parent` = %d AND `item`.`visible`
4260 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4261 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4262 intval($item[0]['parent']),
4264 dbesc(ACTIVITY_POST)
4267 // prepare output of comments
4268 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4269 $comments = array();
4270 if ($type == "xml") {
4272 foreach ($commentData as $comment) {
4273 $comments[$k++ . ":comment"] = $comment;
4276 foreach ($commentData as $comment) {
4277 $comments[] = $comment;
4280 $data['photo']['friendica_comments'] = $comments;
4282 // include info if rights on photo and rights on item are mismatching
4283 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4284 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4285 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4286 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4287 $data['photo']['rights_mismatch'] = $rights_mismatch;
4294 * Similar as /mod/redir.php
4295 * redirect to 'url' after dfrn auth
4297 * Why this when there is mod/redir.php already?
4298 * This use api_user() and api_login()
4301 * c_url: url of remote contact to auth to
4302 * url: string, url to redirect after auth
4304 function api_friendica_remoteauth()
4306 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4307 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4309 if ($url === '' || $c_url === '') {
4310 throw new BadRequestException("Wrong parameters.");
4313 $c_url = normalise_link($c_url);
4318 "SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4323 if ((! DBM::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4324 throw new BadRequestException("Unknown contact");
4329 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4331 if ($r[0]['duplex'] && $r[0]['issued-id']) {
4332 $orig_id = $r[0]['issued-id'];
4333 $dfrn_id = '1:' . $orig_id;
4335 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4336 $orig_id = $r[0]['dfrn-id'];
4337 $dfrn_id = '0:' . $orig_id;
4340 $sec = random_string();
4343 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4344 VALUES( %d, %s, '%s', '%s', %d )",
4352 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4353 $dest = (($url) ? '&destination_url=' . $url : '');
4355 $r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4356 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4357 . '&type=profile&sec=' . $sec . $dest . $quiet
4360 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4363 * @brief Return the item shared, if the item contains only the [share] tag
4365 * @param array $item Sharer item
4366 * @return array Shared item or false if not a reshare
4368 function api_share_as_retweet(&$item)
4370 $body = trim($item["body"]);
4372 if (Diaspora::isReshare($body, false)===false) {
4376 /// @TODO "$1" should maybe mean '$1' ?
4377 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4379 * Skip if there is no shared message in there
4380 * we already checked this in diaspora::isReshare()
4381 * but better one more than one less...
4383 if ($body == $attributes) {
4388 // build the fake reshared item
4389 $reshared_item = $item;
4392 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4393 if ($matches[1] != "") {
4394 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4397 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4398 if ($matches[1] != "") {
4399 $author = $matches[1];
4403 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4404 if ($matches[1] != "") {
4405 $profile = $matches[1];
4408 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4409 if ($matches[1] != "") {
4410 $profile = $matches[1];
4414 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4415 if ($matches[1] != "") {
4416 $avatar = $matches[1];
4419 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4420 if ($matches[1] != "") {
4421 $avatar = $matches[1];
4425 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4426 if ($matches[1] != "") {
4427 $link = $matches[1];
4430 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4431 if ($matches[1] != "") {
4432 $link = $matches[1];
4436 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4437 if ($matches[1] != "")
4438 $posted = $matches[1];
4440 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4441 if ($matches[1] != "") {
4442 $posted = $matches[1];
4445 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4447 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4451 $reshared_item["body"] = $shared_body;
4452 $reshared_item["author-name"] = $author;
4453 $reshared_item["author-link"] = $profile;
4454 $reshared_item["author-avatar"] = $avatar;
4455 $reshared_item["plink"] = $link;
4456 $reshared_item["created"] = $posted;
4457 $reshared_item["edited"] = $posted;
4459 return $reshared_item;
4463 function api_get_nick($profile)
4466 - remove trailing junk from profile url
4467 - pump.io check has to check the website
4473 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4474 dbesc(normalise_link($profile))
4477 if (DBM::is_result($r)) {
4478 $nick = $r[0]["nick"];
4483 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4484 dbesc(normalise_link($profile))
4487 if (DBM::is_result($r)) {
4488 $nick = $r[0]["nick"];
4493 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4494 if ($friendica != $profile) {
4500 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4501 if ($diaspora != $profile) {
4507 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4508 if ($twitter != $profile) {
4515 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4516 if ($StatusnetHost != $profile) {
4517 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4518 if ($StatusnetUser != $profile) {
4519 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4520 $user = json_decode($UserData);
4522 $nick = $user->screen_name;
4528 // To-Do: look at the page if its really a pumpio site
4529 //if (!$nick == "") {
4530 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4531 // if ($pumpio != $profile)
4533 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4544 function api_in_reply_to($item)
4546 $in_reply_to = array();
4548 $in_reply_to['status_id'] = null;
4549 $in_reply_to['user_id'] = null;
4550 $in_reply_to['status_id_str'] = null;
4551 $in_reply_to['user_id_str'] = null;
4552 $in_reply_to['screen_name'] = null;
4554 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4555 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4556 intval($item['uid']),
4557 dbesc($item['thr-parent']));
4559 if (DBM::is_result($r)) {
4560 $in_reply_to['status_id'] = intval($r[0]['id']);
4562 $in_reply_to['status_id'] = intval($item['parent']);
4565 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4567 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4568 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4569 WHERE `item`.`id` = %d LIMIT 1",
4570 intval($in_reply_to['status_id'])
4573 if (DBM::is_result($r)) {
4574 if ($r[0]['nick'] == "") {
4575 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4578 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4579 $in_reply_to['user_id'] = intval($r[0]['id']);
4580 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4583 // There seems to be situation, where both fields are identical:
4584 // https://github.com/friendica/friendica/issues/1010
4585 // This is a bugfix for that.
4586 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4587 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4588 $in_reply_to['status_id'] = null;
4589 $in_reply_to['user_id'] = null;
4590 $in_reply_to['status_id_str'] = null;
4591 $in_reply_to['user_id_str'] = null;
4592 $in_reply_to['screen_name'] = null;
4596 return $in_reply_to;
4599 function api_clean_plain_items($Text)
4601 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4603 $Text = bb_CleanPictureLinks($Text);
4604 $URLSearchString = "^\[\]";
4606 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
4608 if ($include_entities == "true") {
4609 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
4612 // Simplify "attachment" element
4613 $Text = api_clean_attachments($Text);
4619 * @brief Removes most sharing information for API text export
4621 * @param string $body The original body
4623 * @return string Cleaned body
4625 function api_clean_attachments($body)
4627 $data = get_attachment_data($body);
4634 if (isset($data["text"]))
4635 $body = $data["text"];
4637 if (($body == "") && (isset($data["title"])))
4638 $body = $data["title"];
4640 if (isset($data["url"]))
4641 $body .= "\n".$data["url"];
4643 $body .= $data["after"];
4648 function api_best_nickname(&$contacts)
4650 $best_contact = array();
4652 if (count($contact) == 0)
4655 foreach ($contacts as $contact)
4656 if ($contact["network"] == "") {
4657 $contact["network"] = "dfrn";
4658 $best_contact = array($contact);
4661 if (sizeof($best_contact) == 0)
4662 foreach ($contacts as $contact)
4663 if ($contact["network"] == "dfrn")
4664 $best_contact = array($contact);
4666 if (sizeof($best_contact) == 0)
4667 foreach ($contacts as $contact)
4668 if ($contact["network"] == "dspr")
4669 $best_contact = array($contact);
4671 if (sizeof($best_contact) == 0)
4672 foreach ($contacts as $contact)
4673 if ($contact["network"] == "stat")
4674 $best_contact = array($contact);
4676 if (sizeof($best_contact) == 0)
4677 foreach ($contacts as $contact)
4678 if ($contact["network"] == "pump")
4679 $best_contact = array($contact);
4681 if (sizeof($best_contact) == 0)
4682 foreach ($contacts as $contact)
4683 if ($contact["network"] == "twit")
4684 $best_contact = array($contact);
4686 if (sizeof($best_contact) == 1) {
4687 $contacts = $best_contact;
4689 $contacts = array($contacts[0]);
4693 // return all or a specified group of the user with the containing contacts
4694 function api_friendica_group_show($type)
4698 if (api_user() === false) throw new ForbiddenException();
4701 $user_info = api_get_user($a);
4702 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4703 $uid = $user_info['uid'];
4705 // get data of the specified group id or all groups if not specified
4708 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4712 // error message if specified gid is not in database
4713 if (!DBM::is_result($r))
4714 throw new BadRequestException("gid not available");
4717 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4722 // loop through all groups and retrieve all members for adding data in the user array
4723 foreach ($r as $rr) {
4724 $members = Contact::getByGroupId($rr['id']);
4727 if ($type == "xml") {
4728 $user_element = "users";
4730 foreach ($members as $member) {
4731 $user = api_get_user($a, $member['nurl']);
4732 $users[$k++.":user"] = $user;
4735 $user_element = "user";
4736 foreach ($members as $member) {
4737 $user = api_get_user($a, $member['nurl']);
4741 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4743 return api_format_data("groups", $type, array('group' => $grps));
4745 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4748 // delete the specified group of the user
4749 function api_friendica_group_delete($type)
4753 if (api_user() === false) {
4754 throw new ForbiddenException();
4758 $user_info = api_get_user($a);
4759 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4760 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4761 $uid = $user_info['uid'];
4763 // error if no gid specified
4764 if ($gid == 0 || $name == "") {
4765 throw new BadRequestException('gid or name not specified');
4768 // get data of the specified group id
4770 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
4774 // error message if specified gid is not in database
4775 if (!DBM::is_result($r)) {
4776 throw new BadRequestException('gid not available');
4779 // get data of the specified group id and group name
4781 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
4786 // error message if specified gid is not in database
4787 if (!DBM::is_result($rname)) {
4788 throw new BadRequestException('wrong group name');
4792 $ret = Group::removeByName($uid, $name);
4795 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
4796 return api_format_data("group_delete", $type, array('result' => $success));
4798 throw new BadRequestException('other API error');
4801 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4804 // create the specified group with the posted array of contacts
4805 function api_friendica_group_create($type)
4809 if (api_user() === false) throw new ForbiddenException();
4812 $user_info = api_get_user($a);
4813 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4814 $uid = $user_info['uid'];
4815 $json = json_decode($_POST['json'], true);
4816 $users = $json['user'];
4818 // error if no name specified
4820 throw new BadRequestException('group name not specified');
4822 // get data of the specified group name
4824 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
4828 // error message if specified group name already exists
4829 if (DBM::is_result($rname))
4830 throw new BadRequestException('group name already exists');
4832 // check if specified group name is a deleted group
4834 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
4838 // error message if specified group name already exists
4839 if (DBM::is_result($rname))
4840 $reactivate_group = true;
4843 $ret = Group::create($uid, $name);
4845 $gid = Group::getIdByName($uid, $name);
4847 throw new BadRequestException('other API error');
4851 $erroraddinguser = false;
4852 $errorusers = array();
4853 foreach ($users as $user) {
4854 $cid = $user['cid'];
4855 // check if user really exists as contact
4857 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4861 if (count($contact))
4862 $result = Group::addMember($gid, $cid);
4864 $erroraddinguser = true;
4865 $errorusers[] = $cid;
4869 // return success message incl. missing users in array
4870 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
4871 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4872 return api_format_data("group_create", $type, array('result' => $success));
4874 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4877 // update the specified group with the posted array of contacts
4878 function api_friendica_group_update($type)
4882 if (api_user() === false) throw new ForbiddenException();
4885 $user_info = api_get_user($a);
4886 $uid = $user_info['uid'];
4887 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4888 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4889 $json = json_decode($_POST['json'], true);
4890 $users = $json['user'];
4892 // error if no name specified
4894 throw new BadRequestException('group name not specified');
4896 // error if no gid specified
4898 throw new BadRequestException('gid not specified');
4901 $members = Contact::getByGroupId($gid);
4902 foreach ($members as $member) {
4903 $cid = $member['id'];
4904 foreach ($users as $user) {
4905 $found = ($user['cid'] == $cid ? true : false);
4908 $ret = Group::removeMemberByName($uid, $name, $cid);
4913 $erroraddinguser = false;
4914 $errorusers = array();
4915 foreach ($users as $user) {
4916 $cid = $user['cid'];
4917 // check if user really exists as contact
4919 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4924 if (count($contact)) {
4925 $result = Group::addMember($gid, $cid);
4927 $erroraddinguser = true;
4928 $errorusers[] = $cid;
4932 // return success message incl. missing users in array
4933 $status = ($erroraddinguser ? "missing user" : "ok");
4934 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4935 return api_format_data("group_update", $type, array('result' => $success));
4938 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4940 function api_friendica_activity($type)
4944 if (api_user() === false) throw new ForbiddenException();
4945 $verb = strtolower($a->argv[3]);
4946 $verb = preg_replace("|\..*$|", "", $verb);
4948 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4950 $res = do_like($id, $verb);
4953 if ($type == "xml") {
4958 return api_format_data('ok', $type, array('ok' => $ok));
4960 throw new BadRequestException('Error adding activity');
4964 /// @TODO move to top of file or somwhere better
4965 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
4966 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
4967 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
4968 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
4969 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4970 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
4971 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
4972 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
4973 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
4974 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4977 * @brief Returns notifications
4979 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4982 function api_friendica_notification($type)
4986 if (api_user() === false) throw new ForbiddenException();
4987 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
4988 $nm = new NotificationsManager();
4990 $notes = $nm->getAll(array(), "+seen -date", 50);
4992 if ($type == "xml") {
4993 $xmlnotes = array();
4994 foreach ($notes as $note)
4995 $xmlnotes[] = array("@attributes" => $note);
5000 return api_format_data("notes", $type, array('note' => $notes));
5004 * @brief Set notification as seen and returns associated item (if possible)
5006 * POST request with 'id' param as notification id
5008 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5011 function api_friendica_notification_seen($type)
5015 if (api_user() === false) throw new ForbiddenException();
5016 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
5018 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5020 $nm = new NotificationsManager();
5021 $note = $nm->getByID($id);
5022 if (is_null($note)) throw new BadRequestException("Invalid argument");
5024 $nm->setSeen($note);
5025 if ($note['otype']=='item') {
5026 // would be really better with an ItemsManager and $im->getByID() :-P
5028 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5029 intval($note['iid']),
5030 intval(local_user())
5033 // we found the item, return it to the user
5034 $user_info = api_get_user($a);
5035 $ret = api_format_items($r, $user_info, false, $type);
5036 $data = array('status' => $ret);
5037 return api_format_data("status", $type, $data);
5039 // the item can't be found, but we set the note as seen, so we count this as a success
5041 return api_format_data('result', $type, array('result' => "success"));
5044 /// @TODO move to top of file or somwhere better
5045 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5046 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5049 * @brief update a direct_message to seen state
5051 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5052 * @return string (success result=ok, error result=error with error message)
5054 function api_friendica_direct_messages_setseen($type)
5057 if (api_user() === false) {
5058 throw new ForbiddenException();
5062 $user_info = api_get_user($a);
5063 $uid = $user_info['uid'];
5064 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5066 // return error if id is zero
5068 $answer = array('result' => 'error', 'message' => 'message id not specified');
5069 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5072 // get data of the specified message id
5074 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5079 // error message if specified id is not in database
5080 if (!DBM::is_result($r)) {
5081 $answer = array('result' => 'error', 'message' => 'message id not in database');
5082 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5085 // update seen indicator
5087 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5094 $answer = array('result' => 'ok', 'message' => 'message set to seen');
5095 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
5097 $answer = array('result' => 'error', 'message' => 'unknown error');
5098 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5102 /// @TODO move to top of file or somwhere better
5103 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5106 * @brief search for direct_messages containing a searchstring through api
5108 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5109 * @return string (success: success=true if found and search_result contains found messages
5110 * success=false if nothing was found, search_result='nothing found',
5111 * error: result=error with error message)
5113 function api_friendica_direct_messages_search($type)
5117 if (api_user() === false) {
5118 throw new ForbiddenException();
5122 $user_info = api_get_user($a);
5123 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5124 $uid = $user_info['uid'];
5126 // error if no searchstring specified
5127 if ($searchstring == "") {
5128 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
5129 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
5132 // get data for the specified searchstring
5134 "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",
5136 dbesc('%'.$searchstring.'%')
5139 $profile_url = $user_info["url"];
5141 // message if nothing was found
5142 if (!DBM::is_result($r)) {
5143 $success = array('success' => false, 'search_results' => 'problem with query');
5144 } elseif (count($r) == 0) {
5145 $success = array('success' => false, 'search_results' => 'nothing found');
5148 foreach ($r as $item) {
5149 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5150 $recipient = $user_info;
5151 $sender = api_get_user($a, normalise_link($item['contact-url']));
5152 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5153 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5154 $sender = $user_info;
5157 $ret[] = api_format_messages($item, $recipient, $sender);
5159 $success = array('success' => true, 'search_results' => $ret);
5162 return api_format_data("direct_message_search", $type, array('$result' => $success));
5165 /// @TODO move to top of file or somwhere better
5166 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5169 * @brief return data of all the profiles a user has to the client
5171 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5174 function api_friendica_profile_show($type)
5178 if (api_user() === false) {
5179 throw new ForbiddenException();
5183 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5185 // retrieve general information about profiles for user
5186 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5187 $directory = Config::get('system', 'directory');
5189 // get data of the specified profile id or all profiles of the user if not specified
5190 if ($profileid != 0) {
5192 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5197 // error message if specified gid is not in database
5198 if (!DBM::is_result($r)) {
5199 throw new BadRequestException("profile_id not available");
5203 "SELECT * FROM `profile` WHERE `uid` = %d",
5207 // loop through all returned profiles and retrieve data and users
5209 foreach ($r as $rr) {
5210 $profile = api_format_items_profiles($rr, $type);
5212 // select all users from contact table, loop and prepare standard return for user data
5215 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5217 intval($rr['profile_id'])
5220 foreach ($r as $rr) {
5221 $user = api_get_user($a, $rr['nurl']);
5222 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5224 $profile['users'] = $users;
5226 // add prepared profile data to array for final return
5227 if ($type == "xml") {
5228 $profiles[$k++ . ":profile"] = $profile;
5230 $profiles[] = $profile;
5234 // return settings, authenticated user and profiles data
5235 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5237 $result = array('multi_profiles' => $multi_profiles ? true : false,
5238 'global_dir' => $directory,
5239 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5240 'profiles' => $profiles);
5241 return api_format_data("friendica_profiles", $type, array('$result' => $result));
5243 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5246 @TODO Maybe open to implement?
5248 [pagename] => api/1.1/statuses/lookup.json
5249 [id] => 605138389168451584
5250 [include_cards] => true
5251 [cards_platform] => Android-12
5252 [include_entities] => true
5253 [include_my_retweet] => 1
5255 [include_reply_count] => true
5256 [include_descendent_reply_count] => true
5260 Not implemented by now:
5261 statuses/retweets_of_me
5266 account/update_location
5267 account/update_profile_background_image
5270 friendica/profile/update
5271 friendica/profile/create
5272 friendica/profile/delete
5274 Not implemented in status.net:
5275 statuses/retweeted_to_me
5276 statuses/retweeted_by_me
5277 direct_messages/destroy
5279 account/update_delivery_device
5280 notifications/follow