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\Core\System;
10 use Friendica\Core\Config;
11 use Friendica\Core\NotificationsManager;
12 use Friendica\Core\Worker;
13 use Friendica\Database\DBM;
14 use Friendica\Model\User;
15 use Friendica\Network\HTTPException;
16 use Friendica\Network\HTTPException\BadRequestException;
17 use Friendica\Network\HTTPException\ForbiddenException;
18 use Friendica\Network\HTTPException\InternalServerErrorException;
19 use Friendica\Network\HTTPException\MethodNotAllowedException;
20 use Friendica\Network\HTTPException\NotFoundException;
21 use Friendica\Network\HTTPException\NotImplementedException;
22 use Friendica\Network\HTTPException\UnauthorizedException;
23 use Friendica\Network\HTTPException\TooManyRequestsException;
24 use Friendica\Object\Contact;
25 use Friendica\Object\Photo;
26 use Friendica\Protocol\Diaspora;
27 use Friendica\Util\XML;
29 require_once 'include/bbcode.php';
30 require_once 'include/datetime.php';
31 require_once 'include/conversation.php';
32 require_once 'include/oauth.php';
33 require_once 'include/html2plain.php';
34 require_once 'mod/share.php';
35 require_once 'mod/item.php';
36 require_once 'include/security.php';
37 require_once 'include/contact_selectors.php';
38 require_once 'include/html2bbcode.php';
39 require_once 'mod/wall_upload.php';
40 require_once 'mod/proxy.php';
41 require_once 'include/message.php';
42 require_once 'include/group.php';
43 require_once 'include/like.php';
44 require_once 'include/plaintext.php';
46 define('API_METHOD_ANY', '*');
47 define('API_METHOD_GET', 'GET');
48 define('API_METHOD_POST', 'POST,PUT');
49 define('API_METHOD_DELETE', 'POST,DELETE');
55 * @brief Auth API user
57 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
58 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
59 * into a page, and visitors will post something without noticing it).
63 if (x($_SESSION, 'allow_api')) {
71 * @brief Get source name from API client
73 * Clients can send 'source' parameter to be show in post metadata
74 * as "sent via <source>".
75 * Some clients doesn't send a source param, we support ones we know
79 * Client source name, default to "api" if unset/unknown
83 if (requestdata('source')) {
84 return requestdata('source');
87 // Support for known clients that doesn't send a source name
88 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
92 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
98 * @brief Format date for API
100 * @param string $str Source date, as UTC
101 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
103 function api_date($str)
105 // Wed May 23 06:01:13 +0000 2007
106 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y");
110 * @brief Register API endpoint
112 * Register a function to be the endpont for defined API path.
114 * @param string $path API URL path, relative to System::baseUrl()
115 * @param string $func Function name to call on path request
116 * @param bool $auth API need logged user
117 * @param string $method HTTP method reqiured to call this endpoint.
118 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
119 * Default to API_METHOD_ANY
121 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
131 // Workaround for hotot
132 $path = str_replace("api/", "api/1.1/", $path);
142 * @brief Login API user
144 * Log in user via OAuth1 or Simple HTTP Auth.
145 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
147 * @param object $a App
148 * @hook 'authenticate'
150 * 'username' => username from login form
151 * 'password' => password from login form
152 * 'authenticated' => return status,
153 * 'user_record' => return authenticated user record
155 * array $user logged user record
157 function api_login(App $a)
161 $oauth = new FKOAuth1();
162 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
163 if (!is_null($token)) {
164 $oauth->loginUser($token->uid);
165 call_hooks('logged_in', $a->user);
168 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
169 var_dump($consumer, $token);
171 } catch (Exception $e) {
175 // workaround for HTTP-auth in CGI mode
176 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
177 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
178 if (strlen($userpass)) {
179 list($name, $password) = explode(':', $userpass);
180 $_SERVER['PHP_AUTH_USER'] = $name;
181 $_SERVER['PHP_AUTH_PW'] = $password;
185 if (!x($_SERVER, 'PHP_AUTH_USER')) {
186 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
187 header('WWW-Authenticate: Basic realm="Friendica"');
188 throw new UnauthorizedException("This API requires login");
191 $user = $_SERVER['PHP_AUTH_USER'];
192 $password = $_SERVER['PHP_AUTH_PW'];
194 // allow "user@server" login (but ignore 'server' part)
195 $at = strstr($user, "@", true);
200 // next code from mod/auth.php. needs better solution
204 'username' => trim($user),
205 'password' => trim($password),
206 'authenticated' => 0,
207 'user_record' => null,
211 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
212 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
213 * and later plugins should not interfere with an earlier one that succeeded.
215 call_hooks('authenticate', $addon_auth);
217 if (($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
218 $record = $addon_auth['user_record'];
220 $user_id = User::authenticate(trim($user), trim($password));
222 $record = dba::select('user', [], ['uid' => $user_id], ['limit' => 1]);
226 if ((! $record) || (! count($record))) {
227 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
228 header('WWW-Authenticate: Basic realm="Friendica"');
229 //header('HTTP/1.0 401 Unauthorized');
230 //die('This api requires login');
231 throw new UnauthorizedException("This API requires login");
234 authenticate_success($record);
236 $_SESSION["allow_api"] = true;
238 call_hooks('logged_in', $a->user);
242 * @brief Check HTTP method of called API
244 * API endpoints can define which HTTP method to accept when called.
245 * This function check the current HTTP method agains endpoint
248 * @param string $method Required methods, uppercase, separated by comma
251 function api_check_method($method)
253 if ($method == "*") {
256 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
260 * @brief Main API entry point
262 * Authenticate user, call registered API function, set HTTP headers
264 * @param object $a App
265 * @return string API call result
267 function api_call(App $a)
269 global $API, $called_api;
272 if (strpos($a->query_string, ".xml") > 0) {
275 if (strpos($a->query_string, ".json") > 0) {
278 if (strpos($a->query_string, ".rss") > 0) {
281 if (strpos($a->query_string, ".atom") > 0) {
286 foreach ($API as $p => $info) {
287 if (strpos($a->query_string, $p) === 0) {
288 if (!api_check_method($info['method'])) {
289 throw new MethodNotAllowedException();
292 $called_api = explode("/", $p);
293 //unset($_SERVER['PHP_AUTH_USER']);
295 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
296 if ($info['auth'] === true && api_user() === false) {
300 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
301 logger('API parameters: ' . print_r($_REQUEST, true));
303 $stamp = microtime(true);
304 $r = call_user_func($info['func'], $type);
305 $duration = (float) (microtime(true) - $stamp);
306 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
308 if (Config::get("system", "profiler")) {
309 $duration = microtime(true)-$a->performance["start"];
311 /// @TODO round() really everywhere?
313 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
314 "Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
315 round($a->performance["database"] - $a->performance["database_write"], 3),
316 round($a->performance["database_write"], 3),
317 round($a->performance["network"], 2),
318 round($a->performance["file"], 2),
319 round($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
325 if (Config::get("rendertime", "callstack")) {
326 $o = "Database Read:\n";
327 foreach ($a->callstack["database"] as $func => $time) {
328 $time = round($time, 3);
330 $o .= $func . ": " . $time . "\n";
333 $o .= "\nDatabase Write:\n";
334 foreach ($a->callstack["database_write"] as $func => $time) {
335 $time = round($time, 3);
337 $o .= $func . ": " . $time . "\n";
341 $o .= "\nNetwork:\n";
342 foreach ($a->callstack["network"] as $func => $time) {
343 $time = round($time, 3);
345 $o .= $func . ": " . $time . "\n";
348 logger($o, LOGGER_DEBUG);
354 * api function returned false withour throw an
355 * exception. This should not happend, throw a 500
357 throw new InternalServerErrorException();
362 header("Content-Type: text/xml");
366 header("Content-Type: application/json");
368 $json = json_encode($rr);
369 if (x($_GET, 'callback')) {
370 $json = $_GET['callback'] . "(" . $json . ")";
375 header("Content-Type: application/rss+xml");
376 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
379 header("Content-Type: application/atom+xml");
380 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
386 logger('API call not implemented: ' . $a->query_string);
387 throw new NotImplementedException();
388 } catch (HTTPException $e) {
389 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
390 return api_error($type, $e);
395 * @brief Format API error string
397 * @param string $type Return type (xml, json, rss, as)
398 * @param object $e HTTPException Error object
399 * @return strin error message formatted as $type
401 function api_error($type, $e)
405 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
406 /// @TODO: https://dev.twitter.com/overview/api/response-codes
408 $error = array("error" => $error,
409 "code" => $e->httpcode . " " . $e->httpdesc,
410 "request" => $a->query_string);
412 $ret = api_format_data('status', $type, array('status' => $error));
416 header("Content-Type: text/xml");
420 header("Content-Type: application/json");
421 return json_encode($ret);
424 header("Content-Type: application/rss+xml");
428 header("Content-Type: application/atom+xml");
435 * @brief Set values for RSS template
438 * @param array $arr Array to be passed to template
439 * @param array $user_info User info
441 * @todo find proper type-hints
443 function api_rss_extra(App $a, $arr, $user_info)
445 if (is_null($user_info)) {
446 $user_info = api_get_user($a);
449 $arr['$user'] = $user_info;
450 $arr['$rss'] = array(
451 'alternate' => $user_info['url'],
452 'self' => System::baseUrl() . "/" . $a->query_string,
453 'base' => System::baseUrl(),
454 'updated' => api_date(null),
455 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
456 'language' => $user_info['language'],
457 'logo' => System::baseUrl() . "/images/friendica-32.png",
465 * @brief Unique contact to contact url.
467 * @param int $id Contact id
468 * @return bool|string
469 * Contact url or False if contact id is unknown
471 function api_unique_id_to_url($id)
473 $r = dba::select('contact', array('url'), array('uid' => 0, 'id' => $id), array('limit' => 1));
475 if (DBM::is_result($r)) {
483 * @brief Get user info array.
485 * @param object $a App
486 * @param int|string $contact_id Contact ID or URL
487 * @param string $type Return type (for errors)
489 function api_get_user(App $a, $contact_id = null, $type = "json")
498 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
500 // Searching for contact URL
501 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
502 $user = dbesc(normalise_link($contact_id));
504 $extra_query = "AND `contact`.`nurl` = '%s' ";
505 if (api_user() !== false) {
506 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
510 // Searching for contact id with uid = 0
511 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
512 $user = dbesc(api_unique_id_to_url($contact_id));
515 throw new BadRequestException("User not found.");
519 $extra_query = "AND `contact`.`nurl` = '%s' ";
520 if (api_user() !== false) {
521 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
525 if (is_null($user) && x($_GET, 'user_id')) {
526 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
529 throw new BadRequestException("User not found.");
533 $extra_query = "AND `contact`.`nurl` = '%s' ";
534 if (api_user() !== false) {
535 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
538 if (is_null($user) && x($_GET, 'screen_name')) {
539 $user = dbesc($_GET['screen_name']);
541 $extra_query = "AND `contact`.`nick` = '%s' ";
542 if (api_user() !== false) {
543 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
547 if (is_null($user) && x($_GET, 'profileurl')) {
548 $user = dbesc(normalise_link($_GET['profileurl']));
550 $extra_query = "AND `contact`.`nurl` = '%s' ";
551 if (api_user() !== false) {
552 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
556 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
557 $argid = count($called_api);
558 list($user, $null) = explode(".", $a->argv[$argid]);
559 if (is_numeric($user)) {
560 $user = dbesc(api_unique_id_to_url($user));
567 $extra_query = "AND `contact`.`nurl` = '%s' ";
568 if (api_user() !== false) {
569 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
572 $user = dbesc($user);
574 $extra_query = "AND `contact`.`nick` = '%s' ";
575 if (api_user() !== false) {
576 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
581 logger("api_get_user: user ".$user, LOGGER_DEBUG);
584 if (api_user() === false) {
588 $user = $_SESSION['uid'];
589 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
593 logger('api_user: ' . $extra_query . ', user: ' . $user);
597 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
603 // Selecting the id by priority, friendica first
604 api_best_nickname($uinfo);
606 // if the contact wasn't found, fetch it from the contacts with uid = 0
607 if (!DBM::is_result($uinfo)) {
611 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
614 if (DBM::is_result($r)) {
615 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
617 // If no nick where given, extract it from the address
618 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
619 $r[0]['nick'] = api_get_nick($r[0]["url"]);
624 'id_str' => (string) $r[0]["id"],
625 'name' => $r[0]["name"],
626 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
627 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
628 'description' => $r[0]["about"],
629 'profile_image_url' => $r[0]["micro"],
630 'profile_image_url_https' => $r[0]["micro"],
631 'url' => $r[0]["url"],
632 'protected' => false,
633 'followers_count' => 0,
634 'friends_count' => 0,
636 'created_at' => api_date($r[0]["created"]),
637 'favourites_count' => 0,
639 'time_zone' => 'UTC',
640 'geo_enabled' => false,
642 'statuses_count' => 0,
644 'contributors_enabled' => false,
645 'is_translator' => false,
646 'is_translation_enabled' => false,
647 'following' => false,
648 'follow_request_sent' => false,
649 'statusnet_blocking' => false,
650 'notifications' => false,
651 'statusnet_profile_url' => $r[0]["url"],
653 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
655 'network' => $r[0]["network"],
660 throw new BadRequestException("User not found.");
664 if ($uinfo[0]['self']) {
665 if ($uinfo[0]['network'] == "") {
666 $uinfo[0]['network'] = NETWORK_DFRN;
670 "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
674 "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
678 /// @TODO old-lost code? (twice)
679 // Counting is deactivated by now, due to performance issues
680 // count public wall messages
681 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
682 // intval($uinfo[0]['uid'])
684 //$countitms = $r[0]['count'];
687 // Counting is deactivated by now, due to performance issues
688 //$r = q("SELECT count(*) as `count` FROM `item`
689 // WHERE `contact-id` = %d",
690 // intval($uinfo[0]['id'])
692 //$countitms = $r[0]['count'];
696 /// @TODO old-lost code? (twice)
698 // Counting is deactivated by now, due to performance issues
700 $r = q("SELECT count(*) as `count` FROM `contact`
701 WHERE `uid` = %d AND `rel` IN ( %d, %d )
702 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
703 intval($uinfo[0]['uid']),
704 intval(CONTACT_IS_SHARING),
705 intval(CONTACT_IS_FRIEND)
707 $countfriends = $r[0]['count'];
709 $r = q("SELECT count(*) as `count` FROM `contact`
710 WHERE `uid` = %d AND `rel` IN ( %d, %d )
711 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
712 intval($uinfo[0]['uid']),
713 intval(CONTACT_IS_FOLLOWER),
714 intval(CONTACT_IS_FRIEND)
716 $countfollowers = $r[0]['count'];
718 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
719 intval($uinfo[0]['uid'])
721 $starred = $r[0]['count'];
724 if (! $uinfo[0]['self']) {
734 // Add a nick if it isn't present there
735 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
736 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
739 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
741 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
744 'id' => intval($pcontact_id),
745 'id_str' => (string) intval($pcontact_id),
746 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
747 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
748 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
749 'description' => (($profile) ? $profile[0]['pdesc'] : null),
750 'profile_image_url' => $uinfo[0]['micro'],
751 'profile_image_url_https' => $uinfo[0]['micro'],
752 'url' => $uinfo[0]['url'],
753 'protected' => false,
754 'followers_count' => intval($countfollowers),
755 'friends_count' => intval($countfriends),
757 'created_at' => api_date($uinfo[0]['created']),
758 'favourites_count' => intval($starred),
760 'time_zone' => 'UTC',
761 'geo_enabled' => false,
763 'statuses_count' => intval($countitms),
765 'contributors_enabled' => false,
766 'is_translator' => false,
767 'is_translation_enabled' => false,
768 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
769 'follow_request_sent' => false,
770 'statusnet_blocking' => false,
771 'notifications' => false,
773 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
774 'statusnet_profile_url' => $uinfo[0]['url'],
775 'uid' => intval($uinfo[0]['uid']),
776 'cid' => intval($uinfo[0]['cid']),
777 'self' => $uinfo[0]['self'],
778 'network' => $uinfo[0]['network'],
785 * @brief return api-formatted array for item's author and owner
787 * @param object $a App
788 * @param array $item item from db
789 * @return array(array:author, array:owner)
791 function api_item_get_user(App $a, $item)
793 $status_user = api_get_user($a, $item["author-link"]);
795 $status_user["protected"] = (($item["allow_cid"] != "") ||
796 ($item["allow_gid"] != "") ||
797 ($item["deny_cid"] != "") ||
798 ($item["deny_gid"] != "") ||
801 if ($item['thr-parent'] == $item['uri']) {
802 $owner_user = api_get_user($a, $item["owner-link"]);
804 $owner_user = $status_user;
807 return (array($status_user, $owner_user));
811 * @brief walks recursively through an array with the possibility to change value and key
813 * @param array $array The array to walk through
814 * @param string $callback The callback function
816 * @return array the transformed array
818 function api_walk_recursive(array &$array, callable $callback)
820 $new_array = array();
822 foreach ($array as $k => $v) {
824 if ($callback($v, $k)) {
825 $new_array[$k] = api_walk_recursive($v, $callback);
828 if ($callback($v, $k)) {
839 * @brief Callback function to transform the array in an array that can be transformed in a XML file
841 * @param mixed $item Array item value
842 * @param string $key Array key
844 * @return boolean Should the array item be deleted?
846 function api_reformat_xml(&$item, &$key)
848 if (is_bool($item)) {
849 $item = ($item ? "true" : "false");
852 if (substr($key, 0, 10) == "statusnet_") {
853 $key = "statusnet:".substr($key, 10);
854 } elseif (substr($key, 0, 10) == "friendica_") {
855 $key = "friendica:".substr($key, 10);
857 /// @TODO old-lost code?
859 // $key = "default:".$key;
865 * @brief Creates the XML from a JSON style array
867 * @param array $data JSON style array
868 * @param string $root_element Name of the root element
870 * @return string The XML data
872 function api_create_xml($data, $root_element)
874 $childname = key($data);
875 $data2 = array_pop($data);
878 $namespaces = array("" => "http://api.twitter.com",
879 "statusnet" => "http://status.net/schema/api/1/",
880 "friendica" => "http://friendi.ca/schema/api/1/",
881 "georss" => "http://www.georss.org/georss");
883 /// @todo Auto detection of needed namespaces
884 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
885 $namespaces = array();
888 if (is_array($data2)) {
889 api_walk_recursive($data2, "api_reformat_xml");
896 foreach ($data2 as $item) {
897 $data4[$i++.":".$childname] = $item;
903 $data3 = array($root_element => $data2);
905 $ret = XML::fromArray($data3, $xml, false, $namespaces);
910 * @brief Formats the data according to the data type
912 * @param string $root_element Name of the root element
913 * @param string $type Return type (atom, rss, xml, json)
914 * @param array $data JSON style array
916 * @return (string|object) XML data or JSON data
918 function api_format_data($root_element, $type, $data)
926 $ret = api_create_xml($data, $root_element);
941 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
942 * returns a 401 status code and an error message if not.
943 * http://developer.twitter.com/doc/get/account/verify_credentials
945 function api_account_verify_credentials($type)
950 if (api_user() === false) {
951 throw new ForbiddenException();
954 unset($_REQUEST["user_id"]);
955 unset($_GET["user_id"]);
957 unset($_REQUEST["screen_name"]);
958 unset($_GET["screen_name"]);
960 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
962 $user_info = api_get_user($a);
964 // "verified" isn't used here in the standard
965 unset($user_info["verified"]);
967 // - Adding last status
969 $user_info["status"] = api_status_show("raw");
970 if (!count($user_info["status"])) {
971 unset($user_info["status"]);
973 unset($user_info["status"]["user"]);
977 // "uid" and "self" are only needed for some internal stuff, so remove it from here
978 unset($user_info["uid"]);
979 unset($user_info["self"]);
981 return api_format_data("user", $type, array('user' => $user_info));
984 /// @TODO move to top of file or somwhere better
985 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
988 * Get data from $_POST or $_GET
990 function requestdata($k)
1001 /*Waitman Gobble Mod*/
1002 function api_statuses_mediap($type)
1006 if (api_user() === false) {
1007 logger('api_statuses_update: no user');
1008 throw new ForbiddenException();
1010 $user_info = api_get_user($a);
1012 $_REQUEST['type'] = 'wall';
1013 $_REQUEST['profile_uid'] = api_user();
1014 $_REQUEST['api_source'] = true;
1015 $txt = requestdata('status');
1016 /// @TODO old-lost code?
1017 //$txt = urldecode(requestdata('status'));
1019 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1020 $txt = html2bb_video($txt);
1021 $config = HTMLPurifier_Config::createDefault();
1022 $config->set('Cache.DefinitionImpl', null);
1023 $purifier = new HTMLPurifier($config);
1024 $txt = $purifier->purify($txt);
1026 $txt = html2bbcode($txt);
1028 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1030 // tell wall_upload function to return img info instead of echo
1031 $_REQUEST['hush'] = 'yeah';
1032 $bebop = wall_upload_post($a);
1034 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1035 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1038 // this should output the last post (the one we just posted).
1039 return api_status_show($type);
1042 /// @TODO move this to top of file or somewhere better!
1043 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1045 function api_statuses_update($type)
1050 if (api_user() === false) {
1051 logger('api_statuses_update: no user');
1052 throw new ForbiddenException();
1055 $user_info = api_get_user($a);
1057 // convert $_POST array items to the form we use for web posts.
1059 // logger('api_post: ' . print_r($_POST,true));
1061 if (requestdata('htmlstatus')) {
1062 $txt = requestdata('htmlstatus');
1063 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1064 $txt = html2bb_video($txt);
1066 $config = HTMLPurifier_Config::createDefault();
1067 $config->set('Cache.DefinitionImpl', null);
1069 $purifier = new HTMLPurifier($config);
1070 $txt = $purifier->purify($txt);
1072 $_REQUEST['body'] = html2bbcode($txt);
1075 $_REQUEST['body'] = requestdata('status');
1078 $_REQUEST['title'] = requestdata('title');
1080 $parent = requestdata('in_reply_to_status_id');
1082 // Twidere sends "-1" if it is no reply ...
1083 if ($parent == -1) {
1087 if (ctype_digit($parent)) {
1088 $_REQUEST['parent'] = $parent;
1090 $_REQUEST['parent_uri'] = $parent;
1093 if (requestdata('lat') && requestdata('long')) {
1094 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1096 $_REQUEST['profile_uid'] = api_user();
1099 $_REQUEST['type'] = 'net-comment';
1101 // Check for throttling (maximum posts per day, week and month)
1102 $throttle_day = Config::get('system', 'throttle_limit_day');
1103 if ($throttle_day > 0) {
1104 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1107 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1108 AND `created` > '%s' AND `id` = `parent`",
1113 if (DBM::is_result($r)) {
1114 $posts_day = $r[0]["posts_day"];
1119 if ($posts_day > $throttle_day) {
1120 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1121 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1122 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1126 $throttle_week = Config::get('system', 'throttle_limit_week');
1127 if ($throttle_week > 0) {
1128 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1131 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1132 AND `created` > '%s' AND `id` = `parent`",
1137 if (DBM::is_result($r)) {
1138 $posts_week = $r[0]["posts_week"];
1143 if ($posts_week > $throttle_week) {
1144 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1145 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1146 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1150 $throttle_month = Config::get('system', 'throttle_limit_month');
1151 if ($throttle_month > 0) {
1152 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1155 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1156 AND `created` > '%s' AND `id` = `parent`",
1161 if (DBM::is_result($r)) {
1162 $posts_month = $r[0]["posts_month"];
1167 if ($posts_month > $throttle_month) {
1168 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1169 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1170 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1174 $_REQUEST['type'] = 'wall';
1177 if (x($_FILES, 'media')) {
1178 // upload the image if we have one
1179 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1180 $media = wall_upload_post($a);
1181 if (strlen($media) > 0) {
1182 $_REQUEST['body'] .= "\n\n" . $media;
1186 // To-Do: Multiple IDs
1187 if (requestdata('media_ids')) {
1189 "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",
1190 intval(requestdata('media_ids')),
1193 if (DBM::is_result($r)) {
1194 $phototypes = Photo::supportedTypes();
1195 $ext = $phototypes[$r[0]['type']];
1196 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1197 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1201 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1203 $_REQUEST['api_source'] = true;
1205 if (!x($_REQUEST, "source")) {
1206 $_REQUEST["source"] = api_source();
1209 // call out normal post function
1212 // this should output the last post (the one we just posted).
1213 return api_status_show($type);
1216 /// @TODO move to top of file or somwhere better
1217 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1218 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1220 function api_media_upload($type)
1224 if (api_user() === false) {
1226 throw new ForbiddenException();
1229 $user_info = api_get_user($a);
1231 if (!x($_FILES, 'media')) {
1233 throw new BadRequestException("No media.");
1236 $media = wall_upload_post($a, false);
1239 throw new InternalServerErrorException();
1242 $returndata = array();
1243 $returndata["media_id"] = $media["id"];
1244 $returndata["media_id_string"] = (string)$media["id"];
1245 $returndata["size"] = $media["size"];
1246 $returndata["image"] = array("w" => $media["width"],
1247 "h" => $media["height"],
1248 "image_type" => $media["type"]);
1250 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1252 return array("media" => $returndata);
1255 /// @TODO move to top of file or somwhere better
1256 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1258 function api_status_show($type)
1262 $user_info = api_get_user($a);
1264 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1266 if ($type == "raw") {
1267 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1272 // get last public wall message
1276 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1277 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1278 AND `item`.`type` != 'activity' $privacy_sql
1279 ORDER BY `item`.`id` DESC
1281 intval($user_info['cid']),
1283 dbesc($user_info['url']),
1284 dbesc(normalise_link($user_info['url'])),
1285 dbesc($user_info['url']),
1286 dbesc(normalise_link($user_info['url']))
1289 if (DBM::is_result($lastwall)) {
1290 $lastwall = $lastwall[0];
1292 $in_reply_to = api_in_reply_to($lastwall);
1294 $converted = api_convert_item($lastwall);
1296 if ($type == "xml") {
1297 $geo = "georss:point";
1302 $status_info = array(
1303 'created_at' => api_date($lastwall['created']),
1304 'id' => intval($lastwall['id']),
1305 'id_str' => (string) $lastwall['id'],
1306 'text' => $converted["text"],
1307 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1308 'truncated' => false,
1309 'in_reply_to_status_id' => $in_reply_to['status_id'],
1310 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1311 'in_reply_to_user_id' => $in_reply_to['user_id'],
1312 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1313 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1314 'user' => $user_info,
1316 'coordinates' => "",
1318 'contributors' => "",
1319 'is_quote_status' => false,
1320 'retweet_count' => 0,
1321 'favorite_count' => 0,
1322 'favorited' => $lastwall['starred'] ? true : false,
1323 'retweeted' => false,
1324 'possibly_sensitive' => false,
1326 'statusnet_html' => $converted["html"],
1327 'statusnet_conversation_id' => $lastwall['parent'],
1330 if (count($converted["attachments"]) > 0) {
1331 $status_info["attachments"] = $converted["attachments"];
1334 if (count($converted["entities"]) > 0) {
1335 $status_info["entities"] = $converted["entities"];
1338 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1339 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1340 } elseif (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1341 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1344 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1345 unset($status_info["user"]["uid"]);
1346 unset($status_info["user"]["self"]);
1349 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1351 if ($type == "raw") {
1352 return $status_info;
1355 return api_format_data("statuses", $type, array('status' => $status_info));
1359 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1360 * The author's most recent status will be returned inline.
1361 * http://developer.twitter.com/doc/get/users/show
1363 function api_users_show($type)
1367 $user_info = api_get_user($a);
1371 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1372 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1373 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1374 AND `type`!='activity'
1375 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1379 dbesc(ACTIVITY_POST),
1380 intval($user_info['cid']),
1381 dbesc($user_info['url']),
1382 dbesc(normalise_link($user_info['url'])),
1383 dbesc($user_info['url']),
1384 dbesc(normalise_link($user_info['url']))
1387 if (DBM::is_result($lastwall)) {
1388 $lastwall = $lastwall[0];
1390 $in_reply_to = api_in_reply_to($lastwall);
1392 $converted = api_convert_item($lastwall);
1394 if ($type == "xml") {
1395 $geo = "georss:point";
1400 $user_info['status'] = array(
1401 'text' => $converted["text"],
1402 'truncated' => false,
1403 'created_at' => api_date($lastwall['created']),
1404 'in_reply_to_status_id' => $in_reply_to['status_id'],
1405 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1406 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1407 'id' => intval($lastwall['contact-id']),
1408 'id_str' => (string) $lastwall['contact-id'],
1409 'in_reply_to_user_id' => $in_reply_to['user_id'],
1410 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1411 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1413 'favorited' => $lastwall['starred'] ? true : false,
1414 'statusnet_html' => $converted["html"],
1415 'statusnet_conversation_id' => $lastwall['parent'],
1418 if (count($converted["attachments"]) > 0) {
1419 $user_info["status"]["attachments"] = $converted["attachments"];
1422 if (count($converted["entities"]) > 0) {
1423 $user_info["status"]["entities"] = $converted["entities"];
1426 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1427 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1430 if (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1431 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
1435 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1436 unset($user_info["uid"]);
1437 unset($user_info["self"]);
1439 return api_format_data("user", $type, array('user' => $user_info));
1442 /// @TODO move to top of file or somewhere better
1443 api_register_func('api/users/show', 'api_users_show');
1444 api_register_func('api/externalprofile/show', 'api_users_show');
1446 function api_users_search($type)
1450 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1452 $userlist = array();
1454 if (x($_GET, 'q')) {
1455 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1457 if (!DBM::is_result($r)) {
1458 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1461 if (DBM::is_result($r)) {
1463 foreach ($r as $user) {
1464 $user_info = api_get_user($a, $user["id"], "json");
1466 if ($type == "xml") {
1467 $userlist[$k++.":user"] = $user_info;
1469 $userlist[] = $user_info;
1472 $userlist = array("users" => $userlist);
1474 throw new BadRequestException("User not found.");
1477 throw new BadRequestException("User not found.");
1479 return api_format_data("users", $type, $userlist);
1482 /// @TODO move to top of file or somewhere better
1483 api_register_func('api/users/search', 'api_users_search');
1487 * http://developer.twitter.com/doc/get/statuses/home_timeline
1489 * TODO: Optional parameters
1490 * TODO: Add reply info
1492 function api_statuses_home_timeline($type)
1496 if (api_user() === false) {
1497 throw new ForbiddenException();
1500 unset($_REQUEST["user_id"]);
1501 unset($_GET["user_id"]);
1503 unset($_REQUEST["screen_name"]);
1504 unset($_GET["screen_name"]);
1506 $user_info = api_get_user($a);
1507 // get last newtork messages
1510 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1511 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1515 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1516 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1517 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1518 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1519 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1521 $start = $page * $count;
1525 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1527 if ($exclude_replies > 0) {
1528 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1530 if ($conversation_id > 0) {
1531 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1535 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1536 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1537 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1538 `contact`.`id` AS `cid`
1540 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1541 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1542 WHERE `item`.`uid` = %d AND `verb` = '%s'
1543 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1546 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1548 dbesc(ACTIVITY_POST),
1554 $ret = api_format_items($r, $user_info, false, $type);
1556 // Set all posts from the query above to seen
1558 foreach ($r as $item) {
1559 $idarray[] = intval($item["id"]);
1562 $idlist = implode(",", $idarray);
1564 if ($idlist != "") {
1565 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1568 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1572 $data = array('status' => $ret);
1576 $data = api_rss_extra($a, $data, $user_info);
1580 return api_format_data("statuses", $type, $data);
1583 /// @TODO move to top of file or somewhere better
1584 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1585 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1587 function api_statuses_public_timeline($type)
1591 if (api_user() === false) {
1592 throw new ForbiddenException();
1595 $user_info = api_get_user($a);
1596 // get last newtork messages
1599 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1600 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1604 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1605 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1606 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1607 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1608 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1610 $start = $page * $count;
1613 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1615 if ($exclude_replies > 0) {
1616 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1618 if ($conversation_id > 0) {
1619 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1623 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1624 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1625 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1626 `contact`.`id` AS `cid`,
1627 `user`.`nickname`, `user`.`hidewall`
1629 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1630 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1631 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1632 AND NOT `user`.`hidewall`
1633 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1634 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1635 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1636 AND NOT `item`.`private` AND `item`.`wall`
1639 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1640 dbesc(ACTIVITY_POST),
1646 $ret = api_format_items($r, $user_info, false, $type);
1648 $data = array('status' => $ret);
1652 $data = api_rss_extra($a, $data, $user_info);
1656 return api_format_data("statuses", $type, $data);
1659 /// @TODO move to top of file or somewhere better
1660 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1663 * @TODO nothing to say?
1665 function api_statuses_show($type)
1669 if (api_user() === false) {
1670 throw new ForbiddenException();
1673 $user_info = api_get_user($a);
1676 $id = intval($a->argv[3]);
1679 $id = intval($_REQUEST["id"]);
1684 $id = intval($a->argv[4]);
1687 logger('API: api_statuses_show: ' . $id);
1689 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1692 if ($conversation) {
1693 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1695 $sql_extra .= " AND `item`.`id` = %d";
1699 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1700 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1701 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1702 `contact`.`id` AS `cid`
1704 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1705 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1706 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1707 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1710 dbesc(ACTIVITY_POST),
1714 /// @TODO How about copying this to above methods which don't check $r ?
1715 if (!DBM::is_result($r)) {
1716 throw new BadRequestException("There is no status with this id.");
1719 $ret = api_format_items($r, $user_info, false, $type);
1721 if ($conversation) {
1722 $data = array('status' => $ret);
1723 return api_format_data("statuses", $type, $data);
1725 $data = array('status' => $ret[0]);
1726 return api_format_data("status", $type, $data);
1730 /// @TODO move to top of file or somewhere better
1731 api_register_func('api/statuses/show', 'api_statuses_show', true);
1734 * @TODO nothing to say?
1736 function api_conversation_show($type)
1740 if (api_user() === false) {
1741 throw new ForbiddenException();
1744 $user_info = api_get_user($a);
1747 $id = intval($a->argv[3]);
1748 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1749 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1753 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1754 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1756 $start = $page*$count;
1759 $id = intval($_REQUEST["id"]);
1764 $id = intval($a->argv[4]);
1767 logger('API: api_conversation_show: '.$id);
1769 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1770 if (DBM::is_result($r)) {
1771 $id = $r[0]["parent"];
1777 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1780 // Not sure why this query was so complicated. We should keep it here for a while,
1781 // just to make sure that we really don't need it.
1782 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1783 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1786 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1787 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1788 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1789 `contact`.`id` AS `cid`
1791 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1792 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1793 WHERE `item`.`parent` = %d AND `item`.`visible`
1794 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1795 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1796 AND `item`.`id`>%d $sql_extra
1797 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1798 intval($id), intval(api_user()),
1799 dbesc(ACTIVITY_POST),
1801 intval($start), intval($count)
1804 if (!DBM::is_result($r)) {
1805 throw new BadRequestException("There is no status with this id.");
1808 $ret = api_format_items($r, $user_info, false, $type);
1810 $data = array('status' => $ret);
1811 return api_format_data("statuses", $type, $data);
1814 /// @TODO move to top of file or somewhere better
1815 api_register_func('api/conversation/show', 'api_conversation_show', true);
1816 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1819 * @TODO nothing to say?
1821 function api_statuses_repeat($type)
1827 if (api_user() === false) {
1828 throw new ForbiddenException();
1831 $user_info = api_get_user($a);
1834 $id = intval($a->argv[3]);
1837 $id = intval($_REQUEST["id"]);
1842 $id = intval($a->argv[4]);
1845 logger('API: api_statuses_repeat: '.$id);
1848 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1849 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1850 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1851 `contact`.`id` AS `cid`
1853 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1854 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1855 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1856 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1857 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1859 AND `item`.`id`=%d",
1863 /// @TODO other style than above functions!
1864 if (DBM::is_result($r) && $r[0]['body'] != "") {
1865 if (strpos($r[0]['body'], "[/share]") !== false) {
1866 $pos = strpos($r[0]['body'], "[share");
1867 $post = substr($r[0]['body'], $pos);
1869 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1871 $post .= $r[0]['body'];
1872 $post .= "[/share]";
1874 $_REQUEST['body'] = $post;
1875 $_REQUEST['profile_uid'] = api_user();
1876 $_REQUEST['type'] = 'wall';
1877 $_REQUEST['api_source'] = true;
1879 if (!x($_REQUEST, "source")) {
1880 $_REQUEST["source"] = api_source();
1885 throw new ForbiddenException();
1888 // this should output the last post (the one we just posted).
1890 return api_status_show($type);
1893 /// @TODO move to top of file or somewhere better
1894 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1897 * @TODO nothing to say?
1899 function api_statuses_destroy($type)
1903 if (api_user() === false) {
1904 throw new ForbiddenException();
1907 $user_info = api_get_user($a);
1910 $id = intval($a->argv[3]);
1913 $id = intval($_REQUEST["id"]);
1918 $id = intval($a->argv[4]);
1921 logger('API: api_statuses_destroy: '.$id);
1923 $ret = api_statuses_show($type);
1925 drop_item($id, false);
1930 /// @TODO move to top of file or somewhere better
1931 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1934 * @TODO Nothing more than an URL to say?
1935 * http://developer.twitter.com/doc/get/statuses/mentions
1937 function api_statuses_mentions($type)
1941 if (api_user() === false) {
1942 throw new ForbiddenException();
1945 unset($_REQUEST["user_id"]);
1946 unset($_GET["user_id"]);
1948 unset($_REQUEST["screen_name"]);
1949 unset($_GET["screen_name"]);
1951 $user_info = api_get_user($a);
1952 // get last newtork messages
1956 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1957 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1961 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1962 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1963 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1965 $start = $page * $count;
1967 // Ugly code - should be changed
1968 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
1969 $myurl = substr($myurl, strpos($myurl, '://') + 3);
1970 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1971 $myurl = str_replace('www.', '', $myurl);
1972 $diasp_url = str_replace('/profile/', '/u/', $myurl);
1975 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1979 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1980 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1981 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1982 `contact`.`id` AS `cid`
1983 FROM `item` FORCE INDEX (`uid_id`)
1984 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1985 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1986 WHERE `item`.`uid` = %d AND `verb` = '%s'
1987 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1988 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1989 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1992 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1994 dbesc(ACTIVITY_POST),
1995 dbesc(protect_sprintf($myurl)),
1996 dbesc(protect_sprintf($myurl)),
2003 $ret = api_format_items($r, $user_info, false, $type);
2005 $data = array('status' => $ret);
2009 $data = api_rss_extra($a, $data, $user_info);
2013 return api_format_data("statuses", $type, $data);
2016 /// @TODO move to top of file or somewhere better
2017 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2018 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2020 function api_statuses_user_timeline($type)
2024 if (api_user() === false) {
2025 throw new ForbiddenException();
2028 $user_info = api_get_user($a);
2029 // get last network messages
2032 "api_statuses_user_timeline: api_user: ". api_user() .
2033 "\nuser_info: ".print_r($user_info, true) .
2034 "\n_REQUEST: ".print_r($_REQUEST, true),
2039 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2040 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2044 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2045 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2046 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
2047 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
2049 $start = $page * $count;
2052 if ($user_info['self'] == 1) {
2053 $sql_extra .= " AND `item`.`wall` = 1 ";
2056 if ($exclude_replies > 0) {
2057 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2059 if ($conversation_id > 0) {
2060 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2064 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2065 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2066 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2067 `contact`.`id` AS `cid`
2068 FROM `item` FORCE INDEX (`uid_contactid_id`)
2069 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2070 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2071 WHERE `item`.`uid` = %d AND `verb` = '%s'
2072 AND `item`.`contact-id` = %d
2073 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2076 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2078 dbesc(ACTIVITY_POST),
2079 intval($user_info['cid']),
2085 $ret = api_format_items($r, $user_info, true, $type);
2087 $data = array('status' => $ret);
2091 $data = api_rss_extra($a, $data, $user_info);
2095 return api_format_data("statuses", $type, $data);
2098 /// @TODO move to top of file or somwhere better
2099 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2102 * Star/unstar an item
2103 * param: id : id of the item
2105 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2107 function api_favorites_create_destroy($type)
2111 if (api_user() === false) {
2112 throw new ForbiddenException();
2115 // for versioned api.
2116 /// @TODO We need a better global soluton
2117 $action_argv_id = 2;
2118 if ($a->argv[1] == "1.1") {
2119 $action_argv_id = 3;
2122 if ($a->argc <= $action_argv_id) {
2123 throw new BadRequestException("Invalid request.");
2125 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2126 if ($a->argc == $action_argv_id + 2) {
2127 $itemid = intval($a->argv[$action_argv_id + 1]);
2129 /// @TODO use x() to check if _REQUEST contains 'id'
2130 $itemid = intval($_REQUEST['id']);
2133 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2135 if (!DBM::is_result($item) || count($item) == 0) {
2136 throw new BadRequestException("Invalid item.");
2141 $item[0]['starred'] = 1;
2144 $item[0]['starred'] = 0;
2147 throw new BadRequestException("Invalid action ".$action);
2150 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2152 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2155 throw new InternalServerErrorException("DB error");
2159 $user_info = api_get_user($a);
2160 $rets = api_format_items($item, $user_info, false, $type);
2163 $data = array('status' => $ret);
2167 $data = api_rss_extra($a, $data, $user_info);
2170 return api_format_data("status", $type, $data);
2173 /// @TODO move to top of file or somwhere better
2174 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2175 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2177 function api_favorites($type)
2183 if (api_user() === false) {
2184 throw new ForbiddenException();
2187 $called_api = array();
2189 $user_info = api_get_user($a);
2191 // in friendica starred item are private
2192 // return favorites only for self
2193 logger('api_favorites: self:' . $user_info['self']);
2195 if ($user_info['self'] == 0) {
2201 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2202 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2203 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2204 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2209 $start = $page*$count;
2212 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2216 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2217 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2218 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2219 `contact`.`id` AS `cid`
2220 FROM `item`, `contact`
2221 WHERE `item`.`uid` = %d
2222 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2223 AND `item`.`starred` = 1
2224 AND `contact`.`id` = `item`.`contact-id`
2225 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2228 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2235 $ret = api_format_items($r, $user_info, false, $type);
2238 $data = array('status' => $ret);
2242 $data = api_rss_extra($a, $data, $user_info);
2245 return api_format_data("statuses", $type, $data);
2248 /// @TODO move to top of file or somwhere better
2249 api_register_func('api/favorites', 'api_favorites', true);
2251 function api_format_messages($item, $recipient, $sender)
2253 // standard meta information
2255 'id' => $item['id'],
2256 'sender_id' => $sender['id'] ,
2258 'recipient_id' => $recipient['id'],
2259 'created_at' => api_date($item['created']),
2260 'sender_screen_name' => $sender['screen_name'],
2261 'recipient_screen_name' => $recipient['screen_name'],
2262 'sender' => $sender,
2263 'recipient' => $recipient,
2265 'friendica_seen' => $item['seen'],
2266 'friendica_parent_uri' => $item['parent-uri'],
2269 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2270 unset($ret["sender"]["uid"]);
2271 unset($ret["sender"]["self"]);
2272 unset($ret["recipient"]["uid"]);
2273 unset($ret["recipient"]["self"]);
2275 //don't send title to regular StatusNET requests to avoid confusing these apps
2276 if (x($_GET, 'getText')) {
2277 $ret['title'] = $item['title'];
2278 if ($_GET['getText'] == 'html') {
2279 $ret['text'] = bbcode($item['body'], false, false);
2280 } elseif ($_GET['getText'] == 'plain') {
2281 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2282 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2285 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2287 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2288 unset($ret['sender']);
2289 unset($ret['recipient']);
2295 function api_convert_item($item)
2297 $body = $item['body'];
2298 $attachments = api_get_attachments($body);
2300 // Workaround for ostatus messages where the title is identically to the body
2301 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2302 $statusbody = trim(html2plain($html, 0));
2304 // handle data: images
2305 $statusbody = api_format_items_embeded_images($item, $statusbody);
2307 $statustitle = trim($item['title']);
2309 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2310 $statustext = trim($statusbody);
2312 $statustext = trim($statustitle."\n\n".$statusbody);
2315 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2316 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2319 $statushtml = trim(bbcode($body, false, false));
2321 // Workaround for clients with limited HTML parser functionality
2322 $search = array("<br>", "<blockquote>", "</blockquote>",
2323 "<h1>", "</h1>", "<h2>", "</h2>",
2324 "<h3>", "</h3>", "<h4>", "</h4>",
2325 "<h5>", "</h5>", "<h6>", "</h6>");
2326 $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2327 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2328 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2329 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2330 $statushtml = str_replace($search, $replace, $statushtml);
2332 if ($item['title'] != "") {
2333 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2337 $oldtext = $statushtml;
2338 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2339 } while ($oldtext != $statushtml);
2341 if (substr($statushtml, 0, 4) == '<br>') {
2342 $statushtml = substr($statushtml, 4);
2345 if (substr($statushtml, 0, -4) == '<br>') {
2346 $statushtml = substr($statushtml, -4);
2349 // feeds without body should contain the link
2350 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2351 $statushtml .= bbcode($item['plink']);
2354 $entities = api_get_entitities($statustext, $body);
2357 "text" => $statustext,
2358 "html" => $statushtml,
2359 "attachments" => $attachments,
2360 "entities" => $entities
2364 function api_get_attachments(&$body)
2367 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2369 $URLSearchString = "^\[\]";
2370 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2376 $attachments = array();
2378 foreach ($images[1] as $image) {
2379 $imagedata = Photo::getPhotoInfo($image);
2382 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2386 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2387 foreach ($images[0] as $orig) {
2388 $body = str_replace($orig, "", $body);
2392 return $attachments;
2395 function api_get_entitities(&$text, $bbcode)
2399 * Links at the first character of the post
2404 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2406 if ($include_entities != "true") {
2407 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2409 foreach ($images[1] as $image) {
2410 $replace = proxy_url($image);
2411 $text = str_replace($image, $replace, $text);
2416 $bbcode = bb_CleanPictureLinks($bbcode);
2418 // Change pure links in text to bbcode uris
2419 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2421 $entities = array();
2422 $entities["hashtags"] = array();
2423 $entities["symbols"] = array();
2424 $entities["urls"] = array();
2425 $entities["user_mentions"] = array();
2427 $URLSearchString = "^\[\]";
2429 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2431 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2432 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2433 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2435 $bbcode = preg_replace(
2436 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2437 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2440 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2442 $bbcode = preg_replace(
2443 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2444 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2447 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2449 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2451 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2452 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2454 $ordered_urls = array();
2455 foreach ($urls[1] as $id => $url) {
2456 //$start = strpos($text, $url, $offset);
2457 $start = iconv_strpos($text, $url, 0, "UTF-8");
2458 if (!($start === false)) {
2459 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2463 ksort($ordered_urls);
2466 //foreach ($urls[1] AS $id=>$url) {
2467 foreach ($ordered_urls as $url) {
2468 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2469 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2471 $display_url = $url["title"];
2473 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2474 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2476 if (strlen($display_url) > 26)
2477 $display_url = substr($display_url, 0, 25)."…";
2480 //$start = strpos($text, $url, $offset);
2481 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2482 if (!($start === false)) {
2483 $entities["urls"][] = array("url" => $url["url"],
2484 "expanded_url" => $url["url"],
2485 "display_url" => $display_url,
2486 "indices" => array($start, $start+strlen($url["url"])));
2487 $offset = $start + 1;
2491 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2492 $ordered_images = array();
2493 foreach ($images[1] as $image) {
2494 //$start = strpos($text, $url, $offset);
2495 $start = iconv_strpos($text, $image, 0, "UTF-8");
2496 if (!($start === false))
2497 $ordered_images[$start] = $image;
2499 //$entities["media"] = array();
2502 foreach ($ordered_images as $url) {
2503 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2504 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2506 if (strlen($display_url) > 26)
2507 $display_url = substr($display_url, 0, 25)."…";
2509 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2510 if (!($start === false)) {
2511 $image = Photo::getPhotoInfo($url);
2513 // If image cache is activated, then use the following sizes:
2514 // thumb (150), small (340), medium (600) and large (1024)
2515 if (!Config::get("system", "proxy_disabled")) {
2516 $media_url = proxy_url($url);
2519 $scale = Photo::scaleImageTo($image[0], $image[1], 150);
2520 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2522 if (($image[0] > 150) || ($image[1] > 150)) {
2523 $scale = Photo::scaleImageTo($image[0], $image[1], 340);
2524 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2527 $scale = Photo::scaleImageTo($image[0], $image[1], 600);
2528 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2530 if (($image[0] > 600) || ($image[1] > 600)) {
2531 $scale = Photo::scaleImageTo($image[0], $image[1], 1024);
2532 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2536 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2539 $entities["media"][] = array(
2541 "id_str" => (string)$start+1,
2542 "indices" => array($start, $start+strlen($url)),
2543 "media_url" => normalise_link($media_url),
2544 "media_url_https" => $media_url,
2546 "display_url" => $display_url,
2547 "expanded_url" => $url,
2551 $offset = $start + 1;
2557 function api_format_items_embeded_images(&$item, $text)
2559 $text = preg_replace_callback(
2560 "|data:image/([^;]+)[^=]+=*|m",
2561 function ($match) use ($item) {
2562 return System::baseUrl()."/display/".$item['guid'];
2571 * @brief return <a href='url'>name</a> as array
2573 * @param string $txt text
2578 function api_contactlink_to_array($txt)
2581 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2582 if ($r && count($match)==3) {
2584 'name' => $match[2],
2598 * @brief return likes, dislikes and attend status for item
2600 * @param array $item array
2602 * likes => int count
2603 * dislikes => int count
2605 function api_format_items_activities(&$item, $type = "json")
2609 $activities = array(
2611 'dislike' => array(),
2612 'attendyes' => array(),
2613 'attendno' => array(),
2614 'attendmaybe' => array(),
2619 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2620 intval($item['uid']),
2624 foreach ($items as $i) {
2625 // not used as result should be structured like other user data
2626 //builtin_activity_puller($i, $activities);
2628 // get user data and add it to the array of the activity
2629 $user = api_get_user($a, $i['author-link']);
2630 switch ($i['verb']) {
2632 $activities['like'][] = $user;
2634 case ACTIVITY_DISLIKE:
2635 $activities['dislike'][] = $user;
2637 case ACTIVITY_ATTEND:
2638 $activities['attendyes'][] = $user;
2640 case ACTIVITY_ATTENDNO:
2641 $activities['attendno'][] = $user;
2643 case ACTIVITY_ATTENDMAYBE:
2644 $activities['attendmaybe'][] = $user;
2651 if ($type == "xml") {
2652 $xml_activities = array();
2653 foreach ($activities as $k => $v) {
2654 // change xml element from "like" to "friendica:like"
2655 $xml_activities["friendica:".$k] = $v;
2656 // add user data into xml output
2658 foreach ($v as $user)
2659 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2661 $activities = $xml_activities;
2669 * @brief return data from profiles
2671 * @param array $profile array containing data from db table 'profile'
2672 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2675 function api_format_items_profiles(&$profile = null, $type = "json")
2677 if ($profile != null) {
2678 $profile = array('profile_id' => $profile['id'],
2679 'profile_name' => $profile['profile-name'],
2680 'is_default' => $profile['is-default'] ? true : false,
2681 'hide_friends'=> $profile['hide-friends'] ? true : false,
2682 'profile_photo' => $profile['photo'],
2683 'profile_thumb' => $profile['thumb'],
2684 'publish' => $profile['publish'] ? true : false,
2685 'net_publish' => $profile['net-publish'] ? true : false,
2686 'description' => $profile['pdesc'],
2687 'date_of_birth' => $profile['dob'],
2688 'address' => $profile['address'],
2689 'city' => $profile['locality'],
2690 'region' => $profile['region'],
2691 'postal_code' => $profile['postal-code'],
2692 'country' => $profile['country-name'],
2693 'hometown' => $profile['hometown'],
2694 'gender' => $profile['gender'],
2695 'marital' => $profile['marital'],
2696 'marital_with' => $profile['with'],
2697 'marital_since' => $profile['howlong'],
2698 'sexual' => $profile['sexual'],
2699 'politic' => $profile['politic'],
2700 'religion' => $profile['religion'],
2701 'public_keywords' => $profile['pub_keywords'],
2702 'private_keywords' => $profile['prv_keywords'],
2703 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2704 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2705 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2706 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2707 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2708 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2709 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2710 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2711 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2712 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2713 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2714 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2715 'homepage' => $profile['homepage'],
2722 * @brief format items to be returned by api
2724 * @param array $r array of items
2725 * @param array $user_info
2726 * @param bool $filter_user filter items by $user_info
2728 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2734 foreach ($r as $item) {
2735 localize_item($item);
2736 list($status_user, $owner_user) = api_item_get_user($a, $item);
2738 // Look if the posts are matching if they should be filtered by user id
2739 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2743 $in_reply_to = api_in_reply_to($item);
2745 $converted = api_convert_item($item);
2747 if ($type == "xml") {
2748 $geo = "georss:point";
2754 'text' => $converted["text"],
2755 'truncated' => false,
2756 'created_at'=> api_date($item['created']),
2757 'in_reply_to_status_id' => $in_reply_to['status_id'],
2758 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2759 'source' => (($item['app']) ? $item['app'] : 'web'),
2760 'id' => intval($item['id']),
2761 'id_str' => (string) intval($item['id']),
2762 'in_reply_to_user_id' => $in_reply_to['user_id'],
2763 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2764 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2766 'favorited' => $item['starred'] ? true : false,
2767 'user' => $status_user ,
2768 'friendica_owner' => $owner_user,
2769 //'entities' => NULL,
2770 'statusnet_html' => $converted["html"],
2771 'statusnet_conversation_id' => $item['parent'],
2772 'friendica_activities' => api_format_items_activities($item, $type),
2775 if (count($converted["attachments"]) > 0) {
2776 $status["attachments"] = $converted["attachments"];
2779 if (count($converted["entities"]) > 0) {
2780 $status["entities"] = $converted["entities"];
2783 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
2784 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2785 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2786 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2790 // Retweets are only valid for top postings
2791 // It doesn't work reliable with the link if its a feed
2792 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2794 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
2797 if ($item["id"] == $item["parent"]) {
2798 $retweeted_item = api_share_as_retweet($item);
2799 if ($retweeted_item !== false) {
2800 $retweeted_status = $status;
2802 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
2803 } catch (BadRequestException $e) {
2804 // user not found. should be found?
2805 /// @todo check if the user should be always found
2806 $retweeted_status["user"] = array();
2809 $rt_converted = api_convert_item($retweeted_item);
2811 $retweeted_status['text'] = $rt_converted["text"];
2812 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2813 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2814 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2815 $status['retweeted_status'] = $retweeted_status;
2819 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2820 unset($status["user"]["uid"]);
2821 unset($status["user"]["self"]);
2823 if ($item["coord"] != "") {
2824 $coords = explode(' ', $item["coord"]);
2825 if (count($coords) == 2) {
2826 if ($type == "json")
2827 $status["geo"] = array('type' => 'Point',
2828 'coordinates' => array((float) $coords[0],
2829 (float) $coords[1]));
2830 else // Not sure if this is the official format - if someone founds a documentation we can check
2831 $status["georss:point"] = $item["coord"];
2839 function api_account_rate_limit_status($type)
2841 if ($type == "xml") {
2843 'remaining-hits' => '150',
2844 '@attributes' => array("type" => "integer"),
2845 'hourly-limit' => '150',
2846 '@attributes2' => array("type" => "integer"),
2847 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
2848 '@attributes3' => array("type" => "datetime"),
2849 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2850 '@attributes4' => array("type" => "integer"),
2854 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2855 'remaining_hits' => '150',
2856 'hourly_limit' => '150',
2857 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
2861 return api_format_data('hash', $type, array('hash' => $hash));
2864 /// @TODO move to top of file or somwhere better
2865 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
2867 function api_help_test($type)
2869 if ($type == 'xml') {
2875 return api_format_data('ok', $type, array("ok" => $ok));
2878 /// @TODO move to top of file or somwhere better
2879 api_register_func('api/help/test', 'api_help_test', false);
2881 function api_lists($type)
2884 /// @TODO $ret is not filled here?
2885 return api_format_data('lists', $type, array("lists_list" => $ret));
2888 /// @TODO move to top of file or somwhere better
2889 api_register_func('api/lists', 'api_lists', true);
2891 function api_lists_list($type)
2894 /// @TODO $ret is not filled here?
2895 return api_format_data('lists', $type, array("lists_list" => $ret));
2898 /// @TODO move to top of file or somwhere better
2899 api_register_func('api/lists/list', 'api_lists_list', true);
2902 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2903 * This function is deprecated by Twitter
2904 * returns: json, xml
2906 function api_statuses_f($type, $qtype)
2910 if (api_user() === false) {
2911 throw new ForbiddenException();
2914 $user_info = api_get_user($a);
2916 if (x($_GET, 'cursor') && $_GET['cursor']=='undefined') {
2917 /* this is to stop Hotot to load friends multiple times
2918 * I'm not sure if I'm missing return something or
2919 * is a bug in hotot. Workaround, meantime
2923 return array('$users' => $ret);*/
2927 if ($qtype == 'friends') {
2928 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2930 if ($qtype == 'followers') {
2931 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2934 // friends and followers only for self
2935 if ($user_info['self'] == 0) {
2936 $sql_extra = " AND false ";
2940 "SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra ORDER BY `nick`",
2945 foreach ($r as $cid) {
2946 $user = api_get_user($a, $cid['nurl']);
2947 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2948 unset($user["uid"]);
2949 unset($user["self"]);
2956 return array('user' => $ret);
2960 function api_statuses_friends($type)
2962 $data = api_statuses_f($type, "friends");
2963 if ($data === false) {
2966 return api_format_data("users", $type, $data);
2969 function api_statuses_followers($type)
2971 $data = api_statuses_f($type, "followers");
2972 if ($data === false) {
2975 return api_format_data("users", $type, $data);
2978 /// @TODO move to top of file or somewhere better
2979 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
2980 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
2982 function api_statusnet_config($type)
2986 $name = $a->config['sitename'];
2987 $server = $a->get_hostname();
2988 $logo = System::baseUrl() . '/images/friendica-64.png';
2989 $email = $a->config['admin_email'];
2990 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2991 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
2992 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2993 if ($a->config['api_import_size']) {
2994 $texlimit = string($a->config['api_import_size']);
2996 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
2997 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3000 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3001 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3002 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3003 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3004 'shorturllength' => '30',
3005 'friendica' => array(
3006 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3007 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3008 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3009 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3014 return api_format_data('config', $type, array('config' => $config));
3017 /// @TODO move to top of file or somewhere better
3018 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3019 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3021 function api_statusnet_version($type)
3024 $fake_statusnet_version = "0.9.7";
3026 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
3029 /// @TODO move to top of file or somewhere better
3030 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3031 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3034 * @todo use api_format_data() to return data
3036 function api_ff_ids($type,$qtype)
3041 throw new ForbiddenException();
3044 $user_info = api_get_user($a);
3046 if ($qtype == 'friends') {
3047 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3049 if ($qtype == 'followers') {
3050 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3053 if (!$user_info["self"]) {
3054 $sql_extra = " AND false ";
3057 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3060 "SELECT `pcontact`.`id` FROM `contact`
3061 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3062 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3066 if (!DBM::is_result($r)) {
3071 foreach ($r as $rr) {
3072 if ($stringify_ids) {
3075 $ids[] = intval($rr['id']);
3079 return api_format_data("ids", $type, array('id' => $ids));
3082 function api_friends_ids($type)
3084 return api_ff_ids($type, 'friends');
3087 function api_followers_ids($type)
3089 return api_ff_ids($type, 'followers');
3092 /// @TODO move to top of file or somewhere better
3093 api_register_func('api/friends/ids', 'api_friends_ids', true);
3094 api_register_func('api/followers/ids', 'api_followers_ids', true);
3096 function api_direct_messages_new($type)
3101 if (api_user() === false) throw new ForbiddenException();
3103 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) return;
3105 $sender = api_get_user($a);
3107 if ($_POST['screen_name']) {
3109 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3111 dbesc($_POST['screen_name'])
3114 // Selecting the id by priority, friendica first
3115 api_best_nickname($r);
3117 $recipient = api_get_user($a, $r[0]['nurl']);
3119 $recipient = api_get_user($a, $_POST['user_id']);
3124 if (x($_REQUEST, 'replyto')) {
3126 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3128 intval($_REQUEST['replyto'])
3130 $replyto = $r[0]['parent-uri'];
3131 $sub = $r[0]['title'];
3133 if (x($_REQUEST, 'title')) {
3134 $sub = $_REQUEST['title'];
3136 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3140 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3143 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3144 $ret = api_format_messages($r[0], $recipient, $sender);
3146 $ret = array("error"=>$id);
3149 $data = array('direct_message'=>$ret);
3154 $data = api_rss_extra($a, $data, $user_info);
3157 return api_format_data("direct-messages", $type, $data);
3161 /// @TODO move to top of file or somewhere better
3162 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3165 * @brief delete a direct_message from mail table through api
3167 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3170 function api_direct_messages_destroy($type)
3174 if (api_user() === false) {
3175 throw new ForbiddenException();
3179 $user_info = api_get_user($a);
3181 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3183 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3184 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3185 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3187 $uid = $user_info['uid'];
3188 // error if no id or parenturi specified (for clients posting parent-uri as well)
3189 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3190 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3191 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3194 // BadRequestException if no id specified (for clients using Twitter API)
3196 throw new BadRequestException('Message id not specified');
3199 // add parent-uri to sql command if specified by calling app
3200 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3202 // get data of the specified message id
3204 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3209 // error message if specified id is not in database
3210 if (!DBM::is_result($r)) {
3211 if ($verbose == "true") {
3212 $answer = array('result' => 'error', 'message' => 'message id not in database');
3213 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3215 /// @todo BadRequestException ok for Twitter API clients?
3216 throw new BadRequestException('message id not in database');
3221 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3226 if ($verbose == "true") {
3229 $answer = array('result' => 'ok', 'message' => 'message deleted');
3230 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3232 $answer = array('result' => 'error', 'message' => 'unknown error');
3233 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3236 /// @todo return JSON data like Twitter API not yet implemented
3240 /// @TODO move to top of file or somewhere better
3241 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3243 function api_direct_messages_box($type, $box, $verbose)
3247 if (api_user() === false) {
3248 throw new ForbiddenException();
3252 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3253 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3258 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3259 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3261 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3262 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3265 unset($_REQUEST["user_id"]);
3266 unset($_GET["user_id"]);
3268 unset($_REQUEST["screen_name"]);
3269 unset($_GET["screen_name"]);
3271 $user_info = api_get_user($a);
3272 $profile_url = $user_info["url"];
3275 $start = $page * $count;
3278 if ($box=="sentbox") {
3279 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3280 } elseif ($box == "conversation") {
3281 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3282 } elseif ($box == "all") {
3283 $sql_extra = "true";
3284 } elseif ($box == "inbox") {
3285 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3289 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3292 if ($user_id != "") {
3293 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3294 } elseif ($screen_name !="") {
3295 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3299 "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",
3305 if ($verbose == "true" && !DBM::is_result($r)) {
3306 $answer = array('result' => 'error', 'message' => 'no mails available');
3307 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3311 foreach ($r as $item) {
3312 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3313 $recipient = $user_info;
3314 $sender = api_get_user($a, normalise_link($item['contact-url']));
3315 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3316 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3317 $sender = $user_info;
3320 $ret[] = api_format_messages($item, $recipient, $sender);
3324 $data = array('direct_message' => $ret);
3328 $data = api_rss_extra($a, $data, $user_info);
3331 return api_format_data("direct-messages", $type, $data);
3334 function api_direct_messages_sentbox($type)
3336 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3337 return api_direct_messages_box($type, "sentbox", $verbose);
3340 function api_direct_messages_inbox($type)
3342 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3343 return api_direct_messages_box($type, "inbox", $verbose);
3346 function api_direct_messages_all($type)
3348 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3349 return api_direct_messages_box($type, "all", $verbose);
3352 function api_direct_messages_conversation($type)
3354 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3355 return api_direct_messages_box($type, "conversation", $verbose);
3358 /// @TODO move to top of file or somewhere better
3359 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3360 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3361 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3362 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3364 function api_oauth_request_token($type)
3367 $oauth = new FKOAuth1();
3368 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
3369 } catch (Exception $e) {
3370 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3377 function api_oauth_access_token($type)
3380 $oauth = new FKOAuth1();
3381 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
3382 } catch (Exception $e) {
3383 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3390 /// @TODO move to top of file or somewhere better
3391 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3392 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3396 * @brief delete a complete photoalbum with all containing photos from database through api
3398 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3401 function api_fr_photoalbum_delete($type)
3403 if (api_user() === false) {
3404 throw new ForbiddenException();
3407 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3409 // we do not allow calls without album string
3411 throw new BadRequestException("no albumname specified");
3413 // check if album is existing
3415 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3419 if (!DBM::is_result($r))
3420 throw new BadRequestException("album not available");
3422 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3423 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3424 foreach ($r as $rr) {
3426 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3427 intval(local_user()),
3428 dbesc($rr['resource-id'])
3431 if (!DBM::is_result($photo_item)) {
3432 throw new InternalServerErrorException("problem with deleting items occured");
3434 drop_item($photo_item[0]['id'], false);
3437 // now let's delete all photos from the album
3438 $result = dba::delete('photo', array('uid' => api_user(), 'album' => $album));
3440 // return success of deletion or error message
3442 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3443 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3445 throw new InternalServerErrorException("unknown error - deleting from database failed");
3450 * @brief update the name of the album for all photos of an album
3452 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3455 function api_fr_photoalbum_update($type)
3457 if (api_user() === false) {
3458 throw new ForbiddenException();
3461 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3462 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3464 // we do not allow calls without album string
3466 throw new BadRequestException("no albumname specified");
3468 if ($album_new == "") {
3469 throw new BadRequestException("no new albumname specified");
3471 // check if album is existing
3473 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3477 if (!DBM::is_result($r)) {
3478 throw new BadRequestException("album not available");
3480 // now let's update all photos to the albumname
3482 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3488 // return success of updating or error message
3490 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3491 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3493 throw new InternalServerErrorException("unknown error - updating in database failed");
3499 * @brief list all photos of the authenticated user
3501 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3504 function api_fr_photos_list($type)
3506 if (api_user() === false) {
3507 throw new ForbiddenException();
3510 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3511 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3512 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3513 intval(local_user())
3516 'image/jpeg' => 'jpg',
3517 'image/png' => 'png',
3518 'image/gif' => 'gif'
3520 $data = array('photo'=>array());
3521 if (DBM::is_result($r)) {
3522 foreach ($r as $rr) {
3524 $photo['id'] = $rr['resource-id'];
3525 $photo['album'] = $rr['album'];
3526 $photo['filename'] = $rr['filename'];
3527 $photo['type'] = $rr['type'];
3528 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3529 $photo['created'] = $rr['created'];
3530 $photo['edited'] = $rr['edited'];
3531 $photo['desc'] = $rr['desc'];
3533 if ($type == "xml") {
3534 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3536 $photo['thumb'] = $thumb;
3537 $data['photo'][] = $photo;
3541 return api_format_data("photos", $type, $data);
3545 * @brief upload a new photo or change an existing photo
3547 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3550 function api_fr_photo_create_update($type)
3552 if (api_user() === false) {
3553 throw new ForbiddenException();
3556 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3557 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3558 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3559 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3560 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3561 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3562 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3563 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3564 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3566 // do several checks on input parameters
3567 // we do not allow calls without album string
3568 if ($album == null) {
3569 throw new BadRequestException("no albumname specified");
3571 // if photo_id == null --> we are uploading a new photo
3572 if ($photo_id == null) {
3575 // error if no media posted in create-mode
3576 if (!x($_FILES, 'media')) {
3578 throw new BadRequestException("no media data submitted");
3581 // album_new will be ignored in create-mode
3586 // check if photo is existing in database
3588 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3593 if (!DBM::is_result($r)) {
3594 throw new BadRequestException("photo not available");
3598 // checks on acl strings provided by clients
3599 $acl_input_error = false;
3600 $acl_input_error |= check_acl_input($allow_cid);
3601 $acl_input_error |= check_acl_input($deny_cid);
3602 $acl_input_error |= check_acl_input($allow_gid);
3603 $acl_input_error |= check_acl_input($deny_gid);
3604 if ($acl_input_error) {
3605 throw new BadRequestException("acl data invalid");
3607 // now let's upload the new media in create-mode
3608 if ($mode == "create") {
3609 $media = $_FILES['media'];
3610 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3612 // return success of updating or error message
3613 if (!is_null($data)) {
3614 return api_format_data("photo_create", $type, $data);
3616 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3620 // now let's do the changes in update-mode
3621 if ($mode == "update") {
3624 if (!is_null($desc)) {
3625 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3628 if (!is_null($album_new)) {
3629 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3632 if (!is_null($allow_cid)) {
3633 $allow_cid = trim($allow_cid);
3634 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3637 if (!is_null($deny_cid)) {
3638 $deny_cid = trim($deny_cid);
3639 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3642 if (!is_null($allow_gid)) {
3643 $allow_gid = trim($allow_gid);
3644 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3647 if (!is_null($deny_gid)) {
3648 $deny_gid = trim($deny_gid);
3649 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3653 if ($sql_extra != "") {
3654 $nothingtodo = false;
3656 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3658 datetime_convert(), // update edited timestamp
3664 $nothingtodo = true;
3667 if (x($_FILES, 'media')) {
3668 $nothingtodo = false;
3669 $media = $_FILES['media'];
3670 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3671 if (!is_null($data)) {
3672 return api_format_data("photo_update", $type, $data);
3676 // return success of updating or error message
3678 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
3679 return api_format_data("photo_update", $type, array('$result' => $answer));
3682 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
3683 return api_format_data("photo_update", $type, array('$result' => $answer));
3685 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3688 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3693 * @brief delete a single photo from the database through api
3695 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3698 function api_fr_photo_delete($type)
3700 if (api_user() === false) {
3701 throw new ForbiddenException();
3704 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3706 // do several checks on input parameters
3707 // we do not allow calls without photo id
3708 if ($photo_id == null) {
3709 throw new BadRequestException("no photo_id specified");
3711 // check if photo is existing in database
3713 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3717 if (!DBM::is_result($r)) {
3718 throw new BadRequestException("photo not available");
3720 // now we can perform on the deletion of the photo
3721 $result = dba::delete('photo', array('uid' => api_user(), 'resource-id' => $photo_id));
3723 // return success of deletion or error message
3725 // retrieve the id of the parent element (the photo element)
3727 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3728 intval(local_user()),
3732 if (!DBM::is_result($photo_item)) {
3733 throw new InternalServerErrorException("problem with deleting items occured");
3735 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3736 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
3737 drop_item($photo_item[0]['id'], false);
3739 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
3740 return api_format_data("photo_delete", $type, array('$result' => $answer));
3742 throw new InternalServerErrorException("unknown error on deleting photo from database table");
3748 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3750 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3753 function api_fr_photo_detail($type)
3755 if (api_user() === false) {
3756 throw new ForbiddenException();
3758 if (!x($_REQUEST, 'photo_id')) {
3759 throw new BadRequestException("No photo id.");
3762 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3763 $photo_id = $_REQUEST['photo_id'];
3765 // prepare json/xml output with data from database for the requested photo
3766 $data = prepare_photo_data($type, $scale, $photo_id);
3768 return api_format_data("photo_detail", $type, $data);
3773 * @brief updates the profile image for the user (either a specified profile or the default profile)
3775 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3778 function api_account_update_profile_image($type)
3780 if (api_user() === false) {
3781 throw new ForbiddenException();
3784 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
3786 // error if image data is missing
3787 if (!x($_FILES, 'image')) {
3788 throw new BadRequestException("no media data submitted");
3791 // check if specified profile id is valid
3792 if ($profileid != 0) {
3794 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
3798 // error message if specified profile id is not in database
3799 if (!DBM::is_result($r)) {
3800 throw new BadRequestException("profile_id not available");
3802 $is_default_profile = $r['profile'];
3804 $is_default_profile = 1;
3807 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3809 if (x($_FILES, 'image')) {
3810 $media = $_FILES['image'];
3811 } elseif (x($_FILES, 'media')) {
3812 $media = $_FILES['media'];
3814 // save new profile image
3815 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
3818 if (is_array($media['type'])) {
3819 $filetype = $media['type'][0];
3821 $filetype = $media['type'];
3823 if ($filetype == "image/jpeg") {
3825 } elseif ($filetype == "image/png") {
3828 // change specified profile or all profiles to the new resource-id
3829 if ($is_default_profile) {
3831 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
3832 dbesc($data['photo']['id']),
3833 intval(local_user())
3837 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
3838 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
3839 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
3840 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
3841 intval(local_user())
3845 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
3846 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
3847 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
3848 intval($_REQUEST['profile']),
3849 intval(local_user())
3853 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
3854 // so that browsers will do a cache update unconditionally
3857 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
3858 dbesc(datetime_convert()),
3859 intval(local_user())
3862 // Update global directory in background
3863 //$user = api_get_user(get_app());
3864 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
3865 if ($url && strlen(Config::get('system', 'directory'))) {
3866 Worker::add(PRIORITY_LOW, "Directory", $url);
3869 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
3871 // output for client
3873 return api_account_verify_credentials($type);
3875 // SaveMediaToDatabase failed for some reason
3876 throw new InternalServerErrorException("image upload failed");
3880 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3881 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
3882 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
3883 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3884 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3885 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3886 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
3887 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3888 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3891 function check_acl_input($acl_string)
3893 if ($acl_string == null || $acl_string == " ") {
3896 $contact_not_found = false;
3898 // split <x><y><z> into array of cid's
3899 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3901 // check for each cid if it is available on server
3902 $cid_array = $array[0];
3903 foreach ($cid_array as $cid) {
3904 $cid = str_replace("<", "", $cid);
3905 $cid = str_replace(">", "", $cid);
3907 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3911 $contact_not_found |= !DBM::is_result($contact);
3913 return $contact_not_found;
3916 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)
3924 if (is_array($media)) {
3925 if (is_array($media['tmp_name'])) {
3926 $src = $media['tmp_name'][0];
3928 $src = $media['tmp_name'];
3930 if (is_array($media['name'])) {
3931 $filename = basename($media['name'][0]);
3933 $filename = basename($media['name']);
3935 if (is_array($media['size'])) {
3936 $filesize = intval($media['size'][0]);
3938 $filesize = intval($media['size']);
3940 if (is_array($media['type'])) {
3941 $filetype = $media['type'][0];
3943 $filetype = $media['type'];
3947 if ($filetype == "") {
3948 $filetype=Photo::guessImageType($filename);
3950 $imagedata = getimagesize($src);
3952 $filetype = $imagedata['mime'];
3955 "File upload src: " . $src . " - filename: " . $filename .
3956 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG
3959 // check if there was a php upload error
3960 if ($filesize == 0 && $media['error'] == 1) {
3961 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3963 // check against max upload size within Friendica instance
3964 $maximagesize = Config::get('system', 'maximagesize');
3965 if (($maximagesize) && ($filesize > $maximagesize)) {
3966 $formattedBytes = formatBytes($maximagesize);
3967 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3970 // create Photo instance with the data of the image
3971 $imagedata = @file_get_contents($src);
3972 $ph = new Photo($imagedata, $filetype);
3973 if (! $ph->isValid()) {
3974 throw new InternalServerErrorException("unable to process image data");
3977 // check orientation of image
3981 // check max length of images on server
3982 $max_length = Config::get('system', 'max_image_length');
3983 if (! $max_length) {
3984 $max_length = MAX_IMAGE_LENGTH;
3986 if ($max_length > 0) {
3987 $ph->scaleImage($max_length);
3988 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
3990 $width = $ph->getWidth();
3991 $height = $ph->getHeight();
3993 // create a new resource-id if not already provided
3994 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
3996 if ($mediatype == "photo") {
3997 // upload normal image (scales 0, 1, 2)
3998 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4000 $r =$ph->store(local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4002 logger("photo upload: image upload with scale 0 (original size) failed");
4004 if ($width > 640 || $height > 640) {
4005 $ph->scaleImage(640);
4006 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4008 logger("photo upload: image upload with scale 1 (640x640) failed");
4012 if ($width > 320 || $height > 320) {
4013 $ph->scaleImage(320);
4014 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4016 logger("photo upload: image upload with scale 2 (320x320) failed");
4019 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4020 } elseif ($mediatype == "profileimage") {
4021 // upload profile image (scales 4, 5, 6)
4022 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4024 if ($width > 175 || $height > 175) {
4025 $ph->scaleImage(175);
4026 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4028 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4032 if ($width > 80 || $height > 80) {
4033 $ph->scaleImage(80);
4034 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4036 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4040 if ($width > 48 || $height > 48) {
4041 $ph->scaleImage(48);
4042 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4044 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4048 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4052 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4053 if ($photo_id == null && $mediatype == "photo") {
4054 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4056 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4057 return prepare_photo_data($type, false, $hash);
4059 throw new InternalServerErrorException("image upload failed");
4063 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4065 // get data about the api authenticated user
4066 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4067 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4070 $arr['guid'] = get_guid(32);
4071 $arr['uid'] = intval(api_user());
4073 $arr['parent-uri'] = $uri;
4074 $arr['type'] = 'photo';
4076 $arr['resource-id'] = $hash;
4077 $arr['contact-id'] = $owner_record[0]['id'];
4078 $arr['owner-name'] = $owner_record[0]['name'];
4079 $arr['owner-link'] = $owner_record[0]['url'];
4080 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4081 $arr['author-name'] = $owner_record[0]['name'];
4082 $arr['author-link'] = $owner_record[0]['url'];
4083 $arr['author-avatar'] = $owner_record[0]['thumb'];
4085 $arr['allow_cid'] = $allow_cid;
4086 $arr['allow_gid'] = $allow_gid;
4087 $arr['deny_cid'] = $deny_cid;
4088 $arr['deny_gid'] = $deny_gid;
4089 $arr['last-child'] = 1;
4090 $arr['visible'] = $visibility;
4094 'image/jpeg' => 'jpg',
4095 'image/png' => 'png',
4096 'image/gif' => 'gif'
4099 // adds link to the thumbnail scale photo
4100 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4101 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4104 // do the magic for storing the item in the database and trigger the federation to other contacts
4108 function prepare_photo_data($type, $scale, $photo_id)
4110 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4111 $data_sql = ($scale === false ? "" : "data, ");
4113 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4114 // clients needs to convert this in their way for further processing
4116 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4117 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4118 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4119 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4121 intval(local_user()),
4127 'image/jpeg' => 'jpg',
4128 'image/png' => 'png',
4129 'image/gif' => 'gif'
4132 // prepare output data for photo
4133 if (DBM::is_result($r)) {
4134 $data = array('photo' => $r[0]);
4135 $data['photo']['id'] = $data['photo']['resource-id'];
4136 if ($scale !== false) {
4137 $data['photo']['data'] = base64_encode($data['photo']['data']);
4139 unset($data['photo']['datasize']); //needed only with scale param
4141 if ($type == "xml") {
4142 $data['photo']['links'] = array();
4143 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4144 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4146 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4149 $data['photo']['link'] = array();
4150 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4152 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4153 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4157 unset($data['photo']['resource-id']);
4158 unset($data['photo']['minscale']);
4159 unset($data['photo']['maxscale']);
4161 throw new NotFoundException();
4164 // retrieve item element for getting activities (like, dislike etc.) related to photo
4166 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4167 intval(local_user()),
4170 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4172 // retrieve comments on photo
4174 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4175 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4176 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4177 `contact`.`id` AS `cid`
4179 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4180 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4181 WHERE `item`.`parent` = %d AND `item`.`visible`
4182 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4183 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4184 intval($item[0]['parent']),
4186 dbesc(ACTIVITY_POST)
4189 // prepare output of comments
4190 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4191 $comments = array();
4192 if ($type == "xml") {
4194 foreach ($commentData as $comment) {
4195 $comments[$k++ . ":comment"] = $comment;
4198 foreach ($commentData as $comment) {
4199 $comments[] = $comment;
4202 $data['photo']['friendica_comments'] = $comments;
4204 // include info if rights on photo and rights on item are mismatching
4205 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4206 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4207 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4208 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4209 $data['photo']['rights_mismatch'] = $rights_mismatch;
4216 * Similar as /mod/redir.php
4217 * redirect to 'url' after dfrn auth
4219 * Why this when there is mod/redir.php already?
4220 * This use api_user() and api_login()
4223 * c_url: url of remote contact to auth to
4224 * url: string, url to redirect after auth
4226 function api_friendica_remoteauth()
4228 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4229 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4231 if ($url === '' || $c_url === '') {
4232 throw new BadRequestException("Wrong parameters.");
4235 $c_url = normalise_link($c_url);
4240 "SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4245 if ((! DBM::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4246 throw new BadRequestException("Unknown contact");
4251 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4253 if ($r[0]['duplex'] && $r[0]['issued-id']) {
4254 $orig_id = $r[0]['issued-id'];
4255 $dfrn_id = '1:' . $orig_id;
4257 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4258 $orig_id = $r[0]['dfrn-id'];
4259 $dfrn_id = '0:' . $orig_id;
4262 $sec = random_string();
4265 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4266 VALUES( %d, %s, '%s', '%s', %d )",
4274 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4275 $dest = (($url) ? '&destination_url=' . $url : '');
4277 $r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4278 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4279 . '&type=profile&sec=' . $sec . $dest . $quiet
4282 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4285 * @brief Return the item shared, if the item contains only the [share] tag
4287 * @param array $item Sharer item
4288 * @return array Shared item or false if not a reshare
4290 function api_share_as_retweet(&$item)
4292 $body = trim($item["body"]);
4294 if (Diaspora::isReshare($body, false)===false) {
4298 /// @TODO "$1" should maybe mean '$1' ?
4299 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4301 * Skip if there is no shared message in there
4302 * we already checked this in diaspora::isReshare()
4303 * but better one more than one less...
4305 if ($body == $attributes) {
4310 // build the fake reshared item
4311 $reshared_item = $item;
4314 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4315 if ($matches[1] != "") {
4316 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4319 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4320 if ($matches[1] != "") {
4321 $author = $matches[1];
4325 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4326 if ($matches[1] != "") {
4327 $profile = $matches[1];
4330 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4331 if ($matches[1] != "") {
4332 $profile = $matches[1];
4336 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4337 if ($matches[1] != "") {
4338 $avatar = $matches[1];
4341 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4342 if ($matches[1] != "") {
4343 $avatar = $matches[1];
4347 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4348 if ($matches[1] != "") {
4349 $link = $matches[1];
4352 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4353 if ($matches[1] != "") {
4354 $link = $matches[1];
4358 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4359 if ($matches[1] != "")
4360 $posted = $matches[1];
4362 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4363 if ($matches[1] != "") {
4364 $posted = $matches[1];
4367 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4369 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4373 $reshared_item["body"] = $shared_body;
4374 $reshared_item["author-name"] = $author;
4375 $reshared_item["author-link"] = $profile;
4376 $reshared_item["author-avatar"] = $avatar;
4377 $reshared_item["plink"] = $link;
4378 $reshared_item["created"] = $posted;
4379 $reshared_item["edited"] = $posted;
4381 return $reshared_item;
4385 function api_get_nick($profile)
4388 - remove trailing junk from profile url
4389 - pump.io check has to check the website
4395 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4396 dbesc(normalise_link($profile))
4399 if (DBM::is_result($r)) {
4400 $nick = $r[0]["nick"];
4405 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4406 dbesc(normalise_link($profile))
4409 if (DBM::is_result($r)) {
4410 $nick = $r[0]["nick"];
4415 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4416 if ($friendica != $profile) {
4422 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4423 if ($diaspora != $profile) {
4429 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4430 if ($twitter != $profile) {
4437 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4438 if ($StatusnetHost != $profile) {
4439 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4440 if ($StatusnetUser != $profile) {
4441 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4442 $user = json_decode($UserData);
4444 $nick = $user->screen_name;
4450 // To-Do: look at the page if its really a pumpio site
4451 //if (!$nick == "") {
4452 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4453 // if ($pumpio != $profile)
4455 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4466 function api_in_reply_to($item)
4468 $in_reply_to = array();
4470 $in_reply_to['status_id'] = null;
4471 $in_reply_to['user_id'] = null;
4472 $in_reply_to['status_id_str'] = null;
4473 $in_reply_to['user_id_str'] = null;
4474 $in_reply_to['screen_name'] = null;
4476 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4477 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4478 intval($item['uid']),
4479 dbesc($item['thr-parent']));
4481 if (DBM::is_result($r)) {
4482 $in_reply_to['status_id'] = intval($r[0]['id']);
4484 $in_reply_to['status_id'] = intval($item['parent']);
4487 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4489 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4490 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4491 WHERE `item`.`id` = %d LIMIT 1",
4492 intval($in_reply_to['status_id'])
4495 if (DBM::is_result($r)) {
4496 if ($r[0]['nick'] == "") {
4497 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4500 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4501 $in_reply_to['user_id'] = intval($r[0]['id']);
4502 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4505 // There seems to be situation, where both fields are identical:
4506 // https://github.com/friendica/friendica/issues/1010
4507 // This is a bugfix for that.
4508 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4509 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4510 $in_reply_to['status_id'] = null;
4511 $in_reply_to['user_id'] = null;
4512 $in_reply_to['status_id_str'] = null;
4513 $in_reply_to['user_id_str'] = null;
4514 $in_reply_to['screen_name'] = null;
4518 return $in_reply_to;
4521 function api_clean_plain_items($Text)
4523 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4525 $Text = bb_CleanPictureLinks($Text);
4526 $URLSearchString = "^\[\]";
4528 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
4530 if ($include_entities == "true") {
4531 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
4534 // Simplify "attachment" element
4535 $Text = api_clean_attachments($Text);
4541 * @brief Removes most sharing information for API text export
4543 * @param string $body The original body
4545 * @return string Cleaned body
4547 function api_clean_attachments($body)
4549 $data = get_attachment_data($body);
4556 if (isset($data["text"]))
4557 $body = $data["text"];
4559 if (($body == "") && (isset($data["title"])))
4560 $body = $data["title"];
4562 if (isset($data["url"]))
4563 $body .= "\n".$data["url"];
4565 $body .= $data["after"];
4570 function api_best_nickname(&$contacts)
4572 $best_contact = array();
4574 if (count($contact) == 0)
4577 foreach ($contacts as $contact)
4578 if ($contact["network"] == "") {
4579 $contact["network"] = "dfrn";
4580 $best_contact = array($contact);
4583 if (sizeof($best_contact) == 0)
4584 foreach ($contacts as $contact)
4585 if ($contact["network"] == "dfrn")
4586 $best_contact = array($contact);
4588 if (sizeof($best_contact) == 0)
4589 foreach ($contacts as $contact)
4590 if ($contact["network"] == "dspr")
4591 $best_contact = array($contact);
4593 if (sizeof($best_contact) == 0)
4594 foreach ($contacts as $contact)
4595 if ($contact["network"] == "stat")
4596 $best_contact = array($contact);
4598 if (sizeof($best_contact) == 0)
4599 foreach ($contacts as $contact)
4600 if ($contact["network"] == "pump")
4601 $best_contact = array($contact);
4603 if (sizeof($best_contact) == 0)
4604 foreach ($contacts as $contact)
4605 if ($contact["network"] == "twit")
4606 $best_contact = array($contact);
4608 if (sizeof($best_contact) == 1) {
4609 $contacts = $best_contact;
4611 $contacts = array($contacts[0]);
4615 // return all or a specified group of the user with the containing contacts
4616 function api_friendica_group_show($type)
4620 if (api_user() === false) throw new ForbiddenException();
4623 $user_info = api_get_user($a);
4624 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4625 $uid = $user_info['uid'];
4627 // get data of the specified group id or all groups if not specified
4630 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4634 // error message if specified gid is not in database
4635 if (!DBM::is_result($r))
4636 throw new BadRequestException("gid not available");
4639 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4644 // loop through all groups and retrieve all members for adding data in the user array
4645 foreach ($r as $rr) {
4646 $members = group_get_members($rr['id']);
4649 if ($type == "xml") {
4650 $user_element = "users";
4652 foreach ($members as $member) {
4653 $user = api_get_user($a, $member['nurl']);
4654 $users[$k++.":user"] = $user;
4657 $user_element = "user";
4658 foreach ($members as $member) {
4659 $user = api_get_user($a, $member['nurl']);
4663 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4665 return api_format_data("groups", $type, array('group' => $grps));
4667 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4670 // delete the specified group of the user
4671 function api_friendica_group_delete($type)
4675 if (api_user() === false) throw new ForbiddenException();
4678 $user_info = api_get_user($a);
4679 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4680 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4681 $uid = $user_info['uid'];
4683 // error if no gid specified
4684 if ($gid == 0 || $name == "")
4685 throw new BadRequestException('gid or name not specified');
4687 // get data of the specified group id
4689 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
4693 // error message if specified gid is not in database
4694 if (!DBM::is_result($r))
4695 throw new BadRequestException('gid not available');
4697 // get data of the specified group id and group name
4699 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
4704 // error message if specified gid is not in database
4705 if (!DBM::is_result($rname))
4706 throw new BadRequestException('wrong group name');
4709 $ret = group_rmv($uid, $name);
4712 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
4713 return api_format_data("group_delete", $type, array('result' => $success));
4715 throw new BadRequestException('other API error');
4718 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4721 // create the specified group with the posted array of contacts
4722 function api_friendica_group_create($type)
4726 if (api_user() === false) throw new ForbiddenException();
4729 $user_info = api_get_user($a);
4730 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4731 $uid = $user_info['uid'];
4732 $json = json_decode($_POST['json'], true);
4733 $users = $json['user'];
4735 // error if no name specified
4737 throw new BadRequestException('group name not specified');
4739 // get data of the specified group name
4741 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
4745 // error message if specified group name already exists
4746 if (DBM::is_result($rname))
4747 throw new BadRequestException('group name already exists');
4749 // check if specified group name is a deleted group
4751 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
4755 // error message if specified group name already exists
4756 if (DBM::is_result($rname))
4757 $reactivate_group = true;
4760 $ret = group_add($uid, $name);
4762 $gid = group_byname($uid, $name);
4764 throw new BadRequestException('other API error');
4768 $erroraddinguser = false;
4769 $errorusers = array();
4770 foreach ($users as $user) {
4771 $cid = $user['cid'];
4772 // check if user really exists as contact
4774 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4778 if (count($contact))
4779 $result = group_add_member($uid, $name, $cid, $gid);
4781 $erroraddinguser = true;
4782 $errorusers[] = $cid;
4786 // return success message incl. missing users in array
4787 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
4788 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4789 return api_format_data("group_create", $type, array('result' => $success));
4791 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4794 // update the specified group with the posted array of contacts
4795 function api_friendica_group_update($type)
4799 if (api_user() === false) throw new ForbiddenException();
4802 $user_info = api_get_user($a);
4803 $uid = $user_info['uid'];
4804 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4805 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4806 $json = json_decode($_POST['json'], true);
4807 $users = $json['user'];
4809 // error if no name specified
4811 throw new BadRequestException('group name not specified');
4813 // error if no gid specified
4815 throw new BadRequestException('gid not specified');
4818 $members = group_get_members($gid);
4819 foreach ($members as $member) {
4820 $cid = $member['id'];
4821 foreach ($users as $user) {
4822 $found = ($user['cid'] == $cid ? true : false);
4825 $ret = group_rmv_member($uid, $name, $cid);
4830 $erroraddinguser = false;
4831 $errorusers = array();
4832 foreach ($users as $user) {
4833 $cid = $user['cid'];
4834 // check if user really exists as contact
4836 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4841 if (count($contact)) {
4842 $result = group_add_member($uid, $name, $cid, $gid);
4844 $erroraddinguser = true;
4845 $errorusers[] = $cid;
4849 // return success message incl. missing users in array
4850 $status = ($erroraddinguser ? "missing user" : "ok");
4851 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4852 return api_format_data("group_update", $type, array('result' => $success));
4855 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4857 function api_friendica_activity($type)
4861 if (api_user() === false) throw new ForbiddenException();
4862 $verb = strtolower($a->argv[3]);
4863 $verb = preg_replace("|\..*$|", "", $verb);
4865 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4867 $res = do_like($id, $verb);
4870 if ($type == "xml") {
4875 return api_format_data('ok', $type, array('ok' => $ok));
4877 throw new BadRequestException('Error adding activity');
4881 /// @TODO move to top of file or somwhere better
4882 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
4883 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
4884 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
4885 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
4886 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4887 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
4888 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
4889 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
4890 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
4891 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4894 * @brief Returns notifications
4896 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4899 function api_friendica_notification($type)
4903 if (api_user() === false) throw new ForbiddenException();
4904 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
4905 $nm = new NotificationsManager();
4907 $notes = $nm->getAll(array(), "+seen -date", 50);
4909 if ($type == "xml") {
4910 $xmlnotes = array();
4911 foreach ($notes as $note)
4912 $xmlnotes[] = array("@attributes" => $note);
4917 return api_format_data("notes", $type, array('note' => $notes));
4921 * @brief Set notification as seen and returns associated item (if possible)
4923 * POST request with 'id' param as notification id
4925 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4928 function api_friendica_notification_seen($type)
4932 if (api_user() === false) throw new ForbiddenException();
4933 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
4935 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
4937 $nm = new NotificationsManager();
4938 $note = $nm->getByID($id);
4939 if (is_null($note)) throw new BadRequestException("Invalid argument");
4941 $nm->setSeen($note);
4942 if ($note['otype']=='item') {
4943 // would be really better with an ItemsManager and $im->getByID() :-P
4945 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
4946 intval($note['iid']),
4947 intval(local_user())
4950 // we found the item, return it to the user
4951 $user_info = api_get_user($a);
4952 $ret = api_format_items($r, $user_info, false, $type);
4953 $data = array('status' => $ret);
4954 return api_format_data("status", $type, $data);
4956 // the item can't be found, but we set the note as seen, so we count this as a success
4958 return api_format_data('result', $type, array('result' => "success"));
4961 /// @TODO move to top of file or somwhere better
4962 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4963 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
4966 * @brief update a direct_message to seen state
4968 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4969 * @return string (success result=ok, error result=error with error message)
4971 function api_friendica_direct_messages_setseen($type)
4974 if (api_user() === false) {
4975 throw new ForbiddenException();
4979 $user_info = api_get_user($a);
4980 $uid = $user_info['uid'];
4981 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4983 // return error if id is zero
4985 $answer = array('result' => 'error', 'message' => 'message id not specified');
4986 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4989 // get data of the specified message id
4991 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
4996 // error message if specified id is not in database
4997 if (!DBM::is_result($r)) {
4998 $answer = array('result' => 'error', 'message' => 'message id not in database');
4999 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5002 // update seen indicator
5004 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5011 $answer = array('result' => 'ok', 'message' => 'message set to seen');
5012 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
5014 $answer = array('result' => 'error', 'message' => 'unknown error');
5015 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5019 /// @TODO move to top of file or somwhere better
5020 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5023 * @brief search for direct_messages containing a searchstring through api
5025 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5026 * @return string (success: success=true if found and search_result contains found messages
5027 * success=false if nothing was found, search_result='nothing found',
5028 * error: result=error with error message)
5030 function api_friendica_direct_messages_search($type)
5034 if (api_user() === false) {
5035 throw new ForbiddenException();
5039 $user_info = api_get_user($a);
5040 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5041 $uid = $user_info['uid'];
5043 // error if no searchstring specified
5044 if ($searchstring == "") {
5045 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
5046 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
5049 // get data for the specified searchstring
5051 "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",
5053 dbesc('%'.$searchstring.'%')
5056 $profile_url = $user_info["url"];
5058 // message if nothing was found
5059 if (!DBM::is_result($r)) {
5060 $success = array('success' => false, 'search_results' => 'problem with query');
5061 } elseif (count($r) == 0) {
5062 $success = array('success' => false, 'search_results' => 'nothing found');
5065 foreach ($r as $item) {
5066 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5067 $recipient = $user_info;
5068 $sender = api_get_user($a, normalise_link($item['contact-url']));
5069 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5070 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5071 $sender = $user_info;
5074 $ret[] = api_format_messages($item, $recipient, $sender);
5076 $success = array('success' => true, 'search_results' => $ret);
5079 return api_format_data("direct_message_search", $type, array('$result' => $success));
5082 /// @TODO move to top of file or somwhere better
5083 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5086 * @brief return data of all the profiles a user has to the client
5088 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5091 function api_friendica_profile_show($type)
5095 if (api_user() === false) {
5096 throw new ForbiddenException();
5100 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5102 // retrieve general information about profiles for user
5103 $multi_profiles = feature_enabled(api_user(), 'multi_profiles');
5104 $directory = Config::get('system', 'directory');
5106 // get data of the specified profile id or all profiles of the user if not specified
5107 if ($profileid != 0) {
5109 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5114 // error message if specified gid is not in database
5115 if (!DBM::is_result($r)) {
5116 throw new BadRequestException("profile_id not available");
5120 "SELECT * FROM `profile` WHERE `uid` = %d",
5124 // loop through all returned profiles and retrieve data and users
5126 foreach ($r as $rr) {
5127 $profile = api_format_items_profiles($rr, $type);
5129 // select all users from contact table, loop and prepare standard return for user data
5132 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5134 intval($rr['profile_id'])
5137 foreach ($r as $rr) {
5138 $user = api_get_user($a, $rr['nurl']);
5139 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5141 $profile['users'] = $users;
5143 // add prepared profile data to array for final return
5144 if ($type == "xml") {
5145 $profiles[$k++ . ":profile"] = $profile;
5147 $profiles[] = $profile;
5151 // return settings, authenticated user and profiles data
5152 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5154 $result = array('multi_profiles' => $multi_profiles ? true : false,
5155 'global_dir' => $directory,
5156 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5157 'profiles' => $profiles);
5158 return api_format_data("friendica_profiles", $type, array('$result' => $result));
5160 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5163 @TODO Maybe open to implement?
5165 [pagename] => api/1.1/statuses/lookup.json
5166 [id] => 605138389168451584
5167 [include_cards] => true
5168 [cards_platform] => Android-12
5169 [include_entities] => true
5170 [include_my_retweet] => 1
5172 [include_reply_count] => true
5173 [include_descendent_reply_count] => true
5177 Not implemented by now:
5178 statuses/retweets_of_me
5183 account/update_location
5184 account/update_profile_background_image
5187 friendica/profile/update
5188 friendica/profile/create
5189 friendica/profile/delete
5191 Not implemented in status.net:
5192 statuses/retweeted_to_me
5193 statuses/retweeted_by_me
5194 direct_messages/destroy
5196 account/update_delivery_device
5197 notifications/follow