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 * @TODO nothing to say?
1667 function api_statuses_show($type)
1671 if (api_user() === false) {
1672 throw new ForbiddenException();
1675 $user_info = api_get_user($a);
1678 $id = intval($a->argv[3]);
1681 $id = intval($_REQUEST["id"]);
1686 $id = intval($a->argv[4]);
1689 logger('API: api_statuses_show: ' . $id);
1691 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1694 if ($conversation) {
1695 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1697 $sql_extra .= " AND `item`.`id` = %d";
1701 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1702 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1703 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1704 `contact`.`id` AS `cid`
1706 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1707 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1708 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1709 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1712 dbesc(ACTIVITY_POST),
1716 /// @TODO How about copying this to above methods which don't check $r ?
1717 if (!DBM::is_result($r)) {
1718 throw new BadRequestException("There is no status with this id.");
1721 $ret = api_format_items($r, $user_info, false, $type);
1723 if ($conversation) {
1724 $data = array('status' => $ret);
1725 return api_format_data("statuses", $type, $data);
1727 $data = array('status' => $ret[0]);
1728 return api_format_data("status", $type, $data);
1732 /// @TODO move to top of file or somewhere better
1733 api_register_func('api/statuses/show', 'api_statuses_show', true);
1736 * @TODO nothing to say?
1738 function api_conversation_show($type)
1742 if (api_user() === false) {
1743 throw new ForbiddenException();
1746 $user_info = api_get_user($a);
1749 $id = intval($a->argv[3]);
1750 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1751 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1755 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1756 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1758 $start = $page*$count;
1761 $id = intval($_REQUEST["id"]);
1766 $id = intval($a->argv[4]);
1769 logger('API: api_conversation_show: '.$id);
1771 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1772 if (DBM::is_result($r)) {
1773 $id = $r[0]["parent"];
1779 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1782 // Not sure why this query was so complicated. We should keep it here for a while,
1783 // just to make sure that we really don't need it.
1784 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1785 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1788 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1789 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1790 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1791 `contact`.`id` AS `cid`
1793 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1794 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1795 WHERE `item`.`parent` = %d AND `item`.`visible`
1796 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1797 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1798 AND `item`.`id`>%d $sql_extra
1799 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1800 intval($id), intval(api_user()),
1801 dbesc(ACTIVITY_POST),
1803 intval($start), intval($count)
1806 if (!DBM::is_result($r)) {
1807 throw new BadRequestException("There is no status with this id.");
1810 $ret = api_format_items($r, $user_info, false, $type);
1812 $data = array('status' => $ret);
1813 return api_format_data("statuses", $type, $data);
1816 /// @TODO move to top of file or somewhere better
1817 api_register_func('api/conversation/show', 'api_conversation_show', true);
1818 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1821 * @TODO nothing to say?
1823 function api_statuses_repeat($type)
1829 if (api_user() === false) {
1830 throw new ForbiddenException();
1833 $user_info = api_get_user($a);
1836 $id = intval($a->argv[3]);
1839 $id = intval($_REQUEST["id"]);
1844 $id = intval($a->argv[4]);
1847 logger('API: api_statuses_repeat: '.$id);
1850 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1851 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1852 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1853 `contact`.`id` AS `cid`
1855 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1856 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1857 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1858 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1859 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1861 AND `item`.`id`=%d",
1865 /// @TODO other style than above functions!
1866 if (DBM::is_result($r) && $r[0]['body'] != "") {
1867 if (strpos($r[0]['body'], "[/share]") !== false) {
1868 $pos = strpos($r[0]['body'], "[share");
1869 $post = substr($r[0]['body'], $pos);
1871 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1873 $post .= $r[0]['body'];
1874 $post .= "[/share]";
1876 $_REQUEST['body'] = $post;
1877 $_REQUEST['profile_uid'] = api_user();
1878 $_REQUEST['type'] = 'wall';
1879 $_REQUEST['api_source'] = true;
1881 if (!x($_REQUEST, "source")) {
1882 $_REQUEST["source"] = api_source();
1887 throw new ForbiddenException();
1890 // this should output the last post (the one we just posted).
1892 return api_status_show($type);
1895 /// @TODO move to top of file or somewhere better
1896 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1899 * @TODO nothing to say?
1901 function api_statuses_destroy($type)
1905 if (api_user() === false) {
1906 throw new ForbiddenException();
1909 $user_info = api_get_user($a);
1912 $id = intval($a->argv[3]);
1915 $id = intval($_REQUEST["id"]);
1920 $id = intval($a->argv[4]);
1923 logger('API: api_statuses_destroy: '.$id);
1925 $ret = api_statuses_show($type);
1927 drop_item($id, false);
1932 /// @TODO move to top of file or somewhere better
1933 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1936 * @TODO Nothing more than an URL to say?
1937 * http://developer.twitter.com/doc/get/statuses/mentions
1939 function api_statuses_mentions($type)
1943 if (api_user() === false) {
1944 throw new ForbiddenException();
1947 unset($_REQUEST["user_id"]);
1948 unset($_GET["user_id"]);
1950 unset($_REQUEST["screen_name"]);
1951 unset($_GET["screen_name"]);
1953 $user_info = api_get_user($a);
1954 // get last newtork messages
1958 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1959 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1963 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1964 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1965 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1967 $start = $page * $count;
1969 // Ugly code - should be changed
1970 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
1971 $myurl = substr($myurl, strpos($myurl, '://') + 3);
1972 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1973 $myurl = str_replace('www.', '', $myurl);
1974 $diasp_url = str_replace('/profile/', '/u/', $myurl);
1977 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1981 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1982 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1983 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1984 `contact`.`id` AS `cid`
1985 FROM `item` FORCE INDEX (`uid_id`)
1986 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1987 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1988 WHERE `item`.`uid` = %d AND `verb` = '%s'
1989 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1990 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1991 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1994 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1996 dbesc(ACTIVITY_POST),
1997 dbesc(protect_sprintf($myurl)),
1998 dbesc(protect_sprintf($myurl)),
2005 $ret = api_format_items($r, $user_info, false, $type);
2007 $data = array('status' => $ret);
2011 $data = api_rss_extra($a, $data, $user_info);
2015 return api_format_data("statuses", $type, $data);
2018 /// @TODO move to top of file or somewhere better
2019 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2020 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2022 function api_statuses_user_timeline($type)
2026 if (api_user() === false) {
2027 throw new ForbiddenException();
2030 $user_info = api_get_user($a);
2031 // get last network messages
2034 "api_statuses_user_timeline: api_user: ". api_user() .
2035 "\nuser_info: ".print_r($user_info, true) .
2036 "\n_REQUEST: ".print_r($_REQUEST, true),
2041 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2042 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2046 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2047 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2048 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
2049 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
2051 $start = $page * $count;
2054 if ($user_info['self'] == 1) {
2055 $sql_extra .= " AND `item`.`wall` = 1 ";
2058 if ($exclude_replies > 0) {
2059 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2061 if ($conversation_id > 0) {
2062 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2066 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2067 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2068 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2069 `contact`.`id` AS `cid`
2070 FROM `item` FORCE INDEX (`uid_contactid_id`)
2071 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2072 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2073 WHERE `item`.`uid` = %d AND `verb` = '%s'
2074 AND `item`.`contact-id` = %d
2075 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2078 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2080 dbesc(ACTIVITY_POST),
2081 intval($user_info['cid']),
2087 $ret = api_format_items($r, $user_info, true, $type);
2089 $data = array('status' => $ret);
2093 $data = api_rss_extra($a, $data, $user_info);
2097 return api_format_data("statuses", $type, $data);
2100 /// @TODO move to top of file or somwhere better
2101 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2104 * Star/unstar an item
2105 * param: id : id of the item
2107 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2109 function api_favorites_create_destroy($type)
2113 if (api_user() === false) {
2114 throw new ForbiddenException();
2117 // for versioned api.
2118 /// @TODO We need a better global soluton
2119 $action_argv_id = 2;
2120 if ($a->argv[1] == "1.1") {
2121 $action_argv_id = 3;
2124 if ($a->argc <= $action_argv_id) {
2125 throw new BadRequestException("Invalid request.");
2127 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2128 if ($a->argc == $action_argv_id + 2) {
2129 $itemid = intval($a->argv[$action_argv_id + 1]);
2131 /// @TODO use x() to check if _REQUEST contains 'id'
2132 $itemid = intval($_REQUEST['id']);
2135 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2137 if (!DBM::is_result($item) || count($item) == 0) {
2138 throw new BadRequestException("Invalid item.");
2143 $item[0]['starred'] = 1;
2146 $item[0]['starred'] = 0;
2149 throw new BadRequestException("Invalid action ".$action);
2152 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2154 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2157 throw new InternalServerErrorException("DB error");
2161 $user_info = api_get_user($a);
2162 $rets = api_format_items($item, $user_info, false, $type);
2165 $data = array('status' => $ret);
2169 $data = api_rss_extra($a, $data, $user_info);
2172 return api_format_data("status", $type, $data);
2175 /// @TODO move to top of file or somwhere better
2176 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2177 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2179 function api_favorites($type)
2185 if (api_user() === false) {
2186 throw new ForbiddenException();
2189 $called_api = array();
2191 $user_info = api_get_user($a);
2193 // in friendica starred item are private
2194 // return favorites only for self
2195 logger('api_favorites: self:' . $user_info['self']);
2197 if ($user_info['self'] == 0) {
2203 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2204 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2205 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2206 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2211 $start = $page*$count;
2214 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2218 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2219 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2220 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2221 `contact`.`id` AS `cid`
2222 FROM `item`, `contact`
2223 WHERE `item`.`uid` = %d
2224 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2225 AND `item`.`starred` = 1
2226 AND `contact`.`id` = `item`.`contact-id`
2227 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2230 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2237 $ret = api_format_items($r, $user_info, false, $type);
2240 $data = array('status' => $ret);
2244 $data = api_rss_extra($a, $data, $user_info);
2247 return api_format_data("statuses", $type, $data);
2250 /// @TODO move to top of file or somwhere better
2251 api_register_func('api/favorites', 'api_favorites', true);
2253 function api_format_messages($item, $recipient, $sender)
2255 // standard meta information
2257 'id' => $item['id'],
2258 'sender_id' => $sender['id'] ,
2260 'recipient_id' => $recipient['id'],
2261 'created_at' => api_date($item['created']),
2262 'sender_screen_name' => $sender['screen_name'],
2263 'recipient_screen_name' => $recipient['screen_name'],
2264 'sender' => $sender,
2265 'recipient' => $recipient,
2267 'friendica_seen' => $item['seen'],
2268 'friendica_parent_uri' => $item['parent-uri'],
2271 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2272 unset($ret["sender"]["uid"]);
2273 unset($ret["sender"]["self"]);
2274 unset($ret["recipient"]["uid"]);
2275 unset($ret["recipient"]["self"]);
2277 //don't send title to regular StatusNET requests to avoid confusing these apps
2278 if (x($_GET, 'getText')) {
2279 $ret['title'] = $item['title'];
2280 if ($_GET['getText'] == 'html') {
2281 $ret['text'] = bbcode($item['body'], false, false);
2282 } elseif ($_GET['getText'] == 'plain') {
2283 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2284 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2287 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2289 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2290 unset($ret['sender']);
2291 unset($ret['recipient']);
2297 function api_convert_item($item)
2299 $body = $item['body'];
2300 $attachments = api_get_attachments($body);
2302 // Workaround for ostatus messages where the title is identically to the body
2303 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2304 $statusbody = trim(html2plain($html, 0));
2306 // handle data: images
2307 $statusbody = api_format_items_embeded_images($item, $statusbody);
2309 $statustitle = trim($item['title']);
2311 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2312 $statustext = trim($statusbody);
2314 $statustext = trim($statustitle."\n\n".$statusbody);
2317 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2318 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2321 $statushtml = trim(bbcode($body, false, false));
2323 // Workaround for clients with limited HTML parser functionality
2324 $search = array("<br>", "<blockquote>", "</blockquote>",
2325 "<h1>", "</h1>", "<h2>", "</h2>",
2326 "<h3>", "</h3>", "<h4>", "</h4>",
2327 "<h5>", "</h5>", "<h6>", "</h6>");
2328 $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2329 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2330 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2331 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2332 $statushtml = str_replace($search, $replace, $statushtml);
2334 if ($item['title'] != "") {
2335 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2339 $oldtext = $statushtml;
2340 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2341 } while ($oldtext != $statushtml);
2343 if (substr($statushtml, 0, 4) == '<br>') {
2344 $statushtml = substr($statushtml, 4);
2347 if (substr($statushtml, 0, -4) == '<br>') {
2348 $statushtml = substr($statushtml, -4);
2351 // feeds without body should contain the link
2352 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2353 $statushtml .= bbcode($item['plink']);
2356 $entities = api_get_entitities($statustext, $body);
2359 "text" => $statustext,
2360 "html" => $statushtml,
2361 "attachments" => $attachments,
2362 "entities" => $entities
2366 function api_get_attachments(&$body)
2369 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2371 $URLSearchString = "^\[\]";
2372 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2378 $attachments = array();
2380 foreach ($images[1] as $image) {
2381 $imagedata = Image::getInfoFromURL($image);
2384 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2388 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2389 foreach ($images[0] as $orig) {
2390 $body = str_replace($orig, "", $body);
2394 return $attachments;
2397 function api_get_entitities(&$text, $bbcode)
2401 * Links at the first character of the post
2406 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2408 if ($include_entities != "true") {
2409 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2411 foreach ($images[1] as $image) {
2412 $replace = proxy_url($image);
2413 $text = str_replace($image, $replace, $text);
2418 $bbcode = bb_CleanPictureLinks($bbcode);
2420 // Change pure links in text to bbcode uris
2421 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2423 $entities = array();
2424 $entities["hashtags"] = array();
2425 $entities["symbols"] = array();
2426 $entities["urls"] = array();
2427 $entities["user_mentions"] = array();
2429 $URLSearchString = "^\[\]";
2431 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2433 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2434 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2435 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2437 $bbcode = preg_replace(
2438 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2439 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2442 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2444 $bbcode = preg_replace(
2445 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2446 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2449 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2451 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2453 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2454 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2456 $ordered_urls = array();
2457 foreach ($urls[1] as $id => $url) {
2458 //$start = strpos($text, $url, $offset);
2459 $start = iconv_strpos($text, $url, 0, "UTF-8");
2460 if (!($start === false)) {
2461 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2465 ksort($ordered_urls);
2468 //foreach ($urls[1] AS $id=>$url) {
2469 foreach ($ordered_urls as $url) {
2470 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2471 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2473 $display_url = $url["title"];
2475 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2476 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2478 if (strlen($display_url) > 26)
2479 $display_url = substr($display_url, 0, 25)."…";
2482 //$start = strpos($text, $url, $offset);
2483 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2484 if (!($start === false)) {
2485 $entities["urls"][] = array("url" => $url["url"],
2486 "expanded_url" => $url["url"],
2487 "display_url" => $display_url,
2488 "indices" => array($start, $start+strlen($url["url"])));
2489 $offset = $start + 1;
2493 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2494 $ordered_images = array();
2495 foreach ($images[1] as $image) {
2496 //$start = strpos($text, $url, $offset);
2497 $start = iconv_strpos($text, $image, 0, "UTF-8");
2498 if (!($start === false))
2499 $ordered_images[$start] = $image;
2501 //$entities["media"] = array();
2504 foreach ($ordered_images as $url) {
2505 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2506 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2508 if (strlen($display_url) > 26)
2509 $display_url = substr($display_url, 0, 25)."…";
2511 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2512 if (!($start === false)) {
2513 $image = Image::getInfoFromURL($url);
2515 // If image cache is activated, then use the following sizes:
2516 // thumb (150), small (340), medium (600) and large (1024)
2517 if (!Config::get("system", "proxy_disabled")) {
2518 $media_url = proxy_url($url);
2521 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2522 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2524 if (($image[0] > 150) || ($image[1] > 150)) {
2525 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2526 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2529 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2530 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2532 if (($image[0] > 600) || ($image[1] > 600)) {
2533 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2534 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2538 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2541 $entities["media"][] = array(
2543 "id_str" => (string)$start+1,
2544 "indices" => array($start, $start+strlen($url)),
2545 "media_url" => normalise_link($media_url),
2546 "media_url_https" => $media_url,
2548 "display_url" => $display_url,
2549 "expanded_url" => $url,
2553 $offset = $start + 1;
2559 function api_format_items_embeded_images(&$item, $text)
2561 $text = preg_replace_callback(
2562 "|data:image/([^;]+)[^=]+=*|m",
2563 function ($match) use ($item) {
2564 return System::baseUrl()."/display/".$item['guid'];
2573 * @brief return <a href='url'>name</a> as array
2575 * @param string $txt text
2580 function api_contactlink_to_array($txt)
2583 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2584 if ($r && count($match)==3) {
2586 'name' => $match[2],
2600 * @brief return likes, dislikes and attend status for item
2602 * @param array $item array
2604 * likes => int count
2605 * dislikes => int count
2607 function api_format_items_activities(&$item, $type = "json")
2611 $activities = array(
2613 'dislike' => array(),
2614 'attendyes' => array(),
2615 'attendno' => array(),
2616 'attendmaybe' => array(),
2621 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2622 intval($item['uid']),
2626 foreach ($items as $i) {
2627 // not used as result should be structured like other user data
2628 //builtin_activity_puller($i, $activities);
2630 // get user data and add it to the array of the activity
2631 $user = api_get_user($a, $i['author-link']);
2632 switch ($i['verb']) {
2634 $activities['like'][] = $user;
2636 case ACTIVITY_DISLIKE:
2637 $activities['dislike'][] = $user;
2639 case ACTIVITY_ATTEND:
2640 $activities['attendyes'][] = $user;
2642 case ACTIVITY_ATTENDNO:
2643 $activities['attendno'][] = $user;
2645 case ACTIVITY_ATTENDMAYBE:
2646 $activities['attendmaybe'][] = $user;
2653 if ($type == "xml") {
2654 $xml_activities = array();
2655 foreach ($activities as $k => $v) {
2656 // change xml element from "like" to "friendica:like"
2657 $xml_activities["friendica:".$k] = $v;
2658 // add user data into xml output
2660 foreach ($v as $user)
2661 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2663 $activities = $xml_activities;
2671 * @brief return data from profiles
2673 * @param array $profile array containing data from db table 'profile'
2674 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2677 function api_format_items_profiles(&$profile = null, $type = "json")
2679 if ($profile != null) {
2680 $profile = array('profile_id' => $profile['id'],
2681 'profile_name' => $profile['profile-name'],
2682 'is_default' => $profile['is-default'] ? true : false,
2683 'hide_friends'=> $profile['hide-friends'] ? true : false,
2684 'profile_photo' => $profile['photo'],
2685 'profile_thumb' => $profile['thumb'],
2686 'publish' => $profile['publish'] ? true : false,
2687 'net_publish' => $profile['net-publish'] ? true : false,
2688 'description' => $profile['pdesc'],
2689 'date_of_birth' => $profile['dob'],
2690 'address' => $profile['address'],
2691 'city' => $profile['locality'],
2692 'region' => $profile['region'],
2693 'postal_code' => $profile['postal-code'],
2694 'country' => $profile['country-name'],
2695 'hometown' => $profile['hometown'],
2696 'gender' => $profile['gender'],
2697 'marital' => $profile['marital'],
2698 'marital_with' => $profile['with'],
2699 'marital_since' => $profile['howlong'],
2700 'sexual' => $profile['sexual'],
2701 'politic' => $profile['politic'],
2702 'religion' => $profile['religion'],
2703 'public_keywords' => $profile['pub_keywords'],
2704 'private_keywords' => $profile['prv_keywords'],
2705 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2706 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2707 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2708 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2709 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2710 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2711 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2712 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2713 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2714 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2715 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2716 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2717 'homepage' => $profile['homepage'],
2724 * @brief format items to be returned by api
2726 * @param array $r array of items
2727 * @param array $user_info
2728 * @param bool $filter_user filter items by $user_info
2730 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2736 foreach ($r as $item) {
2737 localize_item($item);
2738 list($status_user, $owner_user) = api_item_get_user($a, $item);
2740 // Look if the posts are matching if they should be filtered by user id
2741 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2745 $in_reply_to = api_in_reply_to($item);
2747 $converted = api_convert_item($item);
2749 if ($type == "xml") {
2750 $geo = "georss:point";
2756 'text' => $converted["text"],
2757 'truncated' => false,
2758 'created_at'=> api_date($item['created']),
2759 'in_reply_to_status_id' => $in_reply_to['status_id'],
2760 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2761 'source' => (($item['app']) ? $item['app'] : 'web'),
2762 'id' => intval($item['id']),
2763 'id_str' => (string) intval($item['id']),
2764 'in_reply_to_user_id' => $in_reply_to['user_id'],
2765 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2766 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2768 'favorited' => $item['starred'] ? true : false,
2769 'user' => $status_user ,
2770 'friendica_owner' => $owner_user,
2771 //'entities' => NULL,
2772 'statusnet_html' => $converted["html"],
2773 'statusnet_conversation_id' => $item['parent'],
2774 'friendica_activities' => api_format_items_activities($item, $type),
2777 if (count($converted["attachments"]) > 0) {
2778 $status["attachments"] = $converted["attachments"];
2781 if (count($converted["entities"]) > 0) {
2782 $status["entities"] = $converted["entities"];
2785 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
2786 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2787 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2788 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2792 // Retweets are only valid for top postings
2793 // It doesn't work reliable with the link if its a feed
2794 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2796 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
2799 if ($item["id"] == $item["parent"]) {
2800 $retweeted_item = api_share_as_retweet($item);
2801 if ($retweeted_item !== false) {
2802 $retweeted_status = $status;
2804 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
2805 } catch (BadRequestException $e) {
2806 // user not found. should be found?
2807 /// @todo check if the user should be always found
2808 $retweeted_status["user"] = array();
2811 $rt_converted = api_convert_item($retweeted_item);
2813 $retweeted_status['text'] = $rt_converted["text"];
2814 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2815 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2816 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2817 $status['retweeted_status'] = $retweeted_status;
2821 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2822 unset($status["user"]["uid"]);
2823 unset($status["user"]["self"]);
2825 if ($item["coord"] != "") {
2826 $coords = explode(' ', $item["coord"]);
2827 if (count($coords) == 2) {
2828 if ($type == "json")
2829 $status["geo"] = array('type' => 'Point',
2830 'coordinates' => array((float) $coords[0],
2831 (float) $coords[1]));
2832 else // Not sure if this is the official format - if someone founds a documentation we can check
2833 $status["georss:point"] = $item["coord"];
2841 function api_account_rate_limit_status($type)
2843 if ($type == "xml") {
2845 'remaining-hits' => '150',
2846 '@attributes' => array("type" => "integer"),
2847 'hourly-limit' => '150',
2848 '@attributes2' => array("type" => "integer"),
2849 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
2850 '@attributes3' => array("type" => "datetime"),
2851 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2852 '@attributes4' => array("type" => "integer"),
2856 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2857 'remaining_hits' => '150',
2858 'hourly_limit' => '150',
2859 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
2863 return api_format_data('hash', $type, array('hash' => $hash));
2866 /// @TODO move to top of file or somwhere better
2867 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
2869 function api_help_test($type)
2871 if ($type == 'xml') {
2877 return api_format_data('ok', $type, array("ok" => $ok));
2880 /// @TODO move to top of file or somwhere better
2881 api_register_func('api/help/test', 'api_help_test', false);
2883 function api_lists($type)
2886 /// @TODO $ret is not filled here?
2887 return api_format_data('lists', $type, array("lists_list" => $ret));
2890 /// @TODO move to top of file or somwhere better
2891 api_register_func('api/lists', 'api_lists', true);
2893 function api_lists_list($type)
2896 /// @TODO $ret is not filled here?
2897 return api_format_data('lists', $type, array("lists_list" => $ret));
2900 /// @TODO move to top of file or somwhere better
2901 api_register_func('api/lists/list', 'api_lists_list', true);
2904 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2905 * This function is deprecated by Twitter
2906 * returns: json, xml
2908 function api_statuses_f($type, $qtype)
2912 if (api_user() === false) {
2913 throw new ForbiddenException();
2916 $user_info = api_get_user($a);
2918 if (x($_GET, 'cursor') && $_GET['cursor']=='undefined') {
2919 /* this is to stop Hotot to load friends multiple times
2920 * I'm not sure if I'm missing return something or
2921 * is a bug in hotot. Workaround, meantime
2925 return array('$users' => $ret);*/
2929 if ($qtype == 'friends') {
2930 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2932 if ($qtype == 'followers') {
2933 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2936 // friends and followers only for self
2937 if ($user_info['self'] == 0) {
2938 $sql_extra = " AND false ";
2942 "SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra ORDER BY `nick`",
2947 foreach ($r as $cid) {
2948 $user = api_get_user($a, $cid['nurl']);
2949 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2950 unset($user["uid"]);
2951 unset($user["self"]);
2958 return array('user' => $ret);
2962 function api_statuses_friends($type)
2964 $data = api_statuses_f($type, "friends");
2965 if ($data === false) {
2968 return api_format_data("users", $type, $data);
2971 function api_statuses_followers($type)
2973 $data = api_statuses_f($type, "followers");
2974 if ($data === false) {
2977 return api_format_data("users", $type, $data);
2980 /// @TODO move to top of file or somewhere better
2981 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
2982 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
2984 function api_statusnet_config($type)
2988 $name = $a->config['sitename'];
2989 $server = $a->get_hostname();
2990 $logo = System::baseUrl() . '/images/friendica-64.png';
2991 $email = $a->config['admin_email'];
2992 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2993 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
2994 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2995 if ($a->config['api_import_size']) {
2996 $texlimit = string($a->config['api_import_size']);
2998 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
2999 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3002 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3003 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3004 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3005 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3006 'shorturllength' => '30',
3007 'friendica' => array(
3008 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3009 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3010 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3011 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3016 return api_format_data('config', $type, array('config' => $config));
3019 /// @TODO move to top of file or somewhere better
3020 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3021 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3023 function api_statusnet_version($type)
3026 $fake_statusnet_version = "0.9.7";
3028 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
3031 /// @TODO move to top of file or somewhere better
3032 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3033 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3036 * @todo use api_format_data() to return data
3038 function api_ff_ids($type,$qtype)
3043 throw new ForbiddenException();
3046 $user_info = api_get_user($a);
3048 if ($qtype == 'friends') {
3049 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3051 if ($qtype == 'followers') {
3052 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3055 if (!$user_info["self"]) {
3056 $sql_extra = " AND false ";
3059 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3062 "SELECT `pcontact`.`id` FROM `contact`
3063 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3064 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3068 if (!DBM::is_result($r)) {
3073 foreach ($r as $rr) {
3074 if ($stringify_ids) {
3077 $ids[] = intval($rr['id']);
3081 return api_format_data("ids", $type, array('id' => $ids));
3084 function api_friends_ids($type)
3086 return api_ff_ids($type, 'friends');
3089 function api_followers_ids($type)
3091 return api_ff_ids($type, 'followers');
3094 /// @TODO move to top of file or somewhere better
3095 api_register_func('api/friends/ids', 'api_friends_ids', true);
3096 api_register_func('api/followers/ids', 'api_followers_ids', true);
3098 function api_direct_messages_new($type)
3103 if (api_user() === false) throw new ForbiddenException();
3105 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) return;
3107 $sender = api_get_user($a);
3109 if ($_POST['screen_name']) {
3111 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3113 dbesc($_POST['screen_name'])
3116 // Selecting the id by priority, friendica first
3117 api_best_nickname($r);
3119 $recipient = api_get_user($a, $r[0]['nurl']);
3121 $recipient = api_get_user($a, $_POST['user_id']);
3126 if (x($_REQUEST, 'replyto')) {
3128 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3130 intval($_REQUEST['replyto'])
3132 $replyto = $r[0]['parent-uri'];
3133 $sub = $r[0]['title'];
3135 if (x($_REQUEST, 'title')) {
3136 $sub = $_REQUEST['title'];
3138 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3142 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3145 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3146 $ret = api_format_messages($r[0], $recipient, $sender);
3148 $ret = array("error"=>$id);
3151 $data = array('direct_message'=>$ret);
3156 $data = api_rss_extra($a, $data, $user_info);
3159 return api_format_data("direct-messages", $type, $data);
3163 /// @TODO move to top of file or somewhere better
3164 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3167 * @brief delete a direct_message from mail table through api
3169 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3172 function api_direct_messages_destroy($type)
3176 if (api_user() === false) {
3177 throw new ForbiddenException();
3181 $user_info = api_get_user($a);
3183 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3185 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3186 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3187 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3189 $uid = $user_info['uid'];
3190 // error if no id or parenturi specified (for clients posting parent-uri as well)
3191 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3192 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3193 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3196 // BadRequestException if no id specified (for clients using Twitter API)
3198 throw new BadRequestException('Message id not specified');
3201 // add parent-uri to sql command if specified by calling app
3202 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3204 // get data of the specified message id
3206 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3211 // error message if specified id is not in database
3212 if (!DBM::is_result($r)) {
3213 if ($verbose == "true") {
3214 $answer = array('result' => 'error', 'message' => 'message id not in database');
3215 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3217 /// @todo BadRequestException ok for Twitter API clients?
3218 throw new BadRequestException('message id not in database');
3223 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3228 if ($verbose == "true") {
3231 $answer = array('result' => 'ok', 'message' => 'message deleted');
3232 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3234 $answer = array('result' => 'error', 'message' => 'unknown error');
3235 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3238 /// @todo return JSON data like Twitter API not yet implemented
3242 /// @TODO move to top of file or somewhere better
3243 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3245 function api_direct_messages_box($type, $box, $verbose)
3249 if (api_user() === false) {
3250 throw new ForbiddenException();
3254 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3255 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3260 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3261 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3263 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3264 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3267 unset($_REQUEST["user_id"]);
3268 unset($_GET["user_id"]);
3270 unset($_REQUEST["screen_name"]);
3271 unset($_GET["screen_name"]);
3273 $user_info = api_get_user($a);
3274 $profile_url = $user_info["url"];
3277 $start = $page * $count;
3280 if ($box=="sentbox") {
3281 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3282 } elseif ($box == "conversation") {
3283 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3284 } elseif ($box == "all") {
3285 $sql_extra = "true";
3286 } elseif ($box == "inbox") {
3287 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3291 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3294 if ($user_id != "") {
3295 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3296 } elseif ($screen_name !="") {
3297 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3301 "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",
3307 if ($verbose == "true" && !DBM::is_result($r)) {
3308 $answer = array('result' => 'error', 'message' => 'no mails available');
3309 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3313 foreach ($r as $item) {
3314 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3315 $recipient = $user_info;
3316 $sender = api_get_user($a, normalise_link($item['contact-url']));
3317 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3318 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3319 $sender = $user_info;
3322 $ret[] = api_format_messages($item, $recipient, $sender);
3326 $data = array('direct_message' => $ret);
3330 $data = api_rss_extra($a, $data, $user_info);
3333 return api_format_data("direct-messages", $type, $data);
3336 function api_direct_messages_sentbox($type)
3338 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3339 return api_direct_messages_box($type, "sentbox", $verbose);
3342 function api_direct_messages_inbox($type)
3344 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3345 return api_direct_messages_box($type, "inbox", $verbose);
3348 function api_direct_messages_all($type)
3350 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3351 return api_direct_messages_box($type, "all", $verbose);
3354 function api_direct_messages_conversation($type)
3356 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3357 return api_direct_messages_box($type, "conversation", $verbose);
3360 /// @TODO move to top of file or somewhere better
3361 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3362 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3363 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3364 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3366 function api_oauth_request_token($type)
3368 $oauth1 = new FKOAuth1();
3370 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3371 } catch (Exception $e) {
3372 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3379 function api_oauth_access_token($type)
3381 $oauth1 = new FKOAuth1();
3383 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3384 } catch (Exception $e) {
3385 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3392 /// @TODO move to top of file or somewhere better
3393 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3394 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3398 * @brief delete a complete photoalbum with all containing photos from database through api
3400 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3403 function api_fr_photoalbum_delete($type)
3405 if (api_user() === false) {
3406 throw new ForbiddenException();
3409 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3411 // we do not allow calls without album string
3413 throw new BadRequestException("no albumname specified");
3415 // check if album is existing
3417 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3421 if (!DBM::is_result($r))
3422 throw new BadRequestException("album not available");
3424 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3425 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3426 foreach ($r as $rr) {
3428 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3429 intval(local_user()),
3430 dbesc($rr['resource-id'])
3433 if (!DBM::is_result($photo_item)) {
3434 throw new InternalServerErrorException("problem with deleting items occured");
3436 drop_item($photo_item[0]['id'], false);
3439 // now let's delete all photos from the album
3440 $result = dba::delete('photo', array('uid' => api_user(), 'album' => $album));
3442 // return success of deletion or error message
3444 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3445 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3447 throw new InternalServerErrorException("unknown error - deleting from database failed");
3452 * @brief update the name of the album for all photos of an album
3454 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3457 function api_fr_photoalbum_update($type)
3459 if (api_user() === false) {
3460 throw new ForbiddenException();
3463 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3464 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3466 // we do not allow calls without album string
3468 throw new BadRequestException("no albumname specified");
3470 if ($album_new == "") {
3471 throw new BadRequestException("no new albumname specified");
3473 // check if album is existing
3475 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3479 if (!DBM::is_result($r)) {
3480 throw new BadRequestException("album not available");
3482 // now let's update all photos to the albumname
3484 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3490 // return success of updating or error message
3492 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3493 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3495 throw new InternalServerErrorException("unknown error - updating in database failed");
3501 * @brief list all photos of the authenticated user
3503 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3506 function api_fr_photos_list($type)
3508 if (api_user() === false) {
3509 throw new ForbiddenException();
3512 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3513 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3514 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3515 intval(local_user())
3518 'image/jpeg' => 'jpg',
3519 'image/png' => 'png',
3520 'image/gif' => 'gif'
3522 $data = array('photo'=>array());
3523 if (DBM::is_result($r)) {
3524 foreach ($r as $rr) {
3526 $photo['id'] = $rr['resource-id'];
3527 $photo['album'] = $rr['album'];
3528 $photo['filename'] = $rr['filename'];
3529 $photo['type'] = $rr['type'];
3530 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3531 $photo['created'] = $rr['created'];
3532 $photo['edited'] = $rr['edited'];
3533 $photo['desc'] = $rr['desc'];
3535 if ($type == "xml") {
3536 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3538 $photo['thumb'] = $thumb;
3539 $data['photo'][] = $photo;
3543 return api_format_data("photos", $type, $data);
3547 * @brief upload a new photo or change an existing photo
3549 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3552 function api_fr_photo_create_update($type)
3554 if (api_user() === false) {
3555 throw new ForbiddenException();
3558 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3559 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3560 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3561 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3562 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3563 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3564 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3565 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3566 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3568 // do several checks on input parameters
3569 // we do not allow calls without album string
3570 if ($album == null) {
3571 throw new BadRequestException("no albumname specified");
3573 // if photo_id == null --> we are uploading a new photo
3574 if ($photo_id == null) {
3577 // error if no media posted in create-mode
3578 if (!x($_FILES, 'media')) {
3580 throw new BadRequestException("no media data submitted");
3583 // album_new will be ignored in create-mode
3588 // check if photo is existing in database
3590 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3595 if (!DBM::is_result($r)) {
3596 throw new BadRequestException("photo not available");
3600 // checks on acl strings provided by clients
3601 $acl_input_error = false;
3602 $acl_input_error |= check_acl_input($allow_cid);
3603 $acl_input_error |= check_acl_input($deny_cid);
3604 $acl_input_error |= check_acl_input($allow_gid);
3605 $acl_input_error |= check_acl_input($deny_gid);
3606 if ($acl_input_error) {
3607 throw new BadRequestException("acl data invalid");
3609 // now let's upload the new media in create-mode
3610 if ($mode == "create") {
3611 $media = $_FILES['media'];
3612 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3614 // return success of updating or error message
3615 if (!is_null($data)) {
3616 return api_format_data("photo_create", $type, $data);
3618 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3622 // now let's do the changes in update-mode
3623 if ($mode == "update") {
3626 if (!is_null($desc)) {
3627 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3630 if (!is_null($album_new)) {
3631 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3634 if (!is_null($allow_cid)) {
3635 $allow_cid = trim($allow_cid);
3636 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3639 if (!is_null($deny_cid)) {
3640 $deny_cid = trim($deny_cid);
3641 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3644 if (!is_null($allow_gid)) {
3645 $allow_gid = trim($allow_gid);
3646 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3649 if (!is_null($deny_gid)) {
3650 $deny_gid = trim($deny_gid);
3651 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3655 if ($sql_extra != "") {
3656 $nothingtodo = false;
3658 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3660 datetime_convert(), // update edited timestamp
3666 $nothingtodo = true;
3669 if (x($_FILES, 'media')) {
3670 $nothingtodo = false;
3671 $media = $_FILES['media'];
3672 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3673 if (!is_null($data)) {
3674 return api_format_data("photo_update", $type, $data);
3678 // return success of updating or error message
3680 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
3681 return api_format_data("photo_update", $type, array('$result' => $answer));
3684 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
3685 return api_format_data("photo_update", $type, array('$result' => $answer));
3687 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3690 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3695 * @brief delete a single photo from the database through api
3697 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3700 function api_fr_photo_delete($type)
3702 if (api_user() === false) {
3703 throw new ForbiddenException();
3706 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3708 // do several checks on input parameters
3709 // we do not allow calls without photo id
3710 if ($photo_id == null) {
3711 throw new BadRequestException("no photo_id specified");
3713 // check if photo is existing in database
3715 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3719 if (!DBM::is_result($r)) {
3720 throw new BadRequestException("photo not available");
3722 // now we can perform on the deletion of the photo
3723 $result = dba::delete('photo', array('uid' => api_user(), 'resource-id' => $photo_id));
3725 // return success of deletion or error message
3727 // retrieve the id of the parent element (the photo element)
3729 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3730 intval(local_user()),
3734 if (!DBM::is_result($photo_item)) {
3735 throw new InternalServerErrorException("problem with deleting items occured");
3737 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3738 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
3739 drop_item($photo_item[0]['id'], false);
3741 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
3742 return api_format_data("photo_delete", $type, array('$result' => $answer));
3744 throw new InternalServerErrorException("unknown error on deleting photo from database table");
3750 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3752 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3755 function api_fr_photo_detail($type)
3757 if (api_user() === false) {
3758 throw new ForbiddenException();
3760 if (!x($_REQUEST, 'photo_id')) {
3761 throw new BadRequestException("No photo id.");
3764 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3765 $photo_id = $_REQUEST['photo_id'];
3767 // prepare json/xml output with data from database for the requested photo
3768 $data = prepare_photo_data($type, $scale, $photo_id);
3770 return api_format_data("photo_detail", $type, $data);
3775 * @brief updates the profile image for the user (either a specified profile or the default profile)
3777 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3780 function api_account_update_profile_image($type)
3782 if (api_user() === false) {
3783 throw new ForbiddenException();
3786 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
3788 // error if image data is missing
3789 if (!x($_FILES, 'image')) {
3790 throw new BadRequestException("no media data submitted");
3793 // check if specified profile id is valid
3794 if ($profileid != 0) {
3796 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
3800 // error message if specified profile id is not in database
3801 if (!DBM::is_result($r)) {
3802 throw new BadRequestException("profile_id not available");
3804 $is_default_profile = $r['profile'];
3806 $is_default_profile = 1;
3809 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3811 if (x($_FILES, 'image')) {
3812 $media = $_FILES['image'];
3813 } elseif (x($_FILES, 'media')) {
3814 $media = $_FILES['media'];
3816 // save new profile image
3817 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
3820 if (is_array($media['type'])) {
3821 $filetype = $media['type'][0];
3823 $filetype = $media['type'];
3825 if ($filetype == "image/jpeg") {
3827 } elseif ($filetype == "image/png") {
3830 // change specified profile or all profiles to the new resource-id
3831 if ($is_default_profile) {
3833 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
3834 dbesc($data['photo']['id']),
3835 intval(local_user())
3839 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
3840 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
3841 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
3842 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
3843 intval(local_user())
3847 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
3848 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
3849 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
3850 intval($_REQUEST['profile']),
3851 intval(local_user())
3855 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
3856 // so that browsers will do a cache update unconditionally
3859 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
3860 dbesc(datetime_convert()),
3861 intval(local_user())
3864 // Update global directory in background
3865 //$user = api_get_user(get_app());
3866 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
3867 if ($url && strlen(Config::get('system', 'directory'))) {
3868 Worker::add(PRIORITY_LOW, "Directory", $url);
3871 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
3873 // output for client
3875 return api_account_verify_credentials($type);
3877 // SaveMediaToDatabase failed for some reason
3878 throw new InternalServerErrorException("image upload failed");
3882 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3883 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
3884 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
3885 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3886 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3887 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3888 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
3889 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3890 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3893 function check_acl_input($acl_string)
3895 if ($acl_string == null || $acl_string == " ") {
3898 $contact_not_found = false;
3900 // split <x><y><z> into array of cid's
3901 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3903 // check for each cid if it is available on server
3904 $cid_array = $array[0];
3905 foreach ($cid_array as $cid) {
3906 $cid = str_replace("<", "", $cid);
3907 $cid = str_replace(">", "", $cid);
3909 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3913 $contact_not_found |= !DBM::is_result($contact);
3915 return $contact_not_found;
3918 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)
3926 if (is_array($media)) {
3927 if (is_array($media['tmp_name'])) {
3928 $src = $media['tmp_name'][0];
3930 $src = $media['tmp_name'];
3932 if (is_array($media['name'])) {
3933 $filename = basename($media['name'][0]);
3935 $filename = basename($media['name']);
3937 if (is_array($media['size'])) {
3938 $filesize = intval($media['size'][0]);
3940 $filesize = intval($media['size']);
3942 if (is_array($media['type'])) {
3943 $filetype = $media['type'][0];
3945 $filetype = $media['type'];
3949 if ($filetype == "") {
3950 $filetype=Image::guessType($filename);
3952 $imagedata = getimagesize($src);
3954 $filetype = $imagedata['mime'];
3957 "File upload src: " . $src . " - filename: " . $filename .
3958 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG
3961 // check if there was a php upload error
3962 if ($filesize == 0 && $media['error'] == 1) {
3963 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3965 // check against max upload size within Friendica instance
3966 $maximagesize = Config::get('system', 'maximagesize');
3967 if (($maximagesize) && ($filesize > $maximagesize)) {
3968 $formattedBytes = formatBytes($maximagesize);
3969 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3972 // create Photo instance with the data of the image
3973 $imagedata = @file_get_contents($src);
3974 $Image = new Image($imagedata, $filetype);
3975 if (! $Image->isValid()) {
3976 throw new InternalServerErrorException("unable to process image data");
3979 // check orientation of image
3980 $Image->orient($src);
3983 // check max length of images on server
3984 $max_length = Config::get('system', 'max_image_length');
3985 if (! $max_length) {
3986 $max_length = MAX_IMAGE_LENGTH;
3988 if ($max_length > 0) {
3989 $Image->scaleDown($max_length);
3990 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
3992 $width = $Image->getWidth();
3993 $height = $Image->getHeight();
3995 // create a new resource-id if not already provided
3996 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
3998 if ($mediatype == "photo") {
3999 // upload normal image (scales 0, 1, 2)
4000 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4002 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4004 logger("photo upload: image upload with scale 0 (original size) failed");
4006 if ($width > 640 || $height > 640) {
4007 $Image->scaleDown(640);
4008 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4010 logger("photo upload: image upload with scale 1 (640x640) failed");
4014 if ($width > 320 || $height > 320) {
4015 $Image->scaleDown(320);
4016 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4018 logger("photo upload: image upload with scale 2 (320x320) failed");
4021 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4022 } elseif ($mediatype == "profileimage") {
4023 // upload profile image (scales 4, 5, 6)
4024 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4026 if ($width > 175 || $height > 175) {
4027 $Image->scaleDown(175);
4028 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4030 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4034 if ($width > 80 || $height > 80) {
4035 $Image->scaleDown(80);
4036 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4038 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4042 if ($width > 48 || $height > 48) {
4043 $Image->scaleDown(48);
4044 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4046 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4049 $Image->__destruct();
4050 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4054 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4055 if ($photo_id == null && $mediatype == "photo") {
4056 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4058 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4059 return prepare_photo_data($type, false, $hash);
4061 throw new InternalServerErrorException("image upload failed");
4065 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4067 // get data about the api authenticated user
4068 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4069 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4072 $arr['guid'] = get_guid(32);
4073 $arr['uid'] = intval(api_user());
4075 $arr['parent-uri'] = $uri;
4076 $arr['type'] = 'photo';
4078 $arr['resource-id'] = $hash;
4079 $arr['contact-id'] = $owner_record[0]['id'];
4080 $arr['owner-name'] = $owner_record[0]['name'];
4081 $arr['owner-link'] = $owner_record[0]['url'];
4082 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4083 $arr['author-name'] = $owner_record[0]['name'];
4084 $arr['author-link'] = $owner_record[0]['url'];
4085 $arr['author-avatar'] = $owner_record[0]['thumb'];
4087 $arr['allow_cid'] = $allow_cid;
4088 $arr['allow_gid'] = $allow_gid;
4089 $arr['deny_cid'] = $deny_cid;
4090 $arr['deny_gid'] = $deny_gid;
4091 $arr['last-child'] = 1;
4092 $arr['visible'] = $visibility;
4096 'image/jpeg' => 'jpg',
4097 'image/png' => 'png',
4098 'image/gif' => 'gif'
4101 // adds link to the thumbnail scale photo
4102 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4103 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4106 // do the magic for storing the item in the database and trigger the federation to other contacts
4110 function prepare_photo_data($type, $scale, $photo_id)
4112 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4113 $data_sql = ($scale === false ? "" : "data, ");
4115 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4116 // clients needs to convert this in their way for further processing
4118 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4119 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4120 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4121 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4123 intval(local_user()),
4129 'image/jpeg' => 'jpg',
4130 'image/png' => 'png',
4131 'image/gif' => 'gif'
4134 // prepare output data for photo
4135 if (DBM::is_result($r)) {
4136 $data = array('photo' => $r[0]);
4137 $data['photo']['id'] = $data['photo']['resource-id'];
4138 if ($scale !== false) {
4139 $data['photo']['data'] = base64_encode($data['photo']['data']);
4141 unset($data['photo']['datasize']); //needed only with scale param
4143 if ($type == "xml") {
4144 $data['photo']['links'] = array();
4145 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4146 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4148 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4151 $data['photo']['link'] = array();
4152 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4154 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4155 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4159 unset($data['photo']['resource-id']);
4160 unset($data['photo']['minscale']);
4161 unset($data['photo']['maxscale']);
4163 throw new NotFoundException();
4166 // retrieve item element for getting activities (like, dislike etc.) related to photo
4168 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4169 intval(local_user()),
4172 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4174 // retrieve comments on photo
4176 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4177 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4178 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4179 `contact`.`id` AS `cid`
4181 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4182 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4183 WHERE `item`.`parent` = %d AND `item`.`visible`
4184 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4185 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4186 intval($item[0]['parent']),
4188 dbesc(ACTIVITY_POST)
4191 // prepare output of comments
4192 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4193 $comments = array();
4194 if ($type == "xml") {
4196 foreach ($commentData as $comment) {
4197 $comments[$k++ . ":comment"] = $comment;
4200 foreach ($commentData as $comment) {
4201 $comments[] = $comment;
4204 $data['photo']['friendica_comments'] = $comments;
4206 // include info if rights on photo and rights on item are mismatching
4207 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4208 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4209 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4210 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4211 $data['photo']['rights_mismatch'] = $rights_mismatch;
4218 * Similar as /mod/redir.php
4219 * redirect to 'url' after dfrn auth
4221 * Why this when there is mod/redir.php already?
4222 * This use api_user() and api_login()
4225 * c_url: url of remote contact to auth to
4226 * url: string, url to redirect after auth
4228 function api_friendica_remoteauth()
4230 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4231 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4233 if ($url === '' || $c_url === '') {
4234 throw new BadRequestException("Wrong parameters.");
4237 $c_url = normalise_link($c_url);
4242 "SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4247 if ((! DBM::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4248 throw new BadRequestException("Unknown contact");
4253 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4255 if ($r[0]['duplex'] && $r[0]['issued-id']) {
4256 $orig_id = $r[0]['issued-id'];
4257 $dfrn_id = '1:' . $orig_id;
4259 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4260 $orig_id = $r[0]['dfrn-id'];
4261 $dfrn_id = '0:' . $orig_id;
4264 $sec = random_string();
4267 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4268 VALUES( %d, %s, '%s', '%s', %d )",
4276 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4277 $dest = (($url) ? '&destination_url=' . $url : '');
4279 $r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4280 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4281 . '&type=profile&sec=' . $sec . $dest . $quiet
4284 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4287 * @brief Return the item shared, if the item contains only the [share] tag
4289 * @param array $item Sharer item
4290 * @return array Shared item or false if not a reshare
4292 function api_share_as_retweet(&$item)
4294 $body = trim($item["body"]);
4296 if (Diaspora::isReshare($body, false)===false) {
4300 /// @TODO "$1" should maybe mean '$1' ?
4301 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4303 * Skip if there is no shared message in there
4304 * we already checked this in diaspora::isReshare()
4305 * but better one more than one less...
4307 if ($body == $attributes) {
4312 // build the fake reshared item
4313 $reshared_item = $item;
4316 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4317 if ($matches[1] != "") {
4318 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4321 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4322 if ($matches[1] != "") {
4323 $author = $matches[1];
4327 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4328 if ($matches[1] != "") {
4329 $profile = $matches[1];
4332 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4333 if ($matches[1] != "") {
4334 $profile = $matches[1];
4338 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4339 if ($matches[1] != "") {
4340 $avatar = $matches[1];
4343 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4344 if ($matches[1] != "") {
4345 $avatar = $matches[1];
4349 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4350 if ($matches[1] != "") {
4351 $link = $matches[1];
4354 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4355 if ($matches[1] != "") {
4356 $link = $matches[1];
4360 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4361 if ($matches[1] != "")
4362 $posted = $matches[1];
4364 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4365 if ($matches[1] != "") {
4366 $posted = $matches[1];
4369 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4371 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4375 $reshared_item["body"] = $shared_body;
4376 $reshared_item["author-name"] = $author;
4377 $reshared_item["author-link"] = $profile;
4378 $reshared_item["author-avatar"] = $avatar;
4379 $reshared_item["plink"] = $link;
4380 $reshared_item["created"] = $posted;
4381 $reshared_item["edited"] = $posted;
4383 return $reshared_item;
4387 function api_get_nick($profile)
4390 - remove trailing junk from profile url
4391 - pump.io check has to check the website
4397 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4398 dbesc(normalise_link($profile))
4401 if (DBM::is_result($r)) {
4402 $nick = $r[0]["nick"];
4407 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4408 dbesc(normalise_link($profile))
4411 if (DBM::is_result($r)) {
4412 $nick = $r[0]["nick"];
4417 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4418 if ($friendica != $profile) {
4424 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4425 if ($diaspora != $profile) {
4431 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4432 if ($twitter != $profile) {
4439 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4440 if ($StatusnetHost != $profile) {
4441 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4442 if ($StatusnetUser != $profile) {
4443 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4444 $user = json_decode($UserData);
4446 $nick = $user->screen_name;
4452 // To-Do: look at the page if its really a pumpio site
4453 //if (!$nick == "") {
4454 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4455 // if ($pumpio != $profile)
4457 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4468 function api_in_reply_to($item)
4470 $in_reply_to = array();
4472 $in_reply_to['status_id'] = null;
4473 $in_reply_to['user_id'] = null;
4474 $in_reply_to['status_id_str'] = null;
4475 $in_reply_to['user_id_str'] = null;
4476 $in_reply_to['screen_name'] = null;
4478 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4479 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4480 intval($item['uid']),
4481 dbesc($item['thr-parent']));
4483 if (DBM::is_result($r)) {
4484 $in_reply_to['status_id'] = intval($r[0]['id']);
4486 $in_reply_to['status_id'] = intval($item['parent']);
4489 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4491 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4492 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4493 WHERE `item`.`id` = %d LIMIT 1",
4494 intval($in_reply_to['status_id'])
4497 if (DBM::is_result($r)) {
4498 if ($r[0]['nick'] == "") {
4499 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4502 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4503 $in_reply_to['user_id'] = intval($r[0]['id']);
4504 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4507 // There seems to be situation, where both fields are identical:
4508 // https://github.com/friendica/friendica/issues/1010
4509 // This is a bugfix for that.
4510 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4511 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4512 $in_reply_to['status_id'] = null;
4513 $in_reply_to['user_id'] = null;
4514 $in_reply_to['status_id_str'] = null;
4515 $in_reply_to['user_id_str'] = null;
4516 $in_reply_to['screen_name'] = null;
4520 return $in_reply_to;
4523 function api_clean_plain_items($Text)
4525 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4527 $Text = bb_CleanPictureLinks($Text);
4528 $URLSearchString = "^\[\]";
4530 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
4532 if ($include_entities == "true") {
4533 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
4536 // Simplify "attachment" element
4537 $Text = api_clean_attachments($Text);
4543 * @brief Removes most sharing information for API text export
4545 * @param string $body The original body
4547 * @return string Cleaned body
4549 function api_clean_attachments($body)
4551 $data = get_attachment_data($body);
4558 if (isset($data["text"]))
4559 $body = $data["text"];
4561 if (($body == "") && (isset($data["title"])))
4562 $body = $data["title"];
4564 if (isset($data["url"]))
4565 $body .= "\n".$data["url"];
4567 $body .= $data["after"];
4572 function api_best_nickname(&$contacts)
4574 $best_contact = array();
4576 if (count($contact) == 0)
4579 foreach ($contacts as $contact)
4580 if ($contact["network"] == "") {
4581 $contact["network"] = "dfrn";
4582 $best_contact = array($contact);
4585 if (sizeof($best_contact) == 0)
4586 foreach ($contacts as $contact)
4587 if ($contact["network"] == "dfrn")
4588 $best_contact = array($contact);
4590 if (sizeof($best_contact) == 0)
4591 foreach ($contacts as $contact)
4592 if ($contact["network"] == "dspr")
4593 $best_contact = array($contact);
4595 if (sizeof($best_contact) == 0)
4596 foreach ($contacts as $contact)
4597 if ($contact["network"] == "stat")
4598 $best_contact = array($contact);
4600 if (sizeof($best_contact) == 0)
4601 foreach ($contacts as $contact)
4602 if ($contact["network"] == "pump")
4603 $best_contact = array($contact);
4605 if (sizeof($best_contact) == 0)
4606 foreach ($contacts as $contact)
4607 if ($contact["network"] == "twit")
4608 $best_contact = array($contact);
4610 if (sizeof($best_contact) == 1) {
4611 $contacts = $best_contact;
4613 $contacts = array($contacts[0]);
4617 // return all or a specified group of the user with the containing contacts
4618 function api_friendica_group_show($type)
4622 if (api_user() === false) throw new ForbiddenException();
4625 $user_info = api_get_user($a);
4626 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4627 $uid = $user_info['uid'];
4629 // get data of the specified group id or all groups if not specified
4632 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4636 // error message if specified gid is not in database
4637 if (!DBM::is_result($r))
4638 throw new BadRequestException("gid not available");
4641 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4646 // loop through all groups and retrieve all members for adding data in the user array
4647 foreach ($r as $rr) {
4648 $members = Contact::getByGroupId($rr['id']);
4651 if ($type == "xml") {
4652 $user_element = "users";
4654 foreach ($members as $member) {
4655 $user = api_get_user($a, $member['nurl']);
4656 $users[$k++.":user"] = $user;
4659 $user_element = "user";
4660 foreach ($members as $member) {
4661 $user = api_get_user($a, $member['nurl']);
4665 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4667 return api_format_data("groups", $type, array('group' => $grps));
4669 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4672 // delete the specified group of the user
4673 function api_friendica_group_delete($type)
4677 if (api_user() === false) {
4678 throw new ForbiddenException();
4682 $user_info = api_get_user($a);
4683 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4684 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4685 $uid = $user_info['uid'];
4687 // error if no gid specified
4688 if ($gid == 0 || $name == "") {
4689 throw new BadRequestException('gid or name not specified');
4692 // get data of the specified group id
4694 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
4698 // error message if specified gid is not in database
4699 if (!DBM::is_result($r)) {
4700 throw new BadRequestException('gid not available');
4703 // get data of the specified group id and group name
4705 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
4710 // error message if specified gid is not in database
4711 if (!DBM::is_result($rname)) {
4712 throw new BadRequestException('wrong group name');
4716 $ret = Group::removeByName($uid, $name);
4719 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
4720 return api_format_data("group_delete", $type, array('result' => $success));
4722 throw new BadRequestException('other API error');
4725 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4728 // create the specified group with the posted array of contacts
4729 function api_friendica_group_create($type)
4733 if (api_user() === false) throw new ForbiddenException();
4736 $user_info = api_get_user($a);
4737 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4738 $uid = $user_info['uid'];
4739 $json = json_decode($_POST['json'], true);
4740 $users = $json['user'];
4742 // error if no name specified
4744 throw new BadRequestException('group name not specified');
4746 // get data of the specified group name
4748 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
4752 // error message if specified group name already exists
4753 if (DBM::is_result($rname))
4754 throw new BadRequestException('group name already exists');
4756 // check if specified group name is a deleted group
4758 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
4762 // error message if specified group name already exists
4763 if (DBM::is_result($rname))
4764 $reactivate_group = true;
4767 $ret = Group::create($uid, $name);
4769 $gid = Group::getIdByName($uid, $name);
4771 throw new BadRequestException('other API error');
4775 $erroraddinguser = false;
4776 $errorusers = array();
4777 foreach ($users as $user) {
4778 $cid = $user['cid'];
4779 // check if user really exists as contact
4781 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4785 if (count($contact))
4786 $result = Group::create_member($uid, $name, $cid, $gid);
4788 $erroraddinguser = true;
4789 $errorusers[] = $cid;
4793 // return success message incl. missing users in array
4794 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
4795 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4796 return api_format_data("group_create", $type, array('result' => $success));
4798 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4801 // update the specified group with the posted array of contacts
4802 function api_friendica_group_update($type)
4806 if (api_user() === false) throw new ForbiddenException();
4809 $user_info = api_get_user($a);
4810 $uid = $user_info['uid'];
4811 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4812 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4813 $json = json_decode($_POST['json'], true);
4814 $users = $json['user'];
4816 // error if no name specified
4818 throw new BadRequestException('group name not specified');
4820 // error if no gid specified
4822 throw new BadRequestException('gid not specified');
4825 $members = Contact::getByGroupId($gid);
4826 foreach ($members as $member) {
4827 $cid = $member['id'];
4828 foreach ($users as $user) {
4829 $found = ($user['cid'] == $cid ? true : false);
4832 $ret = Group::removeMemberByName($uid, $name, $cid);
4837 $erroraddinguser = false;
4838 $errorusers = array();
4839 foreach ($users as $user) {
4840 $cid = $user['cid'];
4841 // check if user really exists as contact
4843 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4848 if (count($contact)) {
4849 $result = Group::create_member($uid, $name, $cid, $gid);
4851 $erroraddinguser = true;
4852 $errorusers[] = $cid;
4856 // return success message incl. missing users in array
4857 $status = ($erroraddinguser ? "missing user" : "ok");
4858 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4859 return api_format_data("group_update", $type, array('result' => $success));
4862 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4864 function api_friendica_activity($type)
4868 if (api_user() === false) throw new ForbiddenException();
4869 $verb = strtolower($a->argv[3]);
4870 $verb = preg_replace("|\..*$|", "", $verb);
4872 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4874 $res = do_like($id, $verb);
4877 if ($type == "xml") {
4882 return api_format_data('ok', $type, array('ok' => $ok));
4884 throw new BadRequestException('Error adding activity');
4888 /// @TODO move to top of file or somwhere better
4889 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
4890 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
4891 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
4892 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
4893 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4894 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
4895 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
4896 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
4897 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
4898 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4901 * @brief Returns notifications
4903 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4906 function api_friendica_notification($type)
4910 if (api_user() === false) throw new ForbiddenException();
4911 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
4912 $nm = new NotificationsManager();
4914 $notes = $nm->getAll(array(), "+seen -date", 50);
4916 if ($type == "xml") {
4917 $xmlnotes = array();
4918 foreach ($notes as $note)
4919 $xmlnotes[] = array("@attributes" => $note);
4924 return api_format_data("notes", $type, array('note' => $notes));
4928 * @brief Set notification as seen and returns associated item (if possible)
4930 * POST request with 'id' param as notification id
4932 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4935 function api_friendica_notification_seen($type)
4939 if (api_user() === false) throw new ForbiddenException();
4940 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
4942 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
4944 $nm = new NotificationsManager();
4945 $note = $nm->getByID($id);
4946 if (is_null($note)) throw new BadRequestException("Invalid argument");
4948 $nm->setSeen($note);
4949 if ($note['otype']=='item') {
4950 // would be really better with an ItemsManager and $im->getByID() :-P
4952 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
4953 intval($note['iid']),
4954 intval(local_user())
4957 // we found the item, return it to the user
4958 $user_info = api_get_user($a);
4959 $ret = api_format_items($r, $user_info, false, $type);
4960 $data = array('status' => $ret);
4961 return api_format_data("status", $type, $data);
4963 // the item can't be found, but we set the note as seen, so we count this as a success
4965 return api_format_data('result', $type, array('result' => "success"));
4968 /// @TODO move to top of file or somwhere better
4969 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4970 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
4973 * @brief update a direct_message to seen state
4975 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4976 * @return string (success result=ok, error result=error with error message)
4978 function api_friendica_direct_messages_setseen($type)
4981 if (api_user() === false) {
4982 throw new ForbiddenException();
4986 $user_info = api_get_user($a);
4987 $uid = $user_info['uid'];
4988 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4990 // return error if id is zero
4992 $answer = array('result' => 'error', 'message' => 'message id not specified');
4993 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4996 // get data of the specified message id
4998 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5003 // error message if specified id is not in database
5004 if (!DBM::is_result($r)) {
5005 $answer = array('result' => 'error', 'message' => 'message id not in database');
5006 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5009 // update seen indicator
5011 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5018 $answer = array('result' => 'ok', 'message' => 'message set to seen');
5019 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
5021 $answer = array('result' => 'error', 'message' => 'unknown error');
5022 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5026 /// @TODO move to top of file or somwhere better
5027 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5030 * @brief search for direct_messages containing a searchstring through api
5032 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5033 * @return string (success: success=true if found and search_result contains found messages
5034 * success=false if nothing was found, search_result='nothing found',
5035 * error: result=error with error message)
5037 function api_friendica_direct_messages_search($type)
5041 if (api_user() === false) {
5042 throw new ForbiddenException();
5046 $user_info = api_get_user($a);
5047 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5048 $uid = $user_info['uid'];
5050 // error if no searchstring specified
5051 if ($searchstring == "") {
5052 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
5053 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
5056 // get data for the specified searchstring
5058 "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",
5060 dbesc('%'.$searchstring.'%')
5063 $profile_url = $user_info["url"];
5065 // message if nothing was found
5066 if (!DBM::is_result($r)) {
5067 $success = array('success' => false, 'search_results' => 'problem with query');
5068 } elseif (count($r) == 0) {
5069 $success = array('success' => false, 'search_results' => 'nothing found');
5072 foreach ($r as $item) {
5073 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5074 $recipient = $user_info;
5075 $sender = api_get_user($a, normalise_link($item['contact-url']));
5076 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5077 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5078 $sender = $user_info;
5081 $ret[] = api_format_messages($item, $recipient, $sender);
5083 $success = array('success' => true, 'search_results' => $ret);
5086 return api_format_data("direct_message_search", $type, array('$result' => $success));
5089 /// @TODO move to top of file or somwhere better
5090 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5093 * @brief return data of all the profiles a user has to the client
5095 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5098 function api_friendica_profile_show($type)
5102 if (api_user() === false) {
5103 throw new ForbiddenException();
5107 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5109 // retrieve general information about profiles for user
5110 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5111 $directory = Config::get('system', 'directory');
5113 // get data of the specified profile id or all profiles of the user if not specified
5114 if ($profileid != 0) {
5116 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5121 // error message if specified gid is not in database
5122 if (!DBM::is_result($r)) {
5123 throw new BadRequestException("profile_id not available");
5127 "SELECT * FROM `profile` WHERE `uid` = %d",
5131 // loop through all returned profiles and retrieve data and users
5133 foreach ($r as $rr) {
5134 $profile = api_format_items_profiles($rr, $type);
5136 // select all users from contact table, loop and prepare standard return for user data
5139 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5141 intval($rr['profile_id'])
5144 foreach ($r as $rr) {
5145 $user = api_get_user($a, $rr['nurl']);
5146 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5148 $profile['users'] = $users;
5150 // add prepared profile data to array for final return
5151 if ($type == "xml") {
5152 $profiles[$k++ . ":profile"] = $profile;
5154 $profiles[] = $profile;
5158 // return settings, authenticated user and profiles data
5159 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5161 $result = array('multi_profiles' => $multi_profiles ? true : false,
5162 'global_dir' => $directory,
5163 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5164 'profiles' => $profiles);
5165 return api_format_data("friendica_profiles", $type, array('$result' => $result));
5167 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5170 @TODO Maybe open to implement?
5172 [pagename] => api/1.1/statuses/lookup.json
5173 [id] => 605138389168451584
5174 [include_cards] => true
5175 [cards_platform] => Android-12
5176 [include_entities] => true
5177 [include_my_retweet] => 1
5179 [include_reply_count] => true
5180 [include_descendent_reply_count] => true
5184 Not implemented by now:
5185 statuses/retweets_of_me
5190 account/update_location
5191 account/update_profile_background_image
5194 friendica/profile/update
5195 friendica/profile/create
5196 friendica/profile/delete
5198 Not implemented in status.net:
5199 statuses/retweeted_to_me
5200 statuses/retweeted_by_me
5201 direct_messages/destroy
5203 account/update_delivery_device
5204 notifications/follow