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\User;
16 use Friendica\Network\HTTPException;
17 use Friendica\Network\HTTPException\BadRequestException;
18 use Friendica\Network\HTTPException\ForbiddenException;
19 use Friendica\Network\HTTPException\InternalServerErrorException;
20 use Friendica\Network\HTTPException\MethodNotAllowedException;
21 use Friendica\Network\HTTPException\NotFoundException;
22 use Friendica\Network\HTTPException\NotImplementedException;
23 use Friendica\Network\HTTPException\UnauthorizedException;
24 use Friendica\Network\HTTPException\TooManyRequestsException;
25 use Friendica\Object\Contact;
26 use Friendica\Object\Photo;
27 use Friendica\Protocol\Diaspora;
28 use Friendica\Util\XML;
30 require_once 'include/bbcode.php';
31 require_once 'include/datetime.php';
32 require_once 'include/conversation.php';
33 require_once 'include/oauth.php';
34 require_once 'include/html2plain.php';
35 require_once 'mod/share.php';
36 require_once 'mod/item.php';
37 require_once 'include/security.php';
38 require_once 'include/contact_selectors.php';
39 require_once 'include/html2bbcode.php';
40 require_once 'mod/wall_upload.php';
41 require_once 'mod/proxy.php';
42 require_once 'include/message.php';
43 require_once 'include/group.php';
44 require_once 'include/like.php';
45 require_once 'include/plaintext.php';
47 define('API_METHOD_ANY', '*');
48 define('API_METHOD_GET', 'GET');
49 define('API_METHOD_POST', 'POST,PUT');
50 define('API_METHOD_DELETE', 'POST,DELETE');
56 * @brief Auth API user
58 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
59 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
60 * into a page, and visitors will post something without noticing it).
64 if (x($_SESSION, 'allow_api')) {
72 * @brief Get source name from API client
74 * Clients can send 'source' parameter to be show in post metadata
75 * as "sent via <source>".
76 * Some clients doesn't send a source param, we support ones we know
80 * Client source name, default to "api" if unset/unknown
84 if (requestdata('source')) {
85 return requestdata('source');
88 // Support for known clients that doesn't send a source name
89 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
93 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
99 * @brief Format date for API
101 * @param string $str Source date, as UTC
102 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
104 function api_date($str)
106 // Wed May 23 06:01:13 +0000 2007
107 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y");
111 * @brief Register API endpoint
113 * Register a function to be the endpont for defined API path.
115 * @param string $path API URL path, relative to System::baseUrl()
116 * @param string $func Function name to call on path request
117 * @param bool $auth API need logged user
118 * @param string $method HTTP method reqiured to call this endpoint.
119 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
120 * Default to API_METHOD_ANY
122 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
132 // Workaround for hotot
133 $path = str_replace("api/", "api/1.1/", $path);
143 * @brief Login API user
145 * Log in user via OAuth1 or Simple HTTP Auth.
146 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
148 * @param object $a App
149 * @hook 'authenticate'
151 * 'username' => username from login form
152 * 'password' => password from login form
153 * 'authenticated' => return status,
154 * 'user_record' => return authenticated user record
156 * array $user logged user record
158 function api_login(App $a)
162 $oauth = new FKOAuth1();
163 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
164 if (!is_null($token)) {
165 $oauth->loginUser($token->uid);
166 call_hooks('logged_in', $a->user);
169 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
170 var_dump($consumer, $token);
172 } catch (Exception $e) {
176 // workaround for HTTP-auth in CGI mode
177 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
178 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
179 if (strlen($userpass)) {
180 list($name, $password) = explode(':', $userpass);
181 $_SERVER['PHP_AUTH_USER'] = $name;
182 $_SERVER['PHP_AUTH_PW'] = $password;
186 if (!x($_SERVER, 'PHP_AUTH_USER')) {
187 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
188 header('WWW-Authenticate: Basic realm="Friendica"');
189 throw new UnauthorizedException("This API requires login");
192 $user = $_SERVER['PHP_AUTH_USER'];
193 $password = $_SERVER['PHP_AUTH_PW'];
195 // allow "user@server" login (but ignore 'server' part)
196 $at = strstr($user, "@", true);
201 // next code from mod/auth.php. needs better solution
205 'username' => trim($user),
206 'password' => trim($password),
207 'authenticated' => 0,
208 'user_record' => null,
212 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
213 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
214 * and later plugins should not interfere with an earlier one that succeeded.
216 call_hooks('authenticate', $addon_auth);
218 if (($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
219 $record = $addon_auth['user_record'];
221 $user_id = User::authenticate(trim($user), trim($password));
223 $record = dba::select('user', [], ['uid' => $user_id], ['limit' => 1]);
227 if ((! $record) || (! count($record))) {
228 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
229 header('WWW-Authenticate: Basic realm="Friendica"');
230 //header('HTTP/1.0 401 Unauthorized');
231 //die('This api requires login');
232 throw new UnauthorizedException("This API requires login");
235 authenticate_success($record);
237 $_SESSION["allow_api"] = true;
239 call_hooks('logged_in', $a->user);
243 * @brief Check HTTP method of called API
245 * API endpoints can define which HTTP method to accept when called.
246 * This function check the current HTTP method agains endpoint
249 * @param string $method Required methods, uppercase, separated by comma
252 function api_check_method($method)
254 if ($method == "*") {
257 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
261 * @brief Main API entry point
263 * Authenticate user, call registered API function, set HTTP headers
265 * @param object $a App
266 * @return string API call result
268 function api_call(App $a)
270 global $API, $called_api;
273 if (strpos($a->query_string, ".xml") > 0) {
276 if (strpos($a->query_string, ".json") > 0) {
279 if (strpos($a->query_string, ".rss") > 0) {
282 if (strpos($a->query_string, ".atom") > 0) {
287 foreach ($API as $p => $info) {
288 if (strpos($a->query_string, $p) === 0) {
289 if (!api_check_method($info['method'])) {
290 throw new MethodNotAllowedException();
293 $called_api = explode("/", $p);
294 //unset($_SERVER['PHP_AUTH_USER']);
296 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
297 if ($info['auth'] === true && api_user() === false) {
301 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
302 logger('API parameters: ' . print_r($_REQUEST, true));
304 $stamp = microtime(true);
305 $r = call_user_func($info['func'], $type);
306 $duration = (float) (microtime(true) - $stamp);
307 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
309 if (Config::get("system", "profiler")) {
310 $duration = microtime(true)-$a->performance["start"];
312 /// @TODO round() really everywhere?
314 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
315 "Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
316 round($a->performance["database"] - $a->performance["database_write"], 3),
317 round($a->performance["database_write"], 3),
318 round($a->performance["network"], 2),
319 round($a->performance["file"], 2),
320 round($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
326 if (Config::get("rendertime", "callstack")) {
327 $o = "Database Read:\n";
328 foreach ($a->callstack["database"] as $func => $time) {
329 $time = round($time, 3);
331 $o .= $func . ": " . $time . "\n";
334 $o .= "\nDatabase Write:\n";
335 foreach ($a->callstack["database_write"] as $func => $time) {
336 $time = round($time, 3);
338 $o .= $func . ": " . $time . "\n";
342 $o .= "\nNetwork:\n";
343 foreach ($a->callstack["network"] as $func => $time) {
344 $time = round($time, 3);
346 $o .= $func . ": " . $time . "\n";
349 logger($o, LOGGER_DEBUG);
355 * api function returned false withour throw an
356 * exception. This should not happend, throw a 500
358 throw new InternalServerErrorException();
363 header("Content-Type: text/xml");
367 header("Content-Type: application/json");
369 $json = json_encode($rr);
370 if (x($_GET, 'callback')) {
371 $json = $_GET['callback'] . "(" . $json . ")";
376 header("Content-Type: application/rss+xml");
377 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
380 header("Content-Type: application/atom+xml");
381 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
387 logger('API call not implemented: ' . $a->query_string);
388 throw new NotImplementedException();
389 } catch (HTTPException $e) {
390 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
391 return api_error($type, $e);
396 * @brief Format API error string
398 * @param string $type Return type (xml, json, rss, as)
399 * @param object $e HTTPException Error object
400 * @return strin error message formatted as $type
402 function api_error($type, $e)
406 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
407 /// @TODO: https://dev.twitter.com/overview/api/response-codes
409 $error = array("error" => $error,
410 "code" => $e->httpcode . " " . $e->httpdesc,
411 "request" => $a->query_string);
413 $ret = api_format_data('status', $type, array('status' => $error));
417 header("Content-Type: text/xml");
421 header("Content-Type: application/json");
422 return json_encode($ret);
425 header("Content-Type: application/rss+xml");
429 header("Content-Type: application/atom+xml");
436 * @brief Set values for RSS template
439 * @param array $arr Array to be passed to template
440 * @param array $user_info User info
442 * @todo find proper type-hints
444 function api_rss_extra(App $a, $arr, $user_info)
446 if (is_null($user_info)) {
447 $user_info = api_get_user($a);
450 $arr['$user'] = $user_info;
451 $arr['$rss'] = array(
452 'alternate' => $user_info['url'],
453 'self' => System::baseUrl() . "/" . $a->query_string,
454 'base' => System::baseUrl(),
455 'updated' => api_date(null),
456 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
457 'language' => $user_info['language'],
458 'logo' => System::baseUrl() . "/images/friendica-32.png",
466 * @brief Unique contact to contact url.
468 * @param int $id Contact id
469 * @return bool|string
470 * Contact url or False if contact id is unknown
472 function api_unique_id_to_url($id)
474 $r = dba::select('contact', array('url'), array('uid' => 0, 'id' => $id), array('limit' => 1));
476 if (DBM::is_result($r)) {
484 * @brief Get user info array.
486 * @param object $a App
487 * @param int|string $contact_id Contact ID or URL
488 * @param string $type Return type (for errors)
490 function api_get_user(App $a, $contact_id = null, $type = "json")
499 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
501 // Searching for contact URL
502 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
503 $user = dbesc(normalise_link($contact_id));
505 $extra_query = "AND `contact`.`nurl` = '%s' ";
506 if (api_user() !== false) {
507 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
511 // Searching for contact id with uid = 0
512 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
513 $user = dbesc(api_unique_id_to_url($contact_id));
516 throw new BadRequestException("User not found.");
520 $extra_query = "AND `contact`.`nurl` = '%s' ";
521 if (api_user() !== false) {
522 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
526 if (is_null($user) && x($_GET, 'user_id')) {
527 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
530 throw new BadRequestException("User not found.");
534 $extra_query = "AND `contact`.`nurl` = '%s' ";
535 if (api_user() !== false) {
536 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
539 if (is_null($user) && x($_GET, 'screen_name')) {
540 $user = dbesc($_GET['screen_name']);
542 $extra_query = "AND `contact`.`nick` = '%s' ";
543 if (api_user() !== false) {
544 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
548 if (is_null($user) && x($_GET, 'profileurl')) {
549 $user = dbesc(normalise_link($_GET['profileurl']));
551 $extra_query = "AND `contact`.`nurl` = '%s' ";
552 if (api_user() !== false) {
553 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
557 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
558 $argid = count($called_api);
559 list($user, $null) = explode(".", $a->argv[$argid]);
560 if (is_numeric($user)) {
561 $user = dbesc(api_unique_id_to_url($user));
568 $extra_query = "AND `contact`.`nurl` = '%s' ";
569 if (api_user() !== false) {
570 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
573 $user = dbesc($user);
575 $extra_query = "AND `contact`.`nick` = '%s' ";
576 if (api_user() !== false) {
577 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
582 logger("api_get_user: user ".$user, LOGGER_DEBUG);
585 if (api_user() === false) {
589 $user = $_SESSION['uid'];
590 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
594 logger('api_user: ' . $extra_query . ', user: ' . $user);
598 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
604 // Selecting the id by priority, friendica first
605 api_best_nickname($uinfo);
607 // if the contact wasn't found, fetch it from the contacts with uid = 0
608 if (!DBM::is_result($uinfo)) {
612 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
615 if (DBM::is_result($r)) {
616 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
618 // If no nick where given, extract it from the address
619 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
620 $r[0]['nick'] = api_get_nick($r[0]["url"]);
625 'id_str' => (string) $r[0]["id"],
626 'name' => $r[0]["name"],
627 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
628 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
629 'description' => $r[0]["about"],
630 'profile_image_url' => $r[0]["micro"],
631 'profile_image_url_https' => $r[0]["micro"],
632 'url' => $r[0]["url"],
633 'protected' => false,
634 'followers_count' => 0,
635 'friends_count' => 0,
637 'created_at' => api_date($r[0]["created"]),
638 'favourites_count' => 0,
640 'time_zone' => 'UTC',
641 'geo_enabled' => false,
643 'statuses_count' => 0,
645 'contributors_enabled' => false,
646 'is_translator' => false,
647 'is_translation_enabled' => false,
648 'following' => false,
649 'follow_request_sent' => false,
650 'statusnet_blocking' => false,
651 'notifications' => false,
652 'statusnet_profile_url' => $r[0]["url"],
654 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
656 'network' => $r[0]["network"],
661 throw new BadRequestException("User not found.");
665 if ($uinfo[0]['self']) {
666 if ($uinfo[0]['network'] == "") {
667 $uinfo[0]['network'] = NETWORK_DFRN;
671 "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
675 "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
679 /// @TODO old-lost code? (twice)
680 // Counting is deactivated by now, due to performance issues
681 // count public wall messages
682 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
683 // intval($uinfo[0]['uid'])
685 //$countitms = $r[0]['count'];
688 // Counting is deactivated by now, due to performance issues
689 //$r = q("SELECT count(*) as `count` FROM `item`
690 // WHERE `contact-id` = %d",
691 // intval($uinfo[0]['id'])
693 //$countitms = $r[0]['count'];
697 /// @TODO old-lost code? (twice)
699 // Counting is deactivated by now, due to performance issues
701 $r = q("SELECT count(*) as `count` FROM `contact`
702 WHERE `uid` = %d AND `rel` IN ( %d, %d )
703 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
704 intval($uinfo[0]['uid']),
705 intval(CONTACT_IS_SHARING),
706 intval(CONTACT_IS_FRIEND)
708 $countfriends = $r[0]['count'];
710 $r = q("SELECT count(*) as `count` FROM `contact`
711 WHERE `uid` = %d AND `rel` IN ( %d, %d )
712 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
713 intval($uinfo[0]['uid']),
714 intval(CONTACT_IS_FOLLOWER),
715 intval(CONTACT_IS_FRIEND)
717 $countfollowers = $r[0]['count'];
719 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
720 intval($uinfo[0]['uid'])
722 $starred = $r[0]['count'];
725 if (! $uinfo[0]['self']) {
735 // Add a nick if it isn't present there
736 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
737 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
740 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
742 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
745 'id' => intval($pcontact_id),
746 'id_str' => (string) intval($pcontact_id),
747 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
748 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
749 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
750 'description' => (($profile) ? $profile[0]['pdesc'] : null),
751 'profile_image_url' => $uinfo[0]['micro'],
752 'profile_image_url_https' => $uinfo[0]['micro'],
753 'url' => $uinfo[0]['url'],
754 'protected' => false,
755 'followers_count' => intval($countfollowers),
756 'friends_count' => intval($countfriends),
758 'created_at' => api_date($uinfo[0]['created']),
759 'favourites_count' => intval($starred),
761 'time_zone' => 'UTC',
762 'geo_enabled' => false,
764 'statuses_count' => intval($countitms),
766 'contributors_enabled' => false,
767 'is_translator' => false,
768 'is_translation_enabled' => false,
769 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
770 'follow_request_sent' => false,
771 'statusnet_blocking' => false,
772 'notifications' => false,
774 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
775 'statusnet_profile_url' => $uinfo[0]['url'],
776 'uid' => intval($uinfo[0]['uid']),
777 'cid' => intval($uinfo[0]['cid']),
778 'self' => $uinfo[0]['self'],
779 'network' => $uinfo[0]['network'],
786 * @brief return api-formatted array for item's author and owner
788 * @param object $a App
789 * @param array $item item from db
790 * @return array(array:author, array:owner)
792 function api_item_get_user(App $a, $item)
794 $status_user = api_get_user($a, $item["author-link"]);
796 $status_user["protected"] = (($item["allow_cid"] != "") ||
797 ($item["allow_gid"] != "") ||
798 ($item["deny_cid"] != "") ||
799 ($item["deny_gid"] != "") ||
802 if ($item['thr-parent'] == $item['uri']) {
803 $owner_user = api_get_user($a, $item["owner-link"]);
805 $owner_user = $status_user;
808 return (array($status_user, $owner_user));
812 * @brief walks recursively through an array with the possibility to change value and key
814 * @param array $array The array to walk through
815 * @param string $callback The callback function
817 * @return array the transformed array
819 function api_walk_recursive(array &$array, callable $callback)
821 $new_array = array();
823 foreach ($array as $k => $v) {
825 if ($callback($v, $k)) {
826 $new_array[$k] = api_walk_recursive($v, $callback);
829 if ($callback($v, $k)) {
840 * @brief Callback function to transform the array in an array that can be transformed in a XML file
842 * @param mixed $item Array item value
843 * @param string $key Array key
845 * @return boolean Should the array item be deleted?
847 function api_reformat_xml(&$item, &$key)
849 if (is_bool($item)) {
850 $item = ($item ? "true" : "false");
853 if (substr($key, 0, 10) == "statusnet_") {
854 $key = "statusnet:".substr($key, 10);
855 } elseif (substr($key, 0, 10) == "friendica_") {
856 $key = "friendica:".substr($key, 10);
858 /// @TODO old-lost code?
860 // $key = "default:".$key;
866 * @brief Creates the XML from a JSON style array
868 * @param array $data JSON style array
869 * @param string $root_element Name of the root element
871 * @return string The XML data
873 function api_create_xml($data, $root_element)
875 $childname = key($data);
876 $data2 = array_pop($data);
879 $namespaces = array("" => "http://api.twitter.com",
880 "statusnet" => "http://status.net/schema/api/1/",
881 "friendica" => "http://friendi.ca/schema/api/1/",
882 "georss" => "http://www.georss.org/georss");
884 /// @todo Auto detection of needed namespaces
885 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
886 $namespaces = array();
889 if (is_array($data2)) {
890 api_walk_recursive($data2, "api_reformat_xml");
897 foreach ($data2 as $item) {
898 $data4[$i++.":".$childname] = $item;
904 $data3 = array($root_element => $data2);
906 $ret = XML::fromArray($data3, $xml, false, $namespaces);
911 * @brief Formats the data according to the data type
913 * @param string $root_element Name of the root element
914 * @param string $type Return type (atom, rss, xml, json)
915 * @param array $data JSON style array
917 * @return (string|object) XML data or JSON data
919 function api_format_data($root_element, $type, $data)
927 $ret = api_create_xml($data, $root_element);
942 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
943 * returns a 401 status code and an error message if not.
944 * http://developer.twitter.com/doc/get/account/verify_credentials
946 function api_account_verify_credentials($type)
951 if (api_user() === false) {
952 throw new ForbiddenException();
955 unset($_REQUEST["user_id"]);
956 unset($_GET["user_id"]);
958 unset($_REQUEST["screen_name"]);
959 unset($_GET["screen_name"]);
961 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
963 $user_info = api_get_user($a);
965 // "verified" isn't used here in the standard
966 unset($user_info["verified"]);
968 // - Adding last status
970 $user_info["status"] = api_status_show("raw");
971 if (!count($user_info["status"])) {
972 unset($user_info["status"]);
974 unset($user_info["status"]["user"]);
978 // "uid" and "self" are only needed for some internal stuff, so remove it from here
979 unset($user_info["uid"]);
980 unset($user_info["self"]);
982 return api_format_data("user", $type, array('user' => $user_info));
985 /// @TODO move to top of file or somwhere better
986 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
989 * Get data from $_POST or $_GET
991 function requestdata($k)
1002 /*Waitman Gobble Mod*/
1003 function api_statuses_mediap($type)
1007 if (api_user() === false) {
1008 logger('api_statuses_update: no user');
1009 throw new ForbiddenException();
1011 $user_info = api_get_user($a);
1013 $_REQUEST['type'] = 'wall';
1014 $_REQUEST['profile_uid'] = api_user();
1015 $_REQUEST['api_source'] = true;
1016 $txt = requestdata('status');
1017 /// @TODO old-lost code?
1018 //$txt = urldecode(requestdata('status'));
1020 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1021 $txt = html2bb_video($txt);
1022 $config = HTMLPurifier_Config::createDefault();
1023 $config->set('Cache.DefinitionImpl', null);
1024 $purifier = new HTMLPurifier($config);
1025 $txt = $purifier->purify($txt);
1027 $txt = html2bbcode($txt);
1029 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1031 // tell wall_upload function to return img info instead of echo
1032 $_REQUEST['hush'] = 'yeah';
1033 $bebop = wall_upload_post($a);
1035 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1036 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1039 // this should output the last post (the one we just posted).
1040 return api_status_show($type);
1043 /// @TODO move this to top of file or somewhere better!
1044 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1046 function api_statuses_update($type)
1051 if (api_user() === false) {
1052 logger('api_statuses_update: no user');
1053 throw new ForbiddenException();
1056 $user_info = api_get_user($a);
1058 // convert $_POST array items to the form we use for web posts.
1060 // logger('api_post: ' . print_r($_POST,true));
1062 if (requestdata('htmlstatus')) {
1063 $txt = requestdata('htmlstatus');
1064 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1065 $txt = html2bb_video($txt);
1067 $config = HTMLPurifier_Config::createDefault();
1068 $config->set('Cache.DefinitionImpl', null);
1070 $purifier = new HTMLPurifier($config);
1071 $txt = $purifier->purify($txt);
1073 $_REQUEST['body'] = html2bbcode($txt);
1076 $_REQUEST['body'] = requestdata('status');
1079 $_REQUEST['title'] = requestdata('title');
1081 $parent = requestdata('in_reply_to_status_id');
1083 // Twidere sends "-1" if it is no reply ...
1084 if ($parent == -1) {
1088 if (ctype_digit($parent)) {
1089 $_REQUEST['parent'] = $parent;
1091 $_REQUEST['parent_uri'] = $parent;
1094 if (requestdata('lat') && requestdata('long')) {
1095 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1097 $_REQUEST['profile_uid'] = api_user();
1100 $_REQUEST['type'] = 'net-comment';
1102 // Check for throttling (maximum posts per day, week and month)
1103 $throttle_day = Config::get('system', 'throttle_limit_day');
1104 if ($throttle_day > 0) {
1105 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1108 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1109 AND `created` > '%s' AND `id` = `parent`",
1114 if (DBM::is_result($r)) {
1115 $posts_day = $r[0]["posts_day"];
1120 if ($posts_day > $throttle_day) {
1121 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1122 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1123 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1127 $throttle_week = Config::get('system', 'throttle_limit_week');
1128 if ($throttle_week > 0) {
1129 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1132 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1133 AND `created` > '%s' AND `id` = `parent`",
1138 if (DBM::is_result($r)) {
1139 $posts_week = $r[0]["posts_week"];
1144 if ($posts_week > $throttle_week) {
1145 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1146 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1147 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1151 $throttle_month = Config::get('system', 'throttle_limit_month');
1152 if ($throttle_month > 0) {
1153 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1156 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1157 AND `created` > '%s' AND `id` = `parent`",
1162 if (DBM::is_result($r)) {
1163 $posts_month = $r[0]["posts_month"];
1168 if ($posts_month > $throttle_month) {
1169 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1170 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1171 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1175 $_REQUEST['type'] = 'wall';
1178 if (x($_FILES, 'media')) {
1179 // upload the image if we have one
1180 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1181 $media = wall_upload_post($a);
1182 if (strlen($media) > 0) {
1183 $_REQUEST['body'] .= "\n\n" . $media;
1187 // To-Do: Multiple IDs
1188 if (requestdata('media_ids')) {
1190 "SELECT `resource-id`, `scale`, `nickname`, `type` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1",
1191 intval(requestdata('media_ids')),
1194 if (DBM::is_result($r)) {
1195 $phototypes = Photo::supportedTypes();
1196 $ext = $phototypes[$r[0]['type']];
1197 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1198 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1202 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1204 $_REQUEST['api_source'] = true;
1206 if (!x($_REQUEST, "source")) {
1207 $_REQUEST["source"] = api_source();
1210 // call out normal post function
1213 // this should output the last post (the one we just posted).
1214 return api_status_show($type);
1217 /// @TODO move to top of file or somwhere better
1218 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1219 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1221 function api_media_upload($type)
1225 if (api_user() === false) {
1227 throw new ForbiddenException();
1230 $user_info = api_get_user($a);
1232 if (!x($_FILES, 'media')) {
1234 throw new BadRequestException("No media.");
1237 $media = wall_upload_post($a, false);
1240 throw new InternalServerErrorException();
1243 $returndata = array();
1244 $returndata["media_id"] = $media["id"];
1245 $returndata["media_id_string"] = (string)$media["id"];
1246 $returndata["size"] = $media["size"];
1247 $returndata["image"] = array("w" => $media["width"],
1248 "h" => $media["height"],
1249 "image_type" => $media["type"]);
1251 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1253 return array("media" => $returndata);
1256 /// @TODO move to top of file or somwhere better
1257 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1259 function api_status_show($type)
1263 $user_info = api_get_user($a);
1265 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1267 if ($type == "raw") {
1268 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1273 // get last public wall message
1277 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1278 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1279 AND `item`.`type` != 'activity' $privacy_sql
1280 ORDER BY `item`.`id` DESC
1282 intval($user_info['cid']),
1284 dbesc($user_info['url']),
1285 dbesc(normalise_link($user_info['url'])),
1286 dbesc($user_info['url']),
1287 dbesc(normalise_link($user_info['url']))
1290 if (DBM::is_result($lastwall)) {
1291 $lastwall = $lastwall[0];
1293 $in_reply_to = api_in_reply_to($lastwall);
1295 $converted = api_convert_item($lastwall);
1297 if ($type == "xml") {
1298 $geo = "georss:point";
1303 $status_info = array(
1304 'created_at' => api_date($lastwall['created']),
1305 'id' => intval($lastwall['id']),
1306 'id_str' => (string) $lastwall['id'],
1307 'text' => $converted["text"],
1308 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1309 'truncated' => false,
1310 'in_reply_to_status_id' => $in_reply_to['status_id'],
1311 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1312 'in_reply_to_user_id' => $in_reply_to['user_id'],
1313 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1314 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1315 'user' => $user_info,
1317 'coordinates' => "",
1319 'contributors' => "",
1320 'is_quote_status' => false,
1321 'retweet_count' => 0,
1322 'favorite_count' => 0,
1323 'favorited' => $lastwall['starred'] ? true : false,
1324 'retweeted' => false,
1325 'possibly_sensitive' => false,
1327 'statusnet_html' => $converted["html"],
1328 'statusnet_conversation_id' => $lastwall['parent'],
1331 if (count($converted["attachments"]) > 0) {
1332 $status_info["attachments"] = $converted["attachments"];
1335 if (count($converted["entities"]) > 0) {
1336 $status_info["entities"] = $converted["entities"];
1339 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1340 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1341 } elseif (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1342 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1345 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1346 unset($status_info["user"]["uid"]);
1347 unset($status_info["user"]["self"]);
1350 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1352 if ($type == "raw") {
1353 return $status_info;
1356 return api_format_data("statuses", $type, array('status' => $status_info));
1360 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1361 * The author's most recent status will be returned inline.
1362 * http://developer.twitter.com/doc/get/users/show
1364 function api_users_show($type)
1368 $user_info = api_get_user($a);
1372 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1373 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1374 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1375 AND `type`!='activity'
1376 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1380 dbesc(ACTIVITY_POST),
1381 intval($user_info['cid']),
1382 dbesc($user_info['url']),
1383 dbesc(normalise_link($user_info['url'])),
1384 dbesc($user_info['url']),
1385 dbesc(normalise_link($user_info['url']))
1388 if (DBM::is_result($lastwall)) {
1389 $lastwall = $lastwall[0];
1391 $in_reply_to = api_in_reply_to($lastwall);
1393 $converted = api_convert_item($lastwall);
1395 if ($type == "xml") {
1396 $geo = "georss:point";
1401 $user_info['status'] = array(
1402 'text' => $converted["text"],
1403 'truncated' => false,
1404 'created_at' => api_date($lastwall['created']),
1405 'in_reply_to_status_id' => $in_reply_to['status_id'],
1406 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1407 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1408 'id' => intval($lastwall['contact-id']),
1409 'id_str' => (string) $lastwall['contact-id'],
1410 'in_reply_to_user_id' => $in_reply_to['user_id'],
1411 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1412 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1414 'favorited' => $lastwall['starred'] ? true : false,
1415 'statusnet_html' => $converted["html"],
1416 'statusnet_conversation_id' => $lastwall['parent'],
1419 if (count($converted["attachments"]) > 0) {
1420 $user_info["status"]["attachments"] = $converted["attachments"];
1423 if (count($converted["entities"]) > 0) {
1424 $user_info["status"]["entities"] = $converted["entities"];
1427 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1428 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1431 if (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1432 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
1436 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1437 unset($user_info["uid"]);
1438 unset($user_info["self"]);
1440 return api_format_data("user", $type, array('user' => $user_info));
1443 /// @TODO move to top of file or somewhere better
1444 api_register_func('api/users/show', 'api_users_show');
1445 api_register_func('api/externalprofile/show', 'api_users_show');
1447 function api_users_search($type)
1451 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1453 $userlist = array();
1455 if (x($_GET, 'q')) {
1456 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1458 if (!DBM::is_result($r)) {
1459 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1462 if (DBM::is_result($r)) {
1464 foreach ($r as $user) {
1465 $user_info = api_get_user($a, $user["id"], "json");
1467 if ($type == "xml") {
1468 $userlist[$k++.":user"] = $user_info;
1470 $userlist[] = $user_info;
1473 $userlist = array("users" => $userlist);
1475 throw new BadRequestException("User not found.");
1478 throw new BadRequestException("User not found.");
1480 return api_format_data("users", $type, $userlist);
1483 /// @TODO move to top of file or somewhere better
1484 api_register_func('api/users/search', 'api_users_search');
1488 * http://developer.twitter.com/doc/get/statuses/home_timeline
1490 * TODO: Optional parameters
1491 * TODO: Add reply info
1493 function api_statuses_home_timeline($type)
1497 if (api_user() === false) {
1498 throw new ForbiddenException();
1501 unset($_REQUEST["user_id"]);
1502 unset($_GET["user_id"]);
1504 unset($_REQUEST["screen_name"]);
1505 unset($_GET["screen_name"]);
1507 $user_info = api_get_user($a);
1508 // get last newtork messages
1511 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1512 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1516 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1517 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1518 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1519 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1520 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1522 $start = $page * $count;
1526 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1528 if ($exclude_replies > 0) {
1529 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1531 if ($conversation_id > 0) {
1532 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1536 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1537 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1538 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1539 `contact`.`id` AS `cid`
1541 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1542 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1543 WHERE `item`.`uid` = %d AND `verb` = '%s'
1544 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1547 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1549 dbesc(ACTIVITY_POST),
1555 $ret = api_format_items($r, $user_info, false, $type);
1557 // Set all posts from the query above to seen
1559 foreach ($r as $item) {
1560 $idarray[] = intval($item["id"]);
1563 $idlist = implode(",", $idarray);
1565 if ($idlist != "") {
1566 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1569 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1573 $data = array('status' => $ret);
1577 $data = api_rss_extra($a, $data, $user_info);
1581 return api_format_data("statuses", $type, $data);
1584 /// @TODO move to top of file or somewhere better
1585 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1586 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1588 function api_statuses_public_timeline($type)
1592 if (api_user() === false) {
1593 throw new ForbiddenException();
1596 $user_info = api_get_user($a);
1597 // get last newtork messages
1600 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1601 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1605 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1606 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1607 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1608 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1609 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1611 $start = $page * $count;
1614 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1616 if ($exclude_replies > 0) {
1617 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1619 if ($conversation_id > 0) {
1620 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1624 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1625 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1626 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1627 `contact`.`id` AS `cid`,
1628 `user`.`nickname`, `user`.`hidewall`
1630 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1631 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1632 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1633 AND NOT `user`.`hidewall`
1634 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1635 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1636 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1637 AND NOT `item`.`private` AND `item`.`wall`
1640 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1641 dbesc(ACTIVITY_POST),
1647 $ret = api_format_items($r, $user_info, false, $type);
1649 $data = array('status' => $ret);
1653 $data = api_rss_extra($a, $data, $user_info);
1657 return api_format_data("statuses", $type, $data);
1660 /// @TODO move to top of file or somewhere better
1661 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1664 * @TODO nothing to say?
1666 function api_statuses_show($type)
1670 if (api_user() === false) {
1671 throw new ForbiddenException();
1674 $user_info = api_get_user($a);
1677 $id = intval($a->argv[3]);
1680 $id = intval($_REQUEST["id"]);
1685 $id = intval($a->argv[4]);
1688 logger('API: api_statuses_show: ' . $id);
1690 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1693 if ($conversation) {
1694 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1696 $sql_extra .= " AND `item`.`id` = %d";
1700 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1701 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1702 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1703 `contact`.`id` AS `cid`
1705 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1706 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1707 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1708 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1711 dbesc(ACTIVITY_POST),
1715 /// @TODO How about copying this to above methods which don't check $r ?
1716 if (!DBM::is_result($r)) {
1717 throw new BadRequestException("There is no status with this id.");
1720 $ret = api_format_items($r, $user_info, false, $type);
1722 if ($conversation) {
1723 $data = array('status' => $ret);
1724 return api_format_data("statuses", $type, $data);
1726 $data = array('status' => $ret[0]);
1727 return api_format_data("status", $type, $data);
1731 /// @TODO move to top of file or somewhere better
1732 api_register_func('api/statuses/show', 'api_statuses_show', true);
1735 * @TODO nothing to say?
1737 function api_conversation_show($type)
1741 if (api_user() === false) {
1742 throw new ForbiddenException();
1745 $user_info = api_get_user($a);
1748 $id = intval($a->argv[3]);
1749 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1750 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1754 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1755 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1757 $start = $page*$count;
1760 $id = intval($_REQUEST["id"]);
1765 $id = intval($a->argv[4]);
1768 logger('API: api_conversation_show: '.$id);
1770 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1771 if (DBM::is_result($r)) {
1772 $id = $r[0]["parent"];
1778 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1781 // Not sure why this query was so complicated. We should keep it here for a while,
1782 // just to make sure that we really don't need it.
1783 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1784 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1787 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1788 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1789 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1790 `contact`.`id` AS `cid`
1792 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1793 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1794 WHERE `item`.`parent` = %d AND `item`.`visible`
1795 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1796 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1797 AND `item`.`id`>%d $sql_extra
1798 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1799 intval($id), intval(api_user()),
1800 dbesc(ACTIVITY_POST),
1802 intval($start), intval($count)
1805 if (!DBM::is_result($r)) {
1806 throw new BadRequestException("There is no status with this id.");
1809 $ret = api_format_items($r, $user_info, false, $type);
1811 $data = array('status' => $ret);
1812 return api_format_data("statuses", $type, $data);
1815 /// @TODO move to top of file or somewhere better
1816 api_register_func('api/conversation/show', 'api_conversation_show', true);
1817 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1820 * @TODO nothing to say?
1822 function api_statuses_repeat($type)
1828 if (api_user() === false) {
1829 throw new ForbiddenException();
1832 $user_info = api_get_user($a);
1835 $id = intval($a->argv[3]);
1838 $id = intval($_REQUEST["id"]);
1843 $id = intval($a->argv[4]);
1846 logger('API: api_statuses_repeat: '.$id);
1849 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1850 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1851 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1852 `contact`.`id` AS `cid`
1854 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1855 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1856 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1857 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1858 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1860 AND `item`.`id`=%d",
1864 /// @TODO other style than above functions!
1865 if (DBM::is_result($r) && $r[0]['body'] != "") {
1866 if (strpos($r[0]['body'], "[/share]") !== false) {
1867 $pos = strpos($r[0]['body'], "[share");
1868 $post = substr($r[0]['body'], $pos);
1870 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1872 $post .= $r[0]['body'];
1873 $post .= "[/share]";
1875 $_REQUEST['body'] = $post;
1876 $_REQUEST['profile_uid'] = api_user();
1877 $_REQUEST['type'] = 'wall';
1878 $_REQUEST['api_source'] = true;
1880 if (!x($_REQUEST, "source")) {
1881 $_REQUEST["source"] = api_source();
1886 throw new ForbiddenException();
1889 // this should output the last post (the one we just posted).
1891 return api_status_show($type);
1894 /// @TODO move to top of file or somewhere better
1895 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1898 * @TODO nothing to say?
1900 function api_statuses_destroy($type)
1904 if (api_user() === false) {
1905 throw new ForbiddenException();
1908 $user_info = api_get_user($a);
1911 $id = intval($a->argv[3]);
1914 $id = intval($_REQUEST["id"]);
1919 $id = intval($a->argv[4]);
1922 logger('API: api_statuses_destroy: '.$id);
1924 $ret = api_statuses_show($type);
1926 drop_item($id, false);
1931 /// @TODO move to top of file or somewhere better
1932 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1935 * @TODO Nothing more than an URL to say?
1936 * http://developer.twitter.com/doc/get/statuses/mentions
1938 function api_statuses_mentions($type)
1942 if (api_user() === false) {
1943 throw new ForbiddenException();
1946 unset($_REQUEST["user_id"]);
1947 unset($_GET["user_id"]);
1949 unset($_REQUEST["screen_name"]);
1950 unset($_GET["screen_name"]);
1952 $user_info = api_get_user($a);
1953 // get last newtork messages
1957 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1958 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1962 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1963 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1964 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1966 $start = $page * $count;
1968 // Ugly code - should be changed
1969 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
1970 $myurl = substr($myurl, strpos($myurl, '://') + 3);
1971 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1972 $myurl = str_replace('www.', '', $myurl);
1973 $diasp_url = str_replace('/profile/', '/u/', $myurl);
1976 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1980 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1981 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1982 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1983 `contact`.`id` AS `cid`
1984 FROM `item` FORCE INDEX (`uid_id`)
1985 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1986 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1987 WHERE `item`.`uid` = %d AND `verb` = '%s'
1988 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1989 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1990 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1993 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1995 dbesc(ACTIVITY_POST),
1996 dbesc(protect_sprintf($myurl)),
1997 dbesc(protect_sprintf($myurl)),
2004 $ret = api_format_items($r, $user_info, false, $type);
2006 $data = array('status' => $ret);
2010 $data = api_rss_extra($a, $data, $user_info);
2014 return api_format_data("statuses", $type, $data);
2017 /// @TODO move to top of file or somewhere better
2018 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2019 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2021 function api_statuses_user_timeline($type)
2025 if (api_user() === false) {
2026 throw new ForbiddenException();
2029 $user_info = api_get_user($a);
2030 // get last network messages
2033 "api_statuses_user_timeline: api_user: ". api_user() .
2034 "\nuser_info: ".print_r($user_info, true) .
2035 "\n_REQUEST: ".print_r($_REQUEST, true),
2040 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2041 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2045 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2046 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2047 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
2048 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
2050 $start = $page * $count;
2053 if ($user_info['self'] == 1) {
2054 $sql_extra .= " AND `item`.`wall` = 1 ";
2057 if ($exclude_replies > 0) {
2058 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2060 if ($conversation_id > 0) {
2061 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2065 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2066 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2067 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2068 `contact`.`id` AS `cid`
2069 FROM `item` FORCE INDEX (`uid_contactid_id`)
2070 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2071 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2072 WHERE `item`.`uid` = %d AND `verb` = '%s'
2073 AND `item`.`contact-id` = %d
2074 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2077 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2079 dbesc(ACTIVITY_POST),
2080 intval($user_info['cid']),
2086 $ret = api_format_items($r, $user_info, true, $type);
2088 $data = array('status' => $ret);
2092 $data = api_rss_extra($a, $data, $user_info);
2096 return api_format_data("statuses", $type, $data);
2099 /// @TODO move to top of file or somwhere better
2100 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2103 * Star/unstar an item
2104 * param: id : id of the item
2106 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2108 function api_favorites_create_destroy($type)
2112 if (api_user() === false) {
2113 throw new ForbiddenException();
2116 // for versioned api.
2117 /// @TODO We need a better global soluton
2118 $action_argv_id = 2;
2119 if ($a->argv[1] == "1.1") {
2120 $action_argv_id = 3;
2123 if ($a->argc <= $action_argv_id) {
2124 throw new BadRequestException("Invalid request.");
2126 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2127 if ($a->argc == $action_argv_id + 2) {
2128 $itemid = intval($a->argv[$action_argv_id + 1]);
2130 /// @TODO use x() to check if _REQUEST contains 'id'
2131 $itemid = intval($_REQUEST['id']);
2134 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2136 if (!DBM::is_result($item) || count($item) == 0) {
2137 throw new BadRequestException("Invalid item.");
2142 $item[0]['starred'] = 1;
2145 $item[0]['starred'] = 0;
2148 throw new BadRequestException("Invalid action ".$action);
2151 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2153 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2156 throw new InternalServerErrorException("DB error");
2160 $user_info = api_get_user($a);
2161 $rets = api_format_items($item, $user_info, false, $type);
2164 $data = array('status' => $ret);
2168 $data = api_rss_extra($a, $data, $user_info);
2171 return api_format_data("status", $type, $data);
2174 /// @TODO move to top of file or somwhere better
2175 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2176 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2178 function api_favorites($type)
2184 if (api_user() === false) {
2185 throw new ForbiddenException();
2188 $called_api = array();
2190 $user_info = api_get_user($a);
2192 // in friendica starred item are private
2193 // return favorites only for self
2194 logger('api_favorites: self:' . $user_info['self']);
2196 if ($user_info['self'] == 0) {
2202 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2203 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2204 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2205 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2210 $start = $page*$count;
2213 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2217 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2218 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2219 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2220 `contact`.`id` AS `cid`
2221 FROM `item`, `contact`
2222 WHERE `item`.`uid` = %d
2223 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2224 AND `item`.`starred` = 1
2225 AND `contact`.`id` = `item`.`contact-id`
2226 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2229 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2236 $ret = api_format_items($r, $user_info, false, $type);
2239 $data = array('status' => $ret);
2243 $data = api_rss_extra($a, $data, $user_info);
2246 return api_format_data("statuses", $type, $data);
2249 /// @TODO move to top of file or somwhere better
2250 api_register_func('api/favorites', 'api_favorites', true);
2252 function api_format_messages($item, $recipient, $sender)
2254 // standard meta information
2256 'id' => $item['id'],
2257 'sender_id' => $sender['id'] ,
2259 'recipient_id' => $recipient['id'],
2260 'created_at' => api_date($item['created']),
2261 'sender_screen_name' => $sender['screen_name'],
2262 'recipient_screen_name' => $recipient['screen_name'],
2263 'sender' => $sender,
2264 'recipient' => $recipient,
2266 'friendica_seen' => $item['seen'],
2267 'friendica_parent_uri' => $item['parent-uri'],
2270 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2271 unset($ret["sender"]["uid"]);
2272 unset($ret["sender"]["self"]);
2273 unset($ret["recipient"]["uid"]);
2274 unset($ret["recipient"]["self"]);
2276 //don't send title to regular StatusNET requests to avoid confusing these apps
2277 if (x($_GET, 'getText')) {
2278 $ret['title'] = $item['title'];
2279 if ($_GET['getText'] == 'html') {
2280 $ret['text'] = bbcode($item['body'], false, false);
2281 } elseif ($_GET['getText'] == 'plain') {
2282 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2283 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2286 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2288 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2289 unset($ret['sender']);
2290 unset($ret['recipient']);
2296 function api_convert_item($item)
2298 $body = $item['body'];
2299 $attachments = api_get_attachments($body);
2301 // Workaround for ostatus messages where the title is identically to the body
2302 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2303 $statusbody = trim(html2plain($html, 0));
2305 // handle data: images
2306 $statusbody = api_format_items_embeded_images($item, $statusbody);
2308 $statustitle = trim($item['title']);
2310 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2311 $statustext = trim($statusbody);
2313 $statustext = trim($statustitle."\n\n".$statusbody);
2316 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2317 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2320 $statushtml = trim(bbcode($body, false, false));
2322 // Workaround for clients with limited HTML parser functionality
2323 $search = array("<br>", "<blockquote>", "</blockquote>",
2324 "<h1>", "</h1>", "<h2>", "</h2>",
2325 "<h3>", "</h3>", "<h4>", "</h4>",
2326 "<h5>", "</h5>", "<h6>", "</h6>");
2327 $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2328 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2329 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2330 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2331 $statushtml = str_replace($search, $replace, $statushtml);
2333 if ($item['title'] != "") {
2334 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2338 $oldtext = $statushtml;
2339 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2340 } while ($oldtext != $statushtml);
2342 if (substr($statushtml, 0, 4) == '<br>') {
2343 $statushtml = substr($statushtml, 4);
2346 if (substr($statushtml, 0, -4) == '<br>') {
2347 $statushtml = substr($statushtml, -4);
2350 // feeds without body should contain the link
2351 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2352 $statushtml .= bbcode($item['plink']);
2355 $entities = api_get_entitities($statustext, $body);
2358 "text" => $statustext,
2359 "html" => $statushtml,
2360 "attachments" => $attachments,
2361 "entities" => $entities
2365 function api_get_attachments(&$body)
2368 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2370 $URLSearchString = "^\[\]";
2371 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2377 $attachments = array();
2379 foreach ($images[1] as $image) {
2380 $imagedata = Photo::getInfoFromURL($image);
2383 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2387 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2388 foreach ($images[0] as $orig) {
2389 $body = str_replace($orig, "", $body);
2393 return $attachments;
2396 function api_get_entitities(&$text, $bbcode)
2400 * Links at the first character of the post
2405 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2407 if ($include_entities != "true") {
2408 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2410 foreach ($images[1] as $image) {
2411 $replace = proxy_url($image);
2412 $text = str_replace($image, $replace, $text);
2417 $bbcode = bb_CleanPictureLinks($bbcode);
2419 // Change pure links in text to bbcode uris
2420 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2422 $entities = array();
2423 $entities["hashtags"] = array();
2424 $entities["symbols"] = array();
2425 $entities["urls"] = array();
2426 $entities["user_mentions"] = array();
2428 $URLSearchString = "^\[\]";
2430 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2432 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2433 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2434 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2436 $bbcode = preg_replace(
2437 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2438 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2441 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2443 $bbcode = preg_replace(
2444 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2445 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2448 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2450 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2452 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2453 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2455 $ordered_urls = array();
2456 foreach ($urls[1] as $id => $url) {
2457 //$start = strpos($text, $url, $offset);
2458 $start = iconv_strpos($text, $url, 0, "UTF-8");
2459 if (!($start === false)) {
2460 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2464 ksort($ordered_urls);
2467 //foreach ($urls[1] AS $id=>$url) {
2468 foreach ($ordered_urls as $url) {
2469 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2470 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2472 $display_url = $url["title"];
2474 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2475 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2477 if (strlen($display_url) > 26)
2478 $display_url = substr($display_url, 0, 25)."…";
2481 //$start = strpos($text, $url, $offset);
2482 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2483 if (!($start === false)) {
2484 $entities["urls"][] = array("url" => $url["url"],
2485 "expanded_url" => $url["url"],
2486 "display_url" => $display_url,
2487 "indices" => array($start, $start+strlen($url["url"])));
2488 $offset = $start + 1;
2492 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2493 $ordered_images = array();
2494 foreach ($images[1] as $image) {
2495 //$start = strpos($text, $url, $offset);
2496 $start = iconv_strpos($text, $image, 0, "UTF-8");
2497 if (!($start === false))
2498 $ordered_images[$start] = $image;
2500 //$entities["media"] = array();
2503 foreach ($ordered_images as $url) {
2504 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2505 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2507 if (strlen($display_url) > 26)
2508 $display_url = substr($display_url, 0, 25)."…";
2510 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2511 if (!($start === false)) {
2512 $image = Photo::getInfoFromURL($url);
2514 // If image cache is activated, then use the following sizes:
2515 // thumb (150), small (340), medium (600) and large (1024)
2516 if (!Config::get("system", "proxy_disabled")) {
2517 $media_url = proxy_url($url);
2520 $scale = Photo::scaleImageTo($image[0], $image[1], 150);
2521 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2523 if (($image[0] > 150) || ($image[1] > 150)) {
2524 $scale = Photo::scaleImageTo($image[0], $image[1], 340);
2525 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2528 $scale = Photo::scaleImageTo($image[0], $image[1], 600);
2529 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2531 if (($image[0] > 600) || ($image[1] > 600)) {
2532 $scale = Photo::scaleImageTo($image[0], $image[1], 1024);
2533 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2537 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2540 $entities["media"][] = array(
2542 "id_str" => (string)$start+1,
2543 "indices" => array($start, $start+strlen($url)),
2544 "media_url" => normalise_link($media_url),
2545 "media_url_https" => $media_url,
2547 "display_url" => $display_url,
2548 "expanded_url" => $url,
2552 $offset = $start + 1;
2558 function api_format_items_embeded_images(&$item, $text)
2560 $text = preg_replace_callback(
2561 "|data:image/([^;]+)[^=]+=*|m",
2562 function ($match) use ($item) {
2563 return System::baseUrl()."/display/".$item['guid'];
2572 * @brief return <a href='url'>name</a> as array
2574 * @param string $txt text
2579 function api_contactlink_to_array($txt)
2582 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2583 if ($r && count($match)==3) {
2585 'name' => $match[2],
2599 * @brief return likes, dislikes and attend status for item
2601 * @param array $item array
2603 * likes => int count
2604 * dislikes => int count
2606 function api_format_items_activities(&$item, $type = "json")
2610 $activities = array(
2612 'dislike' => array(),
2613 'attendyes' => array(),
2614 'attendno' => array(),
2615 'attendmaybe' => array(),
2620 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2621 intval($item['uid']),
2625 foreach ($items as $i) {
2626 // not used as result should be structured like other user data
2627 //builtin_activity_puller($i, $activities);
2629 // get user data and add it to the array of the activity
2630 $user = api_get_user($a, $i['author-link']);
2631 switch ($i['verb']) {
2633 $activities['like'][] = $user;
2635 case ACTIVITY_DISLIKE:
2636 $activities['dislike'][] = $user;
2638 case ACTIVITY_ATTEND:
2639 $activities['attendyes'][] = $user;
2641 case ACTIVITY_ATTENDNO:
2642 $activities['attendno'][] = $user;
2644 case ACTIVITY_ATTENDMAYBE:
2645 $activities['attendmaybe'][] = $user;
2652 if ($type == "xml") {
2653 $xml_activities = array();
2654 foreach ($activities as $k => $v) {
2655 // change xml element from "like" to "friendica:like"
2656 $xml_activities["friendica:".$k] = $v;
2657 // add user data into xml output
2659 foreach ($v as $user)
2660 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2662 $activities = $xml_activities;
2670 * @brief return data from profiles
2672 * @param array $profile array containing data from db table 'profile'
2673 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2676 function api_format_items_profiles(&$profile = null, $type = "json")
2678 if ($profile != null) {
2679 $profile = array('profile_id' => $profile['id'],
2680 'profile_name' => $profile['profile-name'],
2681 'is_default' => $profile['is-default'] ? true : false,
2682 'hide_friends'=> $profile['hide-friends'] ? true : false,
2683 'profile_photo' => $profile['photo'],
2684 'profile_thumb' => $profile['thumb'],
2685 'publish' => $profile['publish'] ? true : false,
2686 'net_publish' => $profile['net-publish'] ? true : false,
2687 'description' => $profile['pdesc'],
2688 'date_of_birth' => $profile['dob'],
2689 'address' => $profile['address'],
2690 'city' => $profile['locality'],
2691 'region' => $profile['region'],
2692 'postal_code' => $profile['postal-code'],
2693 'country' => $profile['country-name'],
2694 'hometown' => $profile['hometown'],
2695 'gender' => $profile['gender'],
2696 'marital' => $profile['marital'],
2697 'marital_with' => $profile['with'],
2698 'marital_since' => $profile['howlong'],
2699 'sexual' => $profile['sexual'],
2700 'politic' => $profile['politic'],
2701 'religion' => $profile['religion'],
2702 'public_keywords' => $profile['pub_keywords'],
2703 'private_keywords' => $profile['prv_keywords'],
2704 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2705 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2706 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2707 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2708 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2709 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2710 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2711 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2712 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2713 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2714 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2715 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2716 'homepage' => $profile['homepage'],
2723 * @brief format items to be returned by api
2725 * @param array $r array of items
2726 * @param array $user_info
2727 * @param bool $filter_user filter items by $user_info
2729 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2735 foreach ($r as $item) {
2736 localize_item($item);
2737 list($status_user, $owner_user) = api_item_get_user($a, $item);
2739 // Look if the posts are matching if they should be filtered by user id
2740 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2744 $in_reply_to = api_in_reply_to($item);
2746 $converted = api_convert_item($item);
2748 if ($type == "xml") {
2749 $geo = "georss:point";
2755 'text' => $converted["text"],
2756 'truncated' => false,
2757 'created_at'=> api_date($item['created']),
2758 'in_reply_to_status_id' => $in_reply_to['status_id'],
2759 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2760 'source' => (($item['app']) ? $item['app'] : 'web'),
2761 'id' => intval($item['id']),
2762 'id_str' => (string) intval($item['id']),
2763 'in_reply_to_user_id' => $in_reply_to['user_id'],
2764 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2765 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2767 'favorited' => $item['starred'] ? true : false,
2768 'user' => $status_user ,
2769 'friendica_owner' => $owner_user,
2770 //'entities' => NULL,
2771 'statusnet_html' => $converted["html"],
2772 'statusnet_conversation_id' => $item['parent'],
2773 'friendica_activities' => api_format_items_activities($item, $type),
2776 if (count($converted["attachments"]) > 0) {
2777 $status["attachments"] = $converted["attachments"];
2780 if (count($converted["entities"]) > 0) {
2781 $status["entities"] = $converted["entities"];
2784 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
2785 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2786 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2787 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2791 // Retweets are only valid for top postings
2792 // It doesn't work reliable with the link if its a feed
2793 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2795 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
2798 if ($item["id"] == $item["parent"]) {
2799 $retweeted_item = api_share_as_retweet($item);
2800 if ($retweeted_item !== false) {
2801 $retweeted_status = $status;
2803 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
2804 } catch (BadRequestException $e) {
2805 // user not found. should be found?
2806 /// @todo check if the user should be always found
2807 $retweeted_status["user"] = array();
2810 $rt_converted = api_convert_item($retweeted_item);
2812 $retweeted_status['text'] = $rt_converted["text"];
2813 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2814 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2815 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2816 $status['retweeted_status'] = $retweeted_status;
2820 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2821 unset($status["user"]["uid"]);
2822 unset($status["user"]["self"]);
2824 if ($item["coord"] != "") {
2825 $coords = explode(' ', $item["coord"]);
2826 if (count($coords) == 2) {
2827 if ($type == "json")
2828 $status["geo"] = array('type' => 'Point',
2829 'coordinates' => array((float) $coords[0],
2830 (float) $coords[1]));
2831 else // Not sure if this is the official format - if someone founds a documentation we can check
2832 $status["georss:point"] = $item["coord"];
2840 function api_account_rate_limit_status($type)
2842 if ($type == "xml") {
2844 'remaining-hits' => '150',
2845 '@attributes' => array("type" => "integer"),
2846 'hourly-limit' => '150',
2847 '@attributes2' => array("type" => "integer"),
2848 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
2849 '@attributes3' => array("type" => "datetime"),
2850 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2851 '@attributes4' => array("type" => "integer"),
2855 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2856 'remaining_hits' => '150',
2857 'hourly_limit' => '150',
2858 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
2862 return api_format_data('hash', $type, array('hash' => $hash));
2865 /// @TODO move to top of file or somwhere better
2866 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
2868 function api_help_test($type)
2870 if ($type == 'xml') {
2876 return api_format_data('ok', $type, array("ok" => $ok));
2879 /// @TODO move to top of file or somwhere better
2880 api_register_func('api/help/test', 'api_help_test', false);
2882 function api_lists($type)
2885 /// @TODO $ret is not filled here?
2886 return api_format_data('lists', $type, array("lists_list" => $ret));
2889 /// @TODO move to top of file or somwhere better
2890 api_register_func('api/lists', 'api_lists', true);
2892 function api_lists_list($type)
2895 /// @TODO $ret is not filled here?
2896 return api_format_data('lists', $type, array("lists_list" => $ret));
2899 /// @TODO move to top of file or somwhere better
2900 api_register_func('api/lists/list', 'api_lists_list', true);
2903 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2904 * This function is deprecated by Twitter
2905 * returns: json, xml
2907 function api_statuses_f($type, $qtype)
2911 if (api_user() === false) {
2912 throw new ForbiddenException();
2915 $user_info = api_get_user($a);
2917 if (x($_GET, 'cursor') && $_GET['cursor']=='undefined') {
2918 /* this is to stop Hotot to load friends multiple times
2919 * I'm not sure if I'm missing return something or
2920 * is a bug in hotot. Workaround, meantime
2924 return array('$users' => $ret);*/
2928 if ($qtype == 'friends') {
2929 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2931 if ($qtype == 'followers') {
2932 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2935 // friends and followers only for self
2936 if ($user_info['self'] == 0) {
2937 $sql_extra = " AND false ";
2941 "SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra ORDER BY `nick`",
2946 foreach ($r as $cid) {
2947 $user = api_get_user($a, $cid['nurl']);
2948 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2949 unset($user["uid"]);
2950 unset($user["self"]);
2957 return array('user' => $ret);
2961 function api_statuses_friends($type)
2963 $data = api_statuses_f($type, "friends");
2964 if ($data === false) {
2967 return api_format_data("users", $type, $data);
2970 function api_statuses_followers($type)
2972 $data = api_statuses_f($type, "followers");
2973 if ($data === false) {
2976 return api_format_data("users", $type, $data);
2979 /// @TODO move to top of file or somewhere better
2980 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
2981 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
2983 function api_statusnet_config($type)
2987 $name = $a->config['sitename'];
2988 $server = $a->get_hostname();
2989 $logo = System::baseUrl() . '/images/friendica-64.png';
2990 $email = $a->config['admin_email'];
2991 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2992 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
2993 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2994 if ($a->config['api_import_size']) {
2995 $texlimit = string($a->config['api_import_size']);
2997 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
2998 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3001 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3002 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3003 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3004 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3005 'shorturllength' => '30',
3006 'friendica' => array(
3007 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3008 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3009 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3010 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3015 return api_format_data('config', $type, array('config' => $config));
3018 /// @TODO move to top of file or somewhere better
3019 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3020 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3022 function api_statusnet_version($type)
3025 $fake_statusnet_version = "0.9.7";
3027 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
3030 /// @TODO move to top of file or somewhere better
3031 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3032 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3035 * @todo use api_format_data() to return data
3037 function api_ff_ids($type,$qtype)
3042 throw new ForbiddenException();
3045 $user_info = api_get_user($a);
3047 if ($qtype == 'friends') {
3048 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3050 if ($qtype == 'followers') {
3051 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3054 if (!$user_info["self"]) {
3055 $sql_extra = " AND false ";
3058 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3061 "SELECT `pcontact`.`id` FROM `contact`
3062 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3063 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3067 if (!DBM::is_result($r)) {
3072 foreach ($r as $rr) {
3073 if ($stringify_ids) {
3076 $ids[] = intval($rr['id']);
3080 return api_format_data("ids", $type, array('id' => $ids));
3083 function api_friends_ids($type)
3085 return api_ff_ids($type, 'friends');
3088 function api_followers_ids($type)
3090 return api_ff_ids($type, 'followers');
3093 /// @TODO move to top of file or somewhere better
3094 api_register_func('api/friends/ids', 'api_friends_ids', true);
3095 api_register_func('api/followers/ids', 'api_followers_ids', true);
3097 function api_direct_messages_new($type)
3102 if (api_user() === false) throw new ForbiddenException();
3104 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) return;
3106 $sender = api_get_user($a);
3108 if ($_POST['screen_name']) {
3110 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3112 dbesc($_POST['screen_name'])
3115 // Selecting the id by priority, friendica first
3116 api_best_nickname($r);
3118 $recipient = api_get_user($a, $r[0]['nurl']);
3120 $recipient = api_get_user($a, $_POST['user_id']);
3125 if (x($_REQUEST, 'replyto')) {
3127 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3129 intval($_REQUEST['replyto'])
3131 $replyto = $r[0]['parent-uri'];
3132 $sub = $r[0]['title'];
3134 if (x($_REQUEST, 'title')) {
3135 $sub = $_REQUEST['title'];
3137 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3141 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3144 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3145 $ret = api_format_messages($r[0], $recipient, $sender);
3147 $ret = array("error"=>$id);
3150 $data = array('direct_message'=>$ret);
3155 $data = api_rss_extra($a, $data, $user_info);
3158 return api_format_data("direct-messages", $type, $data);
3162 /// @TODO move to top of file or somewhere better
3163 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3166 * @brief delete a direct_message from mail table through api
3168 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3171 function api_direct_messages_destroy($type)
3175 if (api_user() === false) {
3176 throw new ForbiddenException();
3180 $user_info = api_get_user($a);
3182 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3184 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3185 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3186 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3188 $uid = $user_info['uid'];
3189 // error if no id or parenturi specified (for clients posting parent-uri as well)
3190 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3191 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3192 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3195 // BadRequestException if no id specified (for clients using Twitter API)
3197 throw new BadRequestException('Message id not specified');
3200 // add parent-uri to sql command if specified by calling app
3201 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3203 // get data of the specified message id
3205 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3210 // error message if specified id is not in database
3211 if (!DBM::is_result($r)) {
3212 if ($verbose == "true") {
3213 $answer = array('result' => 'error', 'message' => 'message id not in database');
3214 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3216 /// @todo BadRequestException ok for Twitter API clients?
3217 throw new BadRequestException('message id not in database');
3222 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3227 if ($verbose == "true") {
3230 $answer = array('result' => 'ok', 'message' => 'message deleted');
3231 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3233 $answer = array('result' => 'error', 'message' => 'unknown error');
3234 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3237 /// @todo return JSON data like Twitter API not yet implemented
3241 /// @TODO move to top of file or somewhere better
3242 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3244 function api_direct_messages_box($type, $box, $verbose)
3248 if (api_user() === false) {
3249 throw new ForbiddenException();
3253 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3254 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3259 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3260 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3262 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3263 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3266 unset($_REQUEST["user_id"]);
3267 unset($_GET["user_id"]);
3269 unset($_REQUEST["screen_name"]);
3270 unset($_GET["screen_name"]);
3272 $user_info = api_get_user($a);
3273 $profile_url = $user_info["url"];
3276 $start = $page * $count;
3279 if ($box=="sentbox") {
3280 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3281 } elseif ($box == "conversation") {
3282 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3283 } elseif ($box == "all") {
3284 $sql_extra = "true";
3285 } elseif ($box == "inbox") {
3286 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3290 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3293 if ($user_id != "") {
3294 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3295 } elseif ($screen_name !="") {
3296 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3300 "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",
3306 if ($verbose == "true" && !DBM::is_result($r)) {
3307 $answer = array('result' => 'error', 'message' => 'no mails available');
3308 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3312 foreach ($r as $item) {
3313 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3314 $recipient = $user_info;
3315 $sender = api_get_user($a, normalise_link($item['contact-url']));
3316 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3317 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3318 $sender = $user_info;
3321 $ret[] = api_format_messages($item, $recipient, $sender);
3325 $data = array('direct_message' => $ret);
3329 $data = api_rss_extra($a, $data, $user_info);
3332 return api_format_data("direct-messages", $type, $data);
3335 function api_direct_messages_sentbox($type)
3337 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3338 return api_direct_messages_box($type, "sentbox", $verbose);
3341 function api_direct_messages_inbox($type)
3343 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3344 return api_direct_messages_box($type, "inbox", $verbose);
3347 function api_direct_messages_all($type)
3349 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3350 return api_direct_messages_box($type, "all", $verbose);
3353 function api_direct_messages_conversation($type)
3355 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3356 return api_direct_messages_box($type, "conversation", $verbose);
3359 /// @TODO move to top of file or somewhere better
3360 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3361 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3362 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3363 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3365 function api_oauth_request_token($type)
3368 $oauth = new FKOAuth1();
3369 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
3370 } catch (Exception $e) {
3371 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3378 function api_oauth_access_token($type)
3381 $oauth = new FKOAuth1();
3382 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
3383 } catch (Exception $e) {
3384 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3391 /// @TODO move to top of file or somewhere better
3392 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3393 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3397 * @brief delete a complete photoalbum with all containing photos from database through api
3399 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3402 function api_fr_photoalbum_delete($type)
3404 if (api_user() === false) {
3405 throw new ForbiddenException();
3408 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3410 // we do not allow calls without album string
3412 throw new BadRequestException("no albumname specified");
3414 // check if album is existing
3416 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3420 if (!DBM::is_result($r))
3421 throw new BadRequestException("album not available");
3423 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3424 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3425 foreach ($r as $rr) {
3427 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3428 intval(local_user()),
3429 dbesc($rr['resource-id'])
3432 if (!DBM::is_result($photo_item)) {
3433 throw new InternalServerErrorException("problem with deleting items occured");
3435 drop_item($photo_item[0]['id'], false);
3438 // now let's delete all photos from the album
3439 $result = dba::delete('photo', array('uid' => api_user(), 'album' => $album));
3441 // return success of deletion or error message
3443 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3444 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3446 throw new InternalServerErrorException("unknown error - deleting from database failed");
3451 * @brief update the name of the album for all photos of an album
3453 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3456 function api_fr_photoalbum_update($type)
3458 if (api_user() === false) {
3459 throw new ForbiddenException();
3462 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3463 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3465 // we do not allow calls without album string
3467 throw new BadRequestException("no albumname specified");
3469 if ($album_new == "") {
3470 throw new BadRequestException("no new albumname specified");
3472 // check if album is existing
3474 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3478 if (!DBM::is_result($r)) {
3479 throw new BadRequestException("album not available");
3481 // now let's update all photos to the albumname
3483 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3489 // return success of updating or error message
3491 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3492 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3494 throw new InternalServerErrorException("unknown error - updating in database failed");
3500 * @brief list all photos of the authenticated user
3502 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3505 function api_fr_photos_list($type)
3507 if (api_user() === false) {
3508 throw new ForbiddenException();
3511 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3512 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3513 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3514 intval(local_user())
3517 'image/jpeg' => 'jpg',
3518 'image/png' => 'png',
3519 'image/gif' => 'gif'
3521 $data = array('photo'=>array());
3522 if (DBM::is_result($r)) {
3523 foreach ($r as $rr) {
3525 $photo['id'] = $rr['resource-id'];
3526 $photo['album'] = $rr['album'];
3527 $photo['filename'] = $rr['filename'];
3528 $photo['type'] = $rr['type'];
3529 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3530 $photo['created'] = $rr['created'];
3531 $photo['edited'] = $rr['edited'];
3532 $photo['desc'] = $rr['desc'];
3534 if ($type == "xml") {
3535 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3537 $photo['thumb'] = $thumb;
3538 $data['photo'][] = $photo;
3542 return api_format_data("photos", $type, $data);
3546 * @brief upload a new photo or change an existing photo
3548 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3551 function api_fr_photo_create_update($type)
3553 if (api_user() === false) {
3554 throw new ForbiddenException();
3557 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3558 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3559 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3560 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3561 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3562 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3563 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3564 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3565 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3567 // do several checks on input parameters
3568 // we do not allow calls without album string
3569 if ($album == null) {
3570 throw new BadRequestException("no albumname specified");
3572 // if photo_id == null --> we are uploading a new photo
3573 if ($photo_id == null) {
3576 // error if no media posted in create-mode
3577 if (!x($_FILES, 'media')) {
3579 throw new BadRequestException("no media data submitted");
3582 // album_new will be ignored in create-mode
3587 // check if photo is existing in database
3589 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3594 if (!DBM::is_result($r)) {
3595 throw new BadRequestException("photo not available");
3599 // checks on acl strings provided by clients
3600 $acl_input_error = false;
3601 $acl_input_error |= check_acl_input($allow_cid);
3602 $acl_input_error |= check_acl_input($deny_cid);
3603 $acl_input_error |= check_acl_input($allow_gid);
3604 $acl_input_error |= check_acl_input($deny_gid);
3605 if ($acl_input_error) {
3606 throw new BadRequestException("acl data invalid");
3608 // now let's upload the new media in create-mode
3609 if ($mode == "create") {
3610 $media = $_FILES['media'];
3611 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3613 // return success of updating or error message
3614 if (!is_null($data)) {
3615 return api_format_data("photo_create", $type, $data);
3617 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3621 // now let's do the changes in update-mode
3622 if ($mode == "update") {
3625 if (!is_null($desc)) {
3626 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3629 if (!is_null($album_new)) {
3630 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3633 if (!is_null($allow_cid)) {
3634 $allow_cid = trim($allow_cid);
3635 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3638 if (!is_null($deny_cid)) {
3639 $deny_cid = trim($deny_cid);
3640 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3643 if (!is_null($allow_gid)) {
3644 $allow_gid = trim($allow_gid);
3645 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3648 if (!is_null($deny_gid)) {
3649 $deny_gid = trim($deny_gid);
3650 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3654 if ($sql_extra != "") {
3655 $nothingtodo = false;
3657 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3659 datetime_convert(), // update edited timestamp
3665 $nothingtodo = true;
3668 if (x($_FILES, 'media')) {
3669 $nothingtodo = false;
3670 $media = $_FILES['media'];
3671 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3672 if (!is_null($data)) {
3673 return api_format_data("photo_update", $type, $data);
3677 // return success of updating or error message
3679 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
3680 return api_format_data("photo_update", $type, array('$result' => $answer));
3683 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
3684 return api_format_data("photo_update", $type, array('$result' => $answer));
3686 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3689 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3694 * @brief delete a single photo from the database through api
3696 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3699 function api_fr_photo_delete($type)
3701 if (api_user() === false) {
3702 throw new ForbiddenException();
3705 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3707 // do several checks on input parameters
3708 // we do not allow calls without photo id
3709 if ($photo_id == null) {
3710 throw new BadRequestException("no photo_id specified");
3712 // check if photo is existing in database
3714 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3718 if (!DBM::is_result($r)) {
3719 throw new BadRequestException("photo not available");
3721 // now we can perform on the deletion of the photo
3722 $result = dba::delete('photo', array('uid' => api_user(), 'resource-id' => $photo_id));
3724 // return success of deletion or error message
3726 // retrieve the id of the parent element (the photo element)
3728 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3729 intval(local_user()),
3733 if (!DBM::is_result($photo_item)) {
3734 throw new InternalServerErrorException("problem with deleting items occured");
3736 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3737 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
3738 drop_item($photo_item[0]['id'], false);
3740 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
3741 return api_format_data("photo_delete", $type, array('$result' => $answer));
3743 throw new InternalServerErrorException("unknown error on deleting photo from database table");
3749 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3751 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3754 function api_fr_photo_detail($type)
3756 if (api_user() === false) {
3757 throw new ForbiddenException();
3759 if (!x($_REQUEST, 'photo_id')) {
3760 throw new BadRequestException("No photo id.");
3763 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3764 $photo_id = $_REQUEST['photo_id'];
3766 // prepare json/xml output with data from database for the requested photo
3767 $data = prepare_photo_data($type, $scale, $photo_id);
3769 return api_format_data("photo_detail", $type, $data);
3774 * @brief updates the profile image for the user (either a specified profile or the default profile)
3776 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3779 function api_account_update_profile_image($type)
3781 if (api_user() === false) {
3782 throw new ForbiddenException();
3785 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
3787 // error if image data is missing
3788 if (!x($_FILES, 'image')) {
3789 throw new BadRequestException("no media data submitted");
3792 // check if specified profile id is valid
3793 if ($profileid != 0) {
3795 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
3799 // error message if specified profile id is not in database
3800 if (!DBM::is_result($r)) {
3801 throw new BadRequestException("profile_id not available");
3803 $is_default_profile = $r['profile'];
3805 $is_default_profile = 1;
3808 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3810 if (x($_FILES, 'image')) {
3811 $media = $_FILES['image'];
3812 } elseif (x($_FILES, 'media')) {
3813 $media = $_FILES['media'];
3815 // save new profile image
3816 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
3819 if (is_array($media['type'])) {
3820 $filetype = $media['type'][0];
3822 $filetype = $media['type'];
3824 if ($filetype == "image/jpeg") {
3826 } elseif ($filetype == "image/png") {
3829 // change specified profile or all profiles to the new resource-id
3830 if ($is_default_profile) {
3832 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
3833 dbesc($data['photo']['id']),
3834 intval(local_user())
3838 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
3839 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
3840 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
3841 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
3842 intval(local_user())
3846 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
3847 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
3848 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
3849 intval($_REQUEST['profile']),
3850 intval(local_user())
3854 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
3855 // so that browsers will do a cache update unconditionally
3858 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
3859 dbesc(datetime_convert()),
3860 intval(local_user())
3863 // Update global directory in background
3864 //$user = api_get_user(get_app());
3865 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
3866 if ($url && strlen(Config::get('system', 'directory'))) {
3867 Worker::add(PRIORITY_LOW, "Directory", $url);
3870 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
3872 // output for client
3874 return api_account_verify_credentials($type);
3876 // SaveMediaToDatabase failed for some reason
3877 throw new InternalServerErrorException("image upload failed");
3881 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3882 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
3883 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
3884 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3885 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3886 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3887 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
3888 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3889 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3892 function check_acl_input($acl_string)
3894 if ($acl_string == null || $acl_string == " ") {
3897 $contact_not_found = false;
3899 // split <x><y><z> into array of cid's
3900 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3902 // check for each cid if it is available on server
3903 $cid_array = $array[0];
3904 foreach ($cid_array as $cid) {
3905 $cid = str_replace("<", "", $cid);
3906 $cid = str_replace(">", "", $cid);
3908 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3912 $contact_not_found |= !DBM::is_result($contact);
3914 return $contact_not_found;
3917 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)
3925 if (is_array($media)) {
3926 if (is_array($media['tmp_name'])) {
3927 $src = $media['tmp_name'][0];
3929 $src = $media['tmp_name'];
3931 if (is_array($media['name'])) {
3932 $filename = basename($media['name'][0]);
3934 $filename = basename($media['name']);
3936 if (is_array($media['size'])) {
3937 $filesize = intval($media['size'][0]);
3939 $filesize = intval($media['size']);
3941 if (is_array($media['type'])) {
3942 $filetype = $media['type'][0];
3944 $filetype = $media['type'];
3948 if ($filetype == "") {
3949 $filetype=Photo::guessImageType($filename);
3951 $imagedata = getimagesize($src);
3953 $filetype = $imagedata['mime'];
3956 "File upload src: " . $src . " - filename: " . $filename .
3957 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG
3960 // check if there was a php upload error
3961 if ($filesize == 0 && $media['error'] == 1) {
3962 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3964 // check against max upload size within Friendica instance
3965 $maximagesize = Config::get('system', 'maximagesize');
3966 if (($maximagesize) && ($filesize > $maximagesize)) {
3967 $formattedBytes = formatBytes($maximagesize);
3968 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3971 // create Photo instance with the data of the image
3972 $imagedata = @file_get_contents($src);
3973 $ph = new Photo($imagedata, $filetype);
3974 if (! $ph->isValid()) {
3975 throw new InternalServerErrorException("unable to process image data");
3978 // check orientation of image
3982 // check max length of images on server
3983 $max_length = Config::get('system', 'max_image_length');
3984 if (! $max_length) {
3985 $max_length = MAX_IMAGE_LENGTH;
3987 if ($max_length > 0) {
3988 $ph->scaleImage($max_length);
3989 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
3991 $width = $ph->getWidth();
3992 $height = $ph->getHeight();
3994 // create a new resource-id if not already provided
3995 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
3997 if ($mediatype == "photo") {
3998 // upload normal image (scales 0, 1, 2)
3999 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4001 $r =$ph->store(local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4003 logger("photo upload: image upload with scale 0 (original size) failed");
4005 if ($width > 640 || $height > 640) {
4006 $ph->scaleImage(640);
4007 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4009 logger("photo upload: image upload with scale 1 (640x640) failed");
4013 if ($width > 320 || $height > 320) {
4014 $ph->scaleImage(320);
4015 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4017 logger("photo upload: image upload with scale 2 (320x320) failed");
4020 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4021 } elseif ($mediatype == "profileimage") {
4022 // upload profile image (scales 4, 5, 6)
4023 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4025 if ($width > 175 || $height > 175) {
4026 $ph->scaleImage(175);
4027 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4029 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4033 if ($width > 80 || $height > 80) {
4034 $ph->scaleImage(80);
4035 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4037 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4041 if ($width > 48 || $height > 48) {
4042 $ph->scaleImage(48);
4043 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4045 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4049 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4053 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4054 if ($photo_id == null && $mediatype == "photo") {
4055 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4057 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4058 return prepare_photo_data($type, false, $hash);
4060 throw new InternalServerErrorException("image upload failed");
4064 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4066 // get data about the api authenticated user
4067 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4068 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4071 $arr['guid'] = get_guid(32);
4072 $arr['uid'] = intval(api_user());
4074 $arr['parent-uri'] = $uri;
4075 $arr['type'] = 'photo';
4077 $arr['resource-id'] = $hash;
4078 $arr['contact-id'] = $owner_record[0]['id'];
4079 $arr['owner-name'] = $owner_record[0]['name'];
4080 $arr['owner-link'] = $owner_record[0]['url'];
4081 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4082 $arr['author-name'] = $owner_record[0]['name'];
4083 $arr['author-link'] = $owner_record[0]['url'];
4084 $arr['author-avatar'] = $owner_record[0]['thumb'];
4086 $arr['allow_cid'] = $allow_cid;
4087 $arr['allow_gid'] = $allow_gid;
4088 $arr['deny_cid'] = $deny_cid;
4089 $arr['deny_gid'] = $deny_gid;
4090 $arr['last-child'] = 1;
4091 $arr['visible'] = $visibility;
4095 'image/jpeg' => 'jpg',
4096 'image/png' => 'png',
4097 'image/gif' => 'gif'
4100 // adds link to the thumbnail scale photo
4101 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4102 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4105 // do the magic for storing the item in the database and trigger the federation to other contacts
4109 function prepare_photo_data($type, $scale, $photo_id)
4111 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4112 $data_sql = ($scale === false ? "" : "data, ");
4114 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4115 // clients needs to convert this in their way for further processing
4117 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4118 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4119 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4120 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4122 intval(local_user()),
4128 'image/jpeg' => 'jpg',
4129 'image/png' => 'png',
4130 'image/gif' => 'gif'
4133 // prepare output data for photo
4134 if (DBM::is_result($r)) {
4135 $data = array('photo' => $r[0]);
4136 $data['photo']['id'] = $data['photo']['resource-id'];
4137 if ($scale !== false) {
4138 $data['photo']['data'] = base64_encode($data['photo']['data']);
4140 unset($data['photo']['datasize']); //needed only with scale param
4142 if ($type == "xml") {
4143 $data['photo']['links'] = array();
4144 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4145 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4147 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4150 $data['photo']['link'] = array();
4151 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4153 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4154 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4158 unset($data['photo']['resource-id']);
4159 unset($data['photo']['minscale']);
4160 unset($data['photo']['maxscale']);
4162 throw new NotFoundException();
4165 // retrieve item element for getting activities (like, dislike etc.) related to photo
4167 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4168 intval(local_user()),
4171 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4173 // retrieve comments on photo
4175 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4176 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4177 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4178 `contact`.`id` AS `cid`
4180 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4181 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4182 WHERE `item`.`parent` = %d AND `item`.`visible`
4183 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4184 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4185 intval($item[0]['parent']),
4187 dbesc(ACTIVITY_POST)
4190 // prepare output of comments
4191 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4192 $comments = array();
4193 if ($type == "xml") {
4195 foreach ($commentData as $comment) {
4196 $comments[$k++ . ":comment"] = $comment;
4199 foreach ($commentData as $comment) {
4200 $comments[] = $comment;
4203 $data['photo']['friendica_comments'] = $comments;
4205 // include info if rights on photo and rights on item are mismatching
4206 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4207 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4208 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4209 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4210 $data['photo']['rights_mismatch'] = $rights_mismatch;
4217 * Similar as /mod/redir.php
4218 * redirect to 'url' after dfrn auth
4220 * Why this when there is mod/redir.php already?
4221 * This use api_user() and api_login()
4224 * c_url: url of remote contact to auth to
4225 * url: string, url to redirect after auth
4227 function api_friendica_remoteauth()
4229 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4230 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4232 if ($url === '' || $c_url === '') {
4233 throw new BadRequestException("Wrong parameters.");
4236 $c_url = normalise_link($c_url);
4241 "SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4246 if ((! DBM::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4247 throw new BadRequestException("Unknown contact");
4252 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4254 if ($r[0]['duplex'] && $r[0]['issued-id']) {
4255 $orig_id = $r[0]['issued-id'];
4256 $dfrn_id = '1:' . $orig_id;
4258 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4259 $orig_id = $r[0]['dfrn-id'];
4260 $dfrn_id = '0:' . $orig_id;
4263 $sec = random_string();
4266 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4267 VALUES( %d, %s, '%s', '%s', %d )",
4275 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4276 $dest = (($url) ? '&destination_url=' . $url : '');
4278 $r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4279 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4280 . '&type=profile&sec=' . $sec . $dest . $quiet
4283 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4286 * @brief Return the item shared, if the item contains only the [share] tag
4288 * @param array $item Sharer item
4289 * @return array Shared item or false if not a reshare
4291 function api_share_as_retweet(&$item)
4293 $body = trim($item["body"]);
4295 if (Diaspora::isReshare($body, false)===false) {
4299 /// @TODO "$1" should maybe mean '$1' ?
4300 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4302 * Skip if there is no shared message in there
4303 * we already checked this in diaspora::isReshare()
4304 * but better one more than one less...
4306 if ($body == $attributes) {
4311 // build the fake reshared item
4312 $reshared_item = $item;
4315 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4316 if ($matches[1] != "") {
4317 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4320 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4321 if ($matches[1] != "") {
4322 $author = $matches[1];
4326 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4327 if ($matches[1] != "") {
4328 $profile = $matches[1];
4331 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4332 if ($matches[1] != "") {
4333 $profile = $matches[1];
4337 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4338 if ($matches[1] != "") {
4339 $avatar = $matches[1];
4342 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4343 if ($matches[1] != "") {
4344 $avatar = $matches[1];
4348 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4349 if ($matches[1] != "") {
4350 $link = $matches[1];
4353 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4354 if ($matches[1] != "") {
4355 $link = $matches[1];
4359 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4360 if ($matches[1] != "")
4361 $posted = $matches[1];
4363 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4364 if ($matches[1] != "") {
4365 $posted = $matches[1];
4368 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4370 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4374 $reshared_item["body"] = $shared_body;
4375 $reshared_item["author-name"] = $author;
4376 $reshared_item["author-link"] = $profile;
4377 $reshared_item["author-avatar"] = $avatar;
4378 $reshared_item["plink"] = $link;
4379 $reshared_item["created"] = $posted;
4380 $reshared_item["edited"] = $posted;
4382 return $reshared_item;
4386 function api_get_nick($profile)
4389 - remove trailing junk from profile url
4390 - pump.io check has to check the website
4396 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4397 dbesc(normalise_link($profile))
4400 if (DBM::is_result($r)) {
4401 $nick = $r[0]["nick"];
4406 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4407 dbesc(normalise_link($profile))
4410 if (DBM::is_result($r)) {
4411 $nick = $r[0]["nick"];
4416 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4417 if ($friendica != $profile) {
4423 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4424 if ($diaspora != $profile) {
4430 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4431 if ($twitter != $profile) {
4438 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4439 if ($StatusnetHost != $profile) {
4440 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4441 if ($StatusnetUser != $profile) {
4442 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4443 $user = json_decode($UserData);
4445 $nick = $user->screen_name;
4451 // To-Do: look at the page if its really a pumpio site
4452 //if (!$nick == "") {
4453 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4454 // if ($pumpio != $profile)
4456 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4467 function api_in_reply_to($item)
4469 $in_reply_to = array();
4471 $in_reply_to['status_id'] = null;
4472 $in_reply_to['user_id'] = null;
4473 $in_reply_to['status_id_str'] = null;
4474 $in_reply_to['user_id_str'] = null;
4475 $in_reply_to['screen_name'] = null;
4477 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4478 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4479 intval($item['uid']),
4480 dbesc($item['thr-parent']));
4482 if (DBM::is_result($r)) {
4483 $in_reply_to['status_id'] = intval($r[0]['id']);
4485 $in_reply_to['status_id'] = intval($item['parent']);
4488 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4490 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4491 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4492 WHERE `item`.`id` = %d LIMIT 1",
4493 intval($in_reply_to['status_id'])
4496 if (DBM::is_result($r)) {
4497 if ($r[0]['nick'] == "") {
4498 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4501 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4502 $in_reply_to['user_id'] = intval($r[0]['id']);
4503 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4506 // There seems to be situation, where both fields are identical:
4507 // https://github.com/friendica/friendica/issues/1010
4508 // This is a bugfix for that.
4509 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4510 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4511 $in_reply_to['status_id'] = null;
4512 $in_reply_to['user_id'] = null;
4513 $in_reply_to['status_id_str'] = null;
4514 $in_reply_to['user_id_str'] = null;
4515 $in_reply_to['screen_name'] = null;
4519 return $in_reply_to;
4522 function api_clean_plain_items($Text)
4524 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4526 $Text = bb_CleanPictureLinks($Text);
4527 $URLSearchString = "^\[\]";
4529 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
4531 if ($include_entities == "true") {
4532 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
4535 // Simplify "attachment" element
4536 $Text = api_clean_attachments($Text);
4542 * @brief Removes most sharing information for API text export
4544 * @param string $body The original body
4546 * @return string Cleaned body
4548 function api_clean_attachments($body)
4550 $data = get_attachment_data($body);
4557 if (isset($data["text"]))
4558 $body = $data["text"];
4560 if (($body == "") && (isset($data["title"])))
4561 $body = $data["title"];
4563 if (isset($data["url"]))
4564 $body .= "\n".$data["url"];
4566 $body .= $data["after"];
4571 function api_best_nickname(&$contacts)
4573 $best_contact = array();
4575 if (count($contact) == 0)
4578 foreach ($contacts as $contact)
4579 if ($contact["network"] == "") {
4580 $contact["network"] = "dfrn";
4581 $best_contact = array($contact);
4584 if (sizeof($best_contact) == 0)
4585 foreach ($contacts as $contact)
4586 if ($contact["network"] == "dfrn")
4587 $best_contact = array($contact);
4589 if (sizeof($best_contact) == 0)
4590 foreach ($contacts as $contact)
4591 if ($contact["network"] == "dspr")
4592 $best_contact = array($contact);
4594 if (sizeof($best_contact) == 0)
4595 foreach ($contacts as $contact)
4596 if ($contact["network"] == "stat")
4597 $best_contact = array($contact);
4599 if (sizeof($best_contact) == 0)
4600 foreach ($contacts as $contact)
4601 if ($contact["network"] == "pump")
4602 $best_contact = array($contact);
4604 if (sizeof($best_contact) == 0)
4605 foreach ($contacts as $contact)
4606 if ($contact["network"] == "twit")
4607 $best_contact = array($contact);
4609 if (sizeof($best_contact) == 1) {
4610 $contacts = $best_contact;
4612 $contacts = array($contacts[0]);
4616 // return all or a specified group of the user with the containing contacts
4617 function api_friendica_group_show($type)
4621 if (api_user() === false) throw new ForbiddenException();
4624 $user_info = api_get_user($a);
4625 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4626 $uid = $user_info['uid'];
4628 // get data of the specified group id or all groups if not specified
4631 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4635 // error message if specified gid is not in database
4636 if (!DBM::is_result($r))
4637 throw new BadRequestException("gid not available");
4640 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4645 // loop through all groups and retrieve all members for adding data in the user array
4646 foreach ($r as $rr) {
4647 $members = group_get_members($rr['id']);
4650 if ($type == "xml") {
4651 $user_element = "users";
4653 foreach ($members as $member) {
4654 $user = api_get_user($a, $member['nurl']);
4655 $users[$k++.":user"] = $user;
4658 $user_element = "user";
4659 foreach ($members as $member) {
4660 $user = api_get_user($a, $member['nurl']);
4664 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4666 return api_format_data("groups", $type, array('group' => $grps));
4668 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4671 // delete the specified group of the user
4672 function api_friendica_group_delete($type)
4676 if (api_user() === false) throw new ForbiddenException();
4679 $user_info = api_get_user($a);
4680 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4681 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4682 $uid = $user_info['uid'];
4684 // error if no gid specified
4685 if ($gid == 0 || $name == "")
4686 throw new BadRequestException('gid or name not specified');
4688 // get data of the specified group id
4690 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
4694 // error message if specified gid is not in database
4695 if (!DBM::is_result($r))
4696 throw new BadRequestException('gid not available');
4698 // get data of the specified group id and group name
4700 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
4705 // error message if specified gid is not in database
4706 if (!DBM::is_result($rname))
4707 throw new BadRequestException('wrong group name');
4710 $ret = group_rmv($uid, $name);
4713 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
4714 return api_format_data("group_delete", $type, array('result' => $success));
4716 throw new BadRequestException('other API error');
4719 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4722 // create the specified group with the posted array of contacts
4723 function api_friendica_group_create($type)
4727 if (api_user() === false) throw new ForbiddenException();
4730 $user_info = api_get_user($a);
4731 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4732 $uid = $user_info['uid'];
4733 $json = json_decode($_POST['json'], true);
4734 $users = $json['user'];
4736 // error if no name specified
4738 throw new BadRequestException('group name not specified');
4740 // get data of the specified group name
4742 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
4746 // error message if specified group name already exists
4747 if (DBM::is_result($rname))
4748 throw new BadRequestException('group name already exists');
4750 // check if specified group name is a deleted group
4752 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
4756 // error message if specified group name already exists
4757 if (DBM::is_result($rname))
4758 $reactivate_group = true;
4761 $ret = group_add($uid, $name);
4763 $gid = group_byname($uid, $name);
4765 throw new BadRequestException('other API error');
4769 $erroraddinguser = false;
4770 $errorusers = array();
4771 foreach ($users as $user) {
4772 $cid = $user['cid'];
4773 // check if user really exists as contact
4775 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4779 if (count($contact))
4780 $result = group_add_member($uid, $name, $cid, $gid);
4782 $erroraddinguser = true;
4783 $errorusers[] = $cid;
4787 // return success message incl. missing users in array
4788 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
4789 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4790 return api_format_data("group_create", $type, array('result' => $success));
4792 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4795 // update the specified group with the posted array of contacts
4796 function api_friendica_group_update($type)
4800 if (api_user() === false) throw new ForbiddenException();
4803 $user_info = api_get_user($a);
4804 $uid = $user_info['uid'];
4805 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4806 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4807 $json = json_decode($_POST['json'], true);
4808 $users = $json['user'];
4810 // error if no name specified
4812 throw new BadRequestException('group name not specified');
4814 // error if no gid specified
4816 throw new BadRequestException('gid not specified');
4819 $members = group_get_members($gid);
4820 foreach ($members as $member) {
4821 $cid = $member['id'];
4822 foreach ($users as $user) {
4823 $found = ($user['cid'] == $cid ? true : false);
4826 $ret = group_rmv_member($uid, $name, $cid);
4831 $erroraddinguser = false;
4832 $errorusers = array();
4833 foreach ($users as $user) {
4834 $cid = $user['cid'];
4835 // check if user really exists as contact
4837 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4842 if (count($contact)) {
4843 $result = group_add_member($uid, $name, $cid, $gid);
4845 $erroraddinguser = true;
4846 $errorusers[] = $cid;
4850 // return success message incl. missing users in array
4851 $status = ($erroraddinguser ? "missing user" : "ok");
4852 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4853 return api_format_data("group_update", $type, array('result' => $success));
4856 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4858 function api_friendica_activity($type)
4862 if (api_user() === false) throw new ForbiddenException();
4863 $verb = strtolower($a->argv[3]);
4864 $verb = preg_replace("|\..*$|", "", $verb);
4866 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4868 $res = do_like($id, $verb);
4871 if ($type == "xml") {
4876 return api_format_data('ok', $type, array('ok' => $ok));
4878 throw new BadRequestException('Error adding activity');
4882 /// @TODO move to top of file or somwhere better
4883 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
4884 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
4885 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
4886 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
4887 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4888 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
4889 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
4890 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
4891 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
4892 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4895 * @brief Returns notifications
4897 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4900 function api_friendica_notification($type)
4904 if (api_user() === false) throw new ForbiddenException();
4905 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
4906 $nm = new NotificationsManager();
4908 $notes = $nm->getAll(array(), "+seen -date", 50);
4910 if ($type == "xml") {
4911 $xmlnotes = array();
4912 foreach ($notes as $note)
4913 $xmlnotes[] = array("@attributes" => $note);
4918 return api_format_data("notes", $type, array('note' => $notes));
4922 * @brief Set notification as seen and returns associated item (if possible)
4924 * POST request with 'id' param as notification id
4926 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4929 function api_friendica_notification_seen($type)
4933 if (api_user() === false) throw new ForbiddenException();
4934 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
4936 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
4938 $nm = new NotificationsManager();
4939 $note = $nm->getByID($id);
4940 if (is_null($note)) throw new BadRequestException("Invalid argument");
4942 $nm->setSeen($note);
4943 if ($note['otype']=='item') {
4944 // would be really better with an ItemsManager and $im->getByID() :-P
4946 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
4947 intval($note['iid']),
4948 intval(local_user())
4951 // we found the item, return it to the user
4952 $user_info = api_get_user($a);
4953 $ret = api_format_items($r, $user_info, false, $type);
4954 $data = array('status' => $ret);
4955 return api_format_data("status", $type, $data);
4957 // the item can't be found, but we set the note as seen, so we count this as a success
4959 return api_format_data('result', $type, array('result' => "success"));
4962 /// @TODO move to top of file or somwhere better
4963 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4964 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
4967 * @brief update a direct_message to seen state
4969 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4970 * @return string (success result=ok, error result=error with error message)
4972 function api_friendica_direct_messages_setseen($type)
4975 if (api_user() === false) {
4976 throw new ForbiddenException();
4980 $user_info = api_get_user($a);
4981 $uid = $user_info['uid'];
4982 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4984 // return error if id is zero
4986 $answer = array('result' => 'error', 'message' => 'message id not specified');
4987 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4990 // get data of the specified message id
4992 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
4997 // error message if specified id is not in database
4998 if (!DBM::is_result($r)) {
4999 $answer = array('result' => 'error', 'message' => 'message id not in database');
5000 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5003 // update seen indicator
5005 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5012 $answer = array('result' => 'ok', 'message' => 'message set to seen');
5013 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
5015 $answer = array('result' => 'error', 'message' => 'unknown error');
5016 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5020 /// @TODO move to top of file or somwhere better
5021 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5024 * @brief search for direct_messages containing a searchstring through api
5026 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5027 * @return string (success: success=true if found and search_result contains found messages
5028 * success=false if nothing was found, search_result='nothing found',
5029 * error: result=error with error message)
5031 function api_friendica_direct_messages_search($type)
5035 if (api_user() === false) {
5036 throw new ForbiddenException();
5040 $user_info = api_get_user($a);
5041 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5042 $uid = $user_info['uid'];
5044 // error if no searchstring specified
5045 if ($searchstring == "") {
5046 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
5047 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
5050 // get data for the specified searchstring
5052 "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",
5054 dbesc('%'.$searchstring.'%')
5057 $profile_url = $user_info["url"];
5059 // message if nothing was found
5060 if (!DBM::is_result($r)) {
5061 $success = array('success' => false, 'search_results' => 'problem with query');
5062 } elseif (count($r) == 0) {
5063 $success = array('success' => false, 'search_results' => 'nothing found');
5066 foreach ($r as $item) {
5067 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5068 $recipient = $user_info;
5069 $sender = api_get_user($a, normalise_link($item['contact-url']));
5070 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5071 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5072 $sender = $user_info;
5075 $ret[] = api_format_messages($item, $recipient, $sender);
5077 $success = array('success' => true, 'search_results' => $ret);
5080 return api_format_data("direct_message_search", $type, array('$result' => $success));
5083 /// @TODO move to top of file or somwhere better
5084 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5087 * @brief return data of all the profiles a user has to the client
5089 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5092 function api_friendica_profile_show($type)
5096 if (api_user() === false) {
5097 throw new ForbiddenException();
5101 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5103 // retrieve general information about profiles for user
5104 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5105 $directory = Config::get('system', 'directory');
5107 // get data of the specified profile id or all profiles of the user if not specified
5108 if ($profileid != 0) {
5110 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5115 // error message if specified gid is not in database
5116 if (!DBM::is_result($r)) {
5117 throw new BadRequestException("profile_id not available");
5121 "SELECT * FROM `profile` WHERE `uid` = %d",
5125 // loop through all returned profiles and retrieve data and users
5127 foreach ($r as $rr) {
5128 $profile = api_format_items_profiles($rr, $type);
5130 // select all users from contact table, loop and prepare standard return for user data
5133 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5135 intval($rr['profile_id'])
5138 foreach ($r as $rr) {
5139 $user = api_get_user($a, $rr['nurl']);
5140 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5142 $profile['users'] = $users;
5144 // add prepared profile data to array for final return
5145 if ($type == "xml") {
5146 $profiles[$k++ . ":profile"] = $profile;
5148 $profiles[] = $profile;
5152 // return settings, authenticated user and profiles data
5153 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5155 $result = array('multi_profiles' => $multi_profiles ? true : false,
5156 'global_dir' => $directory,
5157 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5158 'profiles' => $profiles);
5159 return api_format_data("friendica_profiles", $type, array('$result' => $result));
5161 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5164 @TODO Maybe open to implement?
5166 [pagename] => api/1.1/statuses/lookup.json
5167 [id] => 605138389168451584
5168 [include_cards] => true
5169 [cards_platform] => Android-12
5170 [include_entities] => true
5171 [include_my_retweet] => 1
5173 [include_reply_count] => true
5174 [include_descendent_reply_count] => true
5178 Not implemented by now:
5179 statuses/retweets_of_me
5184 account/update_location
5185 account/update_profile_background_image
5188 friendica/profile/update
5189 friendica/profile/create
5190 friendica/profile/delete
5192 Not implemented in status.net:
5193 statuses/retweeted_to_me
5194 statuses/retweeted_by_me
5195 direct_messages/destroy
5197 account/update_delivery_device
5198 notifications/follow