3 * @file include/api.php
4 * Friendica implementation of statusnet/twitter API
6 * @todo Automatically detect if incoming data is HTML or BBCode
9 use Friendica\Content\Feature;
10 use Friendica\Core\System;
11 use Friendica\Core\Config;
12 use Friendica\Core\NotificationsManager;
13 use Friendica\Core\Worker;
14 use Friendica\Database\DBM;
15 use Friendica\Model\User;
16 use Friendica\Network\FKOAuth1;
17 use Friendica\Network\HTTPException;
18 use Friendica\Network\HTTPException\BadRequestException;
19 use Friendica\Network\HTTPException\ForbiddenException;
20 use Friendica\Network\HTTPException\InternalServerErrorException;
21 use Friendica\Network\HTTPException\MethodNotAllowedException;
22 use Friendica\Network\HTTPException\NotFoundException;
23 use Friendica\Network\HTTPException\NotImplementedException;
24 use Friendica\Network\HTTPException\UnauthorizedException;
25 use Friendica\Network\HTTPException\TooManyRequestsException;
26 use Friendica\Object\Contact;
27 use Friendica\Object\Photo;
28 use Friendica\Protocol\Diaspora;
29 use Friendica\Util\XML;
31 require_once 'include/bbcode.php';
32 require_once 'include/datetime.php';
33 require_once 'include/conversation.php';
34 require_once 'include/html2plain.php';
35 require_once 'mod/share.php';
36 require_once 'mod/item.php';
37 require_once 'include/security.php';
38 require_once 'include/contact_selectors.php';
39 require_once 'include/html2bbcode.php';
40 require_once 'mod/wall_upload.php';
41 require_once 'mod/proxy.php';
42 require_once 'include/message.php';
43 require_once 'include/group.php';
44 require_once 'include/like.php';
45 require_once 'include/plaintext.php';
47 define('API_METHOD_ANY', '*');
48 define('API_METHOD_GET', 'GET');
49 define('API_METHOD_POST', 'POST,PUT');
50 define('API_METHOD_DELETE', 'POST,DELETE');
56 * @brief Auth API user
58 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
59 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
60 * into a page, and visitors will post something without noticing it).
64 if (x($_SESSION, 'allow_api')) {
72 * @brief Get source name from API client
74 * Clients can send 'source' parameter to be show in post metadata
75 * as "sent via <source>".
76 * Some clients doesn't send a source param, we support ones we know
80 * Client source name, default to "api" if unset/unknown
84 if (requestdata('source')) {
85 return requestdata('source');
88 // Support for known clients that doesn't send a source name
89 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
93 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
99 * @brief Format date for API
101 * @param string $str Source date, as UTC
102 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
104 function api_date($str)
106 // Wed May 23 06:01:13 +0000 2007
107 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y");
111 * @brief Register API endpoint
113 * Register a function to be the endpont for defined API path.
115 * @param string $path API URL path, relative to System::baseUrl()
116 * @param string $func Function name to call on path request
117 * @param bool $auth API need logged user
118 * @param string $method HTTP method reqiured to call this endpoint.
119 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
120 * Default to API_METHOD_ANY
122 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
132 // Workaround for hotot
133 $path = str_replace("api/", "api/1.1/", $path);
143 * @brief Login API user
145 * Log in user via OAuth1 or Simple HTTP Auth.
146 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
148 * @param object $a App
149 * @hook 'authenticate'
151 * 'username' => username from login form
152 * 'password' => password from login form
153 * 'authenticated' => return status,
154 * 'user_record' => return authenticated user record
156 * array $user logged user record
158 function api_login(App $a)
162 list($consumer, $token) = FKOAuth1::verify_request(OAuthRequest::from_request());
163 if (!is_null($token)) {
164 FKOAuth1::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::getInfoFromURL($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::getInfoFromURL($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 $r = FKOAuth1::fetch_request_token(OAuthRequest::from_request());
3368 } catch (Exception $e) {
3369 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3376 function api_oauth_access_token($type)
3379 $r = FKOAuth1::fetch_access_token(OAuthRequest::from_request());
3380 } catch (Exception $e) {
3381 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3388 /// @TODO move to top of file or somewhere better
3389 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3390 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3394 * @brief delete a complete photoalbum with all containing photos from database through api
3396 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3399 function api_fr_photoalbum_delete($type)
3401 if (api_user() === false) {
3402 throw new ForbiddenException();
3405 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3407 // we do not allow calls without album string
3409 throw new BadRequestException("no albumname specified");
3411 // check if album is existing
3413 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3417 if (!DBM::is_result($r))
3418 throw new BadRequestException("album not available");
3420 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3421 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3422 foreach ($r as $rr) {
3424 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3425 intval(local_user()),
3426 dbesc($rr['resource-id'])
3429 if (!DBM::is_result($photo_item)) {
3430 throw new InternalServerErrorException("problem with deleting items occured");
3432 drop_item($photo_item[0]['id'], false);
3435 // now let's delete all photos from the album
3436 $result = dba::delete('photo', array('uid' => api_user(), 'album' => $album));
3438 // return success of deletion or error message
3440 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3441 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3443 throw new InternalServerErrorException("unknown error - deleting from database failed");
3448 * @brief update the name of the album for all photos of an album
3450 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3453 function api_fr_photoalbum_update($type)
3455 if (api_user() === false) {
3456 throw new ForbiddenException();
3459 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3460 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3462 // we do not allow calls without album string
3464 throw new BadRequestException("no albumname specified");
3466 if ($album_new == "") {
3467 throw new BadRequestException("no new albumname specified");
3469 // check if album is existing
3471 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3475 if (!DBM::is_result($r)) {
3476 throw new BadRequestException("album not available");
3478 // now let's update all photos to the albumname
3480 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3486 // return success of updating or error message
3488 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3489 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3491 throw new InternalServerErrorException("unknown error - updating in database failed");
3497 * @brief list all photos of the authenticated user
3499 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3502 function api_fr_photos_list($type)
3504 if (api_user() === false) {
3505 throw new ForbiddenException();
3508 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3509 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3510 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3511 intval(local_user())
3514 'image/jpeg' => 'jpg',
3515 'image/png' => 'png',
3516 'image/gif' => 'gif'
3518 $data = array('photo'=>array());
3519 if (DBM::is_result($r)) {
3520 foreach ($r as $rr) {
3522 $photo['id'] = $rr['resource-id'];
3523 $photo['album'] = $rr['album'];
3524 $photo['filename'] = $rr['filename'];
3525 $photo['type'] = $rr['type'];
3526 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3527 $photo['created'] = $rr['created'];
3528 $photo['edited'] = $rr['edited'];
3529 $photo['desc'] = $rr['desc'];
3531 if ($type == "xml") {
3532 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3534 $photo['thumb'] = $thumb;
3535 $data['photo'][] = $photo;
3539 return api_format_data("photos", $type, $data);
3543 * @brief upload a new photo or change an existing photo
3545 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3548 function api_fr_photo_create_update($type)
3550 if (api_user() === false) {
3551 throw new ForbiddenException();
3554 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3555 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3556 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3557 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3558 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3559 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3560 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3561 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3562 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3564 // do several checks on input parameters
3565 // we do not allow calls without album string
3566 if ($album == null) {
3567 throw new BadRequestException("no albumname specified");
3569 // if photo_id == null --> we are uploading a new photo
3570 if ($photo_id == null) {
3573 // error if no media posted in create-mode
3574 if (!x($_FILES, 'media')) {
3576 throw new BadRequestException("no media data submitted");
3579 // album_new will be ignored in create-mode
3584 // check if photo is existing in database
3586 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3591 if (!DBM::is_result($r)) {
3592 throw new BadRequestException("photo not available");
3596 // checks on acl strings provided by clients
3597 $acl_input_error = false;
3598 $acl_input_error |= check_acl_input($allow_cid);
3599 $acl_input_error |= check_acl_input($deny_cid);
3600 $acl_input_error |= check_acl_input($allow_gid);
3601 $acl_input_error |= check_acl_input($deny_gid);
3602 if ($acl_input_error) {
3603 throw new BadRequestException("acl data invalid");
3605 // now let's upload the new media in create-mode
3606 if ($mode == "create") {
3607 $media = $_FILES['media'];
3608 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3610 // return success of updating or error message
3611 if (!is_null($data)) {
3612 return api_format_data("photo_create", $type, $data);
3614 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3618 // now let's do the changes in update-mode
3619 if ($mode == "update") {
3622 if (!is_null($desc)) {
3623 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3626 if (!is_null($album_new)) {
3627 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3630 if (!is_null($allow_cid)) {
3631 $allow_cid = trim($allow_cid);
3632 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3635 if (!is_null($deny_cid)) {
3636 $deny_cid = trim($deny_cid);
3637 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3640 if (!is_null($allow_gid)) {
3641 $allow_gid = trim($allow_gid);
3642 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3645 if (!is_null($deny_gid)) {
3646 $deny_gid = trim($deny_gid);
3647 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3651 if ($sql_extra != "") {
3652 $nothingtodo = false;
3654 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3656 datetime_convert(), // update edited timestamp
3662 $nothingtodo = true;
3665 if (x($_FILES, 'media')) {
3666 $nothingtodo = false;
3667 $media = $_FILES['media'];
3668 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3669 if (!is_null($data)) {
3670 return api_format_data("photo_update", $type, $data);
3674 // return success of updating or error message
3676 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
3677 return api_format_data("photo_update", $type, array('$result' => $answer));
3680 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
3681 return api_format_data("photo_update", $type, array('$result' => $answer));
3683 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3686 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3691 * @brief delete a single photo from the database through api
3693 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3696 function api_fr_photo_delete($type)
3698 if (api_user() === false) {
3699 throw new ForbiddenException();
3702 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3704 // do several checks on input parameters
3705 // we do not allow calls without photo id
3706 if ($photo_id == null) {
3707 throw new BadRequestException("no photo_id specified");
3709 // check if photo is existing in database
3711 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3715 if (!DBM::is_result($r)) {
3716 throw new BadRequestException("photo not available");
3718 // now we can perform on the deletion of the photo
3719 $result = dba::delete('photo', array('uid' => api_user(), 'resource-id' => $photo_id));
3721 // return success of deletion or error message
3723 // retrieve the id of the parent element (the photo element)
3725 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3726 intval(local_user()),
3730 if (!DBM::is_result($photo_item)) {
3731 throw new InternalServerErrorException("problem with deleting items occured");
3733 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3734 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
3735 drop_item($photo_item[0]['id'], false);
3737 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
3738 return api_format_data("photo_delete", $type, array('$result' => $answer));
3740 throw new InternalServerErrorException("unknown error on deleting photo from database table");
3746 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3748 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3751 function api_fr_photo_detail($type)
3753 if (api_user() === false) {
3754 throw new ForbiddenException();
3756 if (!x($_REQUEST, 'photo_id')) {
3757 throw new BadRequestException("No photo id.");
3760 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3761 $photo_id = $_REQUEST['photo_id'];
3763 // prepare json/xml output with data from database for the requested photo
3764 $data = prepare_photo_data($type, $scale, $photo_id);
3766 return api_format_data("photo_detail", $type, $data);
3771 * @brief updates the profile image for the user (either a specified profile or the default profile)
3773 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3776 function api_account_update_profile_image($type)
3778 if (api_user() === false) {
3779 throw new ForbiddenException();
3782 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
3784 // error if image data is missing
3785 if (!x($_FILES, 'image')) {
3786 throw new BadRequestException("no media data submitted");
3789 // check if specified profile id is valid
3790 if ($profileid != 0) {
3792 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
3796 // error message if specified profile id is not in database
3797 if (!DBM::is_result($r)) {
3798 throw new BadRequestException("profile_id not available");
3800 $is_default_profile = $r['profile'];
3802 $is_default_profile = 1;
3805 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3807 if (x($_FILES, 'image')) {
3808 $media = $_FILES['image'];
3809 } elseif (x($_FILES, 'media')) {
3810 $media = $_FILES['media'];
3812 // save new profile image
3813 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
3816 if (is_array($media['type'])) {
3817 $filetype = $media['type'][0];
3819 $filetype = $media['type'];
3821 if ($filetype == "image/jpeg") {
3823 } elseif ($filetype == "image/png") {
3826 // change specified profile or all profiles to the new resource-id
3827 if ($is_default_profile) {
3829 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
3830 dbesc($data['photo']['id']),
3831 intval(local_user())
3835 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
3836 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
3837 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
3838 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
3839 intval(local_user())
3843 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
3844 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
3845 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
3846 intval($_REQUEST['profile']),
3847 intval(local_user())
3851 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
3852 // so that browsers will do a cache update unconditionally
3855 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
3856 dbesc(datetime_convert()),
3857 intval(local_user())
3860 // Update global directory in background
3861 //$user = api_get_user(get_app());
3862 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
3863 if ($url && strlen(Config::get('system', 'directory'))) {
3864 Worker::add(PRIORITY_LOW, "Directory", $url);
3867 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
3869 // output for client
3871 return api_account_verify_credentials($type);
3873 // SaveMediaToDatabase failed for some reason
3874 throw new InternalServerErrorException("image upload failed");
3878 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3879 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
3880 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
3881 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3882 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3883 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3884 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
3885 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3886 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3889 function check_acl_input($acl_string)
3891 if ($acl_string == null || $acl_string == " ") {
3894 $contact_not_found = false;
3896 // split <x><y><z> into array of cid's
3897 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3899 // check for each cid if it is available on server
3900 $cid_array = $array[0];
3901 foreach ($cid_array as $cid) {
3902 $cid = str_replace("<", "", $cid);
3903 $cid = str_replace(">", "", $cid);
3905 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3909 $contact_not_found |= !DBM::is_result($contact);
3911 return $contact_not_found;
3914 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)
3922 if (is_array($media)) {
3923 if (is_array($media['tmp_name'])) {
3924 $src = $media['tmp_name'][0];
3926 $src = $media['tmp_name'];
3928 if (is_array($media['name'])) {
3929 $filename = basename($media['name'][0]);
3931 $filename = basename($media['name']);
3933 if (is_array($media['size'])) {
3934 $filesize = intval($media['size'][0]);
3936 $filesize = intval($media['size']);
3938 if (is_array($media['type'])) {
3939 $filetype = $media['type'][0];
3941 $filetype = $media['type'];
3945 if ($filetype == "") {
3946 $filetype=Photo::guessImageType($filename);
3948 $imagedata = getimagesize($src);
3950 $filetype = $imagedata['mime'];
3953 "File upload src: " . $src . " - filename: " . $filename .
3954 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG
3957 // check if there was a php upload error
3958 if ($filesize == 0 && $media['error'] == 1) {
3959 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3961 // check against max upload size within Friendica instance
3962 $maximagesize = Config::get('system', 'maximagesize');
3963 if (($maximagesize) && ($filesize > $maximagesize)) {
3964 $formattedBytes = formatBytes($maximagesize);
3965 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3968 // create Photo instance with the data of the image
3969 $imagedata = @file_get_contents($src);
3970 $ph = new Photo($imagedata, $filetype);
3971 if (! $ph->isValid()) {
3972 throw new InternalServerErrorException("unable to process image data");
3975 // check orientation of image
3979 // check max length of images on server
3980 $max_length = Config::get('system', 'max_image_length');
3981 if (! $max_length) {
3982 $max_length = MAX_IMAGE_LENGTH;
3984 if ($max_length > 0) {
3985 $ph->scaleImage($max_length);
3986 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
3988 $width = $ph->getWidth();
3989 $height = $ph->getHeight();
3991 // create a new resource-id if not already provided
3992 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
3994 if ($mediatype == "photo") {
3995 // upload normal image (scales 0, 1, 2)
3996 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
3998 $r =$ph->store(local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4000 logger("photo upload: image upload with scale 0 (original size) failed");
4002 if ($width > 640 || $height > 640) {
4003 $ph->scaleImage(640);
4004 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4006 logger("photo upload: image upload with scale 1 (640x640) failed");
4010 if ($width > 320 || $height > 320) {
4011 $ph->scaleImage(320);
4012 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4014 logger("photo upload: image upload with scale 2 (320x320) failed");
4017 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4018 } elseif ($mediatype == "profileimage") {
4019 // upload profile image (scales 4, 5, 6)
4020 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4022 if ($width > 175 || $height > 175) {
4023 $ph->scaleImage(175);
4024 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4026 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4030 if ($width > 80 || $height > 80) {
4031 $ph->scaleImage(80);
4032 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4034 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4038 if ($width > 48 || $height > 48) {
4039 $ph->scaleImage(48);
4040 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4042 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4046 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4050 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4051 if ($photo_id == null && $mediatype == "photo") {
4052 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4054 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4055 return prepare_photo_data($type, false, $hash);
4057 throw new InternalServerErrorException("image upload failed");
4061 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4063 // get data about the api authenticated user
4064 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4065 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4068 $arr['guid'] = get_guid(32);
4069 $arr['uid'] = intval(api_user());
4071 $arr['parent-uri'] = $uri;
4072 $arr['type'] = 'photo';
4074 $arr['resource-id'] = $hash;
4075 $arr['contact-id'] = $owner_record[0]['id'];
4076 $arr['owner-name'] = $owner_record[0]['name'];
4077 $arr['owner-link'] = $owner_record[0]['url'];
4078 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4079 $arr['author-name'] = $owner_record[0]['name'];
4080 $arr['author-link'] = $owner_record[0]['url'];
4081 $arr['author-avatar'] = $owner_record[0]['thumb'];
4083 $arr['allow_cid'] = $allow_cid;
4084 $arr['allow_gid'] = $allow_gid;
4085 $arr['deny_cid'] = $deny_cid;
4086 $arr['deny_gid'] = $deny_gid;
4087 $arr['last-child'] = 1;
4088 $arr['visible'] = $visibility;
4092 'image/jpeg' => 'jpg',
4093 'image/png' => 'png',
4094 'image/gif' => 'gif'
4097 // adds link to the thumbnail scale photo
4098 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4099 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4102 // do the magic for storing the item in the database and trigger the federation to other contacts
4106 function prepare_photo_data($type, $scale, $photo_id)
4108 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4109 $data_sql = ($scale === false ? "" : "data, ");
4111 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4112 // clients needs to convert this in their way for further processing
4114 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4115 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4116 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4117 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4119 intval(local_user()),
4125 'image/jpeg' => 'jpg',
4126 'image/png' => 'png',
4127 'image/gif' => 'gif'
4130 // prepare output data for photo
4131 if (DBM::is_result($r)) {
4132 $data = array('photo' => $r[0]);
4133 $data['photo']['id'] = $data['photo']['resource-id'];
4134 if ($scale !== false) {
4135 $data['photo']['data'] = base64_encode($data['photo']['data']);
4137 unset($data['photo']['datasize']); //needed only with scale param
4139 if ($type == "xml") {
4140 $data['photo']['links'] = array();
4141 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4142 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4144 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4147 $data['photo']['link'] = array();
4148 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4150 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4151 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4155 unset($data['photo']['resource-id']);
4156 unset($data['photo']['minscale']);
4157 unset($data['photo']['maxscale']);
4159 throw new NotFoundException();
4162 // retrieve item element for getting activities (like, dislike etc.) related to photo
4164 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4165 intval(local_user()),
4168 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4170 // retrieve comments on photo
4172 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4173 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4174 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4175 `contact`.`id` AS `cid`
4177 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4178 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4179 WHERE `item`.`parent` = %d AND `item`.`visible`
4180 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4181 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4182 intval($item[0]['parent']),
4184 dbesc(ACTIVITY_POST)
4187 // prepare output of comments
4188 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4189 $comments = array();
4190 if ($type == "xml") {
4192 foreach ($commentData as $comment) {
4193 $comments[$k++ . ":comment"] = $comment;
4196 foreach ($commentData as $comment) {
4197 $comments[] = $comment;
4200 $data['photo']['friendica_comments'] = $comments;
4202 // include info if rights on photo and rights on item are mismatching
4203 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4204 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4205 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4206 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4207 $data['photo']['rights_mismatch'] = $rights_mismatch;
4214 * Similar as /mod/redir.php
4215 * redirect to 'url' after dfrn auth
4217 * Why this when there is mod/redir.php already?
4218 * This use api_user() and api_login()
4221 * c_url: url of remote contact to auth to
4222 * url: string, url to redirect after auth
4224 function api_friendica_remoteauth()
4226 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4227 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4229 if ($url === '' || $c_url === '') {
4230 throw new BadRequestException("Wrong parameters.");
4233 $c_url = normalise_link($c_url);
4238 "SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4243 if ((! DBM::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4244 throw new BadRequestException("Unknown contact");
4249 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4251 if ($r[0]['duplex'] && $r[0]['issued-id']) {
4252 $orig_id = $r[0]['issued-id'];
4253 $dfrn_id = '1:' . $orig_id;
4255 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4256 $orig_id = $r[0]['dfrn-id'];
4257 $dfrn_id = '0:' . $orig_id;
4260 $sec = random_string();
4263 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4264 VALUES( %d, %s, '%s', '%s', %d )",
4272 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4273 $dest = (($url) ? '&destination_url=' . $url : '');
4275 $r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4276 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4277 . '&type=profile&sec=' . $sec . $dest . $quiet
4280 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4283 * @brief Return the item shared, if the item contains only the [share] tag
4285 * @param array $item Sharer item
4286 * @return array Shared item or false if not a reshare
4288 function api_share_as_retweet(&$item)
4290 $body = trim($item["body"]);
4292 if (Diaspora::isReshare($body, false)===false) {
4296 /// @TODO "$1" should maybe mean '$1' ?
4297 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4299 * Skip if there is no shared message in there
4300 * we already checked this in diaspora::isReshare()
4301 * but better one more than one less...
4303 if ($body == $attributes) {
4308 // build the fake reshared item
4309 $reshared_item = $item;
4312 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4313 if ($matches[1] != "") {
4314 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4317 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4318 if ($matches[1] != "") {
4319 $author = $matches[1];
4323 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4324 if ($matches[1] != "") {
4325 $profile = $matches[1];
4328 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4329 if ($matches[1] != "") {
4330 $profile = $matches[1];
4334 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4335 if ($matches[1] != "") {
4336 $avatar = $matches[1];
4339 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4340 if ($matches[1] != "") {
4341 $avatar = $matches[1];
4345 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4346 if ($matches[1] != "") {
4347 $link = $matches[1];
4350 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4351 if ($matches[1] != "") {
4352 $link = $matches[1];
4356 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4357 if ($matches[1] != "")
4358 $posted = $matches[1];
4360 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4361 if ($matches[1] != "") {
4362 $posted = $matches[1];
4365 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4367 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4371 $reshared_item["body"] = $shared_body;
4372 $reshared_item["author-name"] = $author;
4373 $reshared_item["author-link"] = $profile;
4374 $reshared_item["author-avatar"] = $avatar;
4375 $reshared_item["plink"] = $link;
4376 $reshared_item["created"] = $posted;
4377 $reshared_item["edited"] = $posted;
4379 return $reshared_item;
4383 function api_get_nick($profile)
4386 - remove trailing junk from profile url
4387 - pump.io check has to check the website
4393 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4394 dbesc(normalise_link($profile))
4397 if (DBM::is_result($r)) {
4398 $nick = $r[0]["nick"];
4403 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4404 dbesc(normalise_link($profile))
4407 if (DBM::is_result($r)) {
4408 $nick = $r[0]["nick"];
4413 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4414 if ($friendica != $profile) {
4420 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4421 if ($diaspora != $profile) {
4427 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4428 if ($twitter != $profile) {
4435 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4436 if ($StatusnetHost != $profile) {
4437 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4438 if ($StatusnetUser != $profile) {
4439 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4440 $user = json_decode($UserData);
4442 $nick = $user->screen_name;
4448 // To-Do: look at the page if its really a pumpio site
4449 //if (!$nick == "") {
4450 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4451 // if ($pumpio != $profile)
4453 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4464 function api_in_reply_to($item)
4466 $in_reply_to = array();
4468 $in_reply_to['status_id'] = null;
4469 $in_reply_to['user_id'] = null;
4470 $in_reply_to['status_id_str'] = null;
4471 $in_reply_to['user_id_str'] = null;
4472 $in_reply_to['screen_name'] = null;
4474 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4475 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4476 intval($item['uid']),
4477 dbesc($item['thr-parent']));
4479 if (DBM::is_result($r)) {
4480 $in_reply_to['status_id'] = intval($r[0]['id']);
4482 $in_reply_to['status_id'] = intval($item['parent']);
4485 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4487 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4488 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4489 WHERE `item`.`id` = %d LIMIT 1",
4490 intval($in_reply_to['status_id'])
4493 if (DBM::is_result($r)) {
4494 if ($r[0]['nick'] == "") {
4495 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4498 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4499 $in_reply_to['user_id'] = intval($r[0]['id']);
4500 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4503 // There seems to be situation, where both fields are identical:
4504 // https://github.com/friendica/friendica/issues/1010
4505 // This is a bugfix for that.
4506 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4507 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4508 $in_reply_to['status_id'] = null;
4509 $in_reply_to['user_id'] = null;
4510 $in_reply_to['status_id_str'] = null;
4511 $in_reply_to['user_id_str'] = null;
4512 $in_reply_to['screen_name'] = null;
4516 return $in_reply_to;
4519 function api_clean_plain_items($Text)
4521 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4523 $Text = bb_CleanPictureLinks($Text);
4524 $URLSearchString = "^\[\]";
4526 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
4528 if ($include_entities == "true") {
4529 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
4532 // Simplify "attachment" element
4533 $Text = api_clean_attachments($Text);
4539 * @brief Removes most sharing information for API text export
4541 * @param string $body The original body
4543 * @return string Cleaned body
4545 function api_clean_attachments($body)
4547 $data = get_attachment_data($body);
4554 if (isset($data["text"]))
4555 $body = $data["text"];
4557 if (($body == "") && (isset($data["title"])))
4558 $body = $data["title"];
4560 if (isset($data["url"]))
4561 $body .= "\n".$data["url"];
4563 $body .= $data["after"];
4568 function api_best_nickname(&$contacts)
4570 $best_contact = array();
4572 if (count($contact) == 0)
4575 foreach ($contacts as $contact)
4576 if ($contact["network"] == "") {
4577 $contact["network"] = "dfrn";
4578 $best_contact = array($contact);
4581 if (sizeof($best_contact) == 0)
4582 foreach ($contacts as $contact)
4583 if ($contact["network"] == "dfrn")
4584 $best_contact = array($contact);
4586 if (sizeof($best_contact) == 0)
4587 foreach ($contacts as $contact)
4588 if ($contact["network"] == "dspr")
4589 $best_contact = array($contact);
4591 if (sizeof($best_contact) == 0)
4592 foreach ($contacts as $contact)
4593 if ($contact["network"] == "stat")
4594 $best_contact = array($contact);
4596 if (sizeof($best_contact) == 0)
4597 foreach ($contacts as $contact)
4598 if ($contact["network"] == "pump")
4599 $best_contact = array($contact);
4601 if (sizeof($best_contact) == 0)
4602 foreach ($contacts as $contact)
4603 if ($contact["network"] == "twit")
4604 $best_contact = array($contact);
4606 if (sizeof($best_contact) == 1) {
4607 $contacts = $best_contact;
4609 $contacts = array($contacts[0]);
4613 // return all or a specified group of the user with the containing contacts
4614 function api_friendica_group_show($type)
4618 if (api_user() === false) throw new ForbiddenException();
4621 $user_info = api_get_user($a);
4622 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4623 $uid = $user_info['uid'];
4625 // get data of the specified group id or all groups if not specified
4628 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4632 // error message if specified gid is not in database
4633 if (!DBM::is_result($r))
4634 throw new BadRequestException("gid not available");
4637 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4642 // loop through all groups and retrieve all members for adding data in the user array
4643 foreach ($r as $rr) {
4644 $members = group_get_members($rr['id']);
4647 if ($type == "xml") {
4648 $user_element = "users";
4650 foreach ($members as $member) {
4651 $user = api_get_user($a, $member['nurl']);
4652 $users[$k++.":user"] = $user;
4655 $user_element = "user";
4656 foreach ($members as $member) {
4657 $user = api_get_user($a, $member['nurl']);
4661 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4663 return api_format_data("groups", $type, array('group' => $grps));
4665 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4668 // delete the specified group of the user
4669 function api_friendica_group_delete($type)
4673 if (api_user() === false) throw new ForbiddenException();
4676 $user_info = api_get_user($a);
4677 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4678 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4679 $uid = $user_info['uid'];
4681 // error if no gid specified
4682 if ($gid == 0 || $name == "")
4683 throw new BadRequestException('gid or name not specified');
4685 // get data of the specified group id
4687 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
4691 // error message if specified gid is not in database
4692 if (!DBM::is_result($r))
4693 throw new BadRequestException('gid not available');
4695 // get data of the specified group id and group name
4697 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
4702 // error message if specified gid is not in database
4703 if (!DBM::is_result($rname))
4704 throw new BadRequestException('wrong group name');
4707 $ret = group_rmv($uid, $name);
4710 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
4711 return api_format_data("group_delete", $type, array('result' => $success));
4713 throw new BadRequestException('other API error');
4716 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4719 // create the specified group with the posted array of contacts
4720 function api_friendica_group_create($type)
4724 if (api_user() === false) throw new ForbiddenException();
4727 $user_info = api_get_user($a);
4728 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4729 $uid = $user_info['uid'];
4730 $json = json_decode($_POST['json'], true);
4731 $users = $json['user'];
4733 // error if no name specified
4735 throw new BadRequestException('group name not specified');
4737 // get data of the specified group name
4739 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
4743 // error message if specified group name already exists
4744 if (DBM::is_result($rname))
4745 throw new BadRequestException('group name already exists');
4747 // check if specified group name is a deleted group
4749 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
4753 // error message if specified group name already exists
4754 if (DBM::is_result($rname))
4755 $reactivate_group = true;
4758 $ret = group_add($uid, $name);
4760 $gid = group_byname($uid, $name);
4762 throw new BadRequestException('other API error');
4766 $erroraddinguser = false;
4767 $errorusers = array();
4768 foreach ($users as $user) {
4769 $cid = $user['cid'];
4770 // check if user really exists as contact
4772 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4776 if (count($contact))
4777 $result = group_add_member($uid, $name, $cid, $gid);
4779 $erroraddinguser = true;
4780 $errorusers[] = $cid;
4784 // return success message incl. missing users in array
4785 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
4786 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4787 return api_format_data("group_create", $type, array('result' => $success));
4789 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4792 // update the specified group with the posted array of contacts
4793 function api_friendica_group_update($type)
4797 if (api_user() === false) throw new ForbiddenException();
4800 $user_info = api_get_user($a);
4801 $uid = $user_info['uid'];
4802 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4803 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4804 $json = json_decode($_POST['json'], true);
4805 $users = $json['user'];
4807 // error if no name specified
4809 throw new BadRequestException('group name not specified');
4811 // error if no gid specified
4813 throw new BadRequestException('gid not specified');
4816 $members = group_get_members($gid);
4817 foreach ($members as $member) {
4818 $cid = $member['id'];
4819 foreach ($users as $user) {
4820 $found = ($user['cid'] == $cid ? true : false);
4823 $ret = group_rmv_member($uid, $name, $cid);
4828 $erroraddinguser = false;
4829 $errorusers = array();
4830 foreach ($users as $user) {
4831 $cid = $user['cid'];
4832 // check if user really exists as contact
4834 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4839 if (count($contact)) {
4840 $result = group_add_member($uid, $name, $cid, $gid);
4842 $erroraddinguser = true;
4843 $errorusers[] = $cid;
4847 // return success message incl. missing users in array
4848 $status = ($erroraddinguser ? "missing user" : "ok");
4849 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4850 return api_format_data("group_update", $type, array('result' => $success));
4853 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4855 function api_friendica_activity($type)
4859 if (api_user() === false) throw new ForbiddenException();
4860 $verb = strtolower($a->argv[3]);
4861 $verb = preg_replace("|\..*$|", "", $verb);
4863 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4865 $res = do_like($id, $verb);
4868 if ($type == "xml") {
4873 return api_format_data('ok', $type, array('ok' => $ok));
4875 throw new BadRequestException('Error adding activity');
4879 /// @TODO move to top of file or somwhere better
4880 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
4881 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
4882 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
4883 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
4884 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4885 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
4886 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
4887 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
4888 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
4889 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4892 * @brief Returns notifications
4894 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4897 function api_friendica_notification($type)
4901 if (api_user() === false) throw new ForbiddenException();
4902 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
4903 $nm = new NotificationsManager();
4905 $notes = $nm->getAll(array(), "+seen -date", 50);
4907 if ($type == "xml") {
4908 $xmlnotes = array();
4909 foreach ($notes as $note)
4910 $xmlnotes[] = array("@attributes" => $note);
4915 return api_format_data("notes", $type, array('note' => $notes));
4919 * @brief Set notification as seen and returns associated item (if possible)
4921 * POST request with 'id' param as notification id
4923 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4926 function api_friendica_notification_seen($type)
4930 if (api_user() === false) throw new ForbiddenException();
4931 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
4933 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
4935 $nm = new NotificationsManager();
4936 $note = $nm->getByID($id);
4937 if (is_null($note)) throw new BadRequestException("Invalid argument");
4939 $nm->setSeen($note);
4940 if ($note['otype']=='item') {
4941 // would be really better with an ItemsManager and $im->getByID() :-P
4943 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
4944 intval($note['iid']),
4945 intval(local_user())
4948 // we found the item, return it to the user
4949 $user_info = api_get_user($a);
4950 $ret = api_format_items($r, $user_info, false, $type);
4951 $data = array('status' => $ret);
4952 return api_format_data("status", $type, $data);
4954 // the item can't be found, but we set the note as seen, so we count this as a success
4956 return api_format_data('result', $type, array('result' => "success"));
4959 /// @TODO move to top of file or somwhere better
4960 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4961 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
4964 * @brief update a direct_message to seen state
4966 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4967 * @return string (success result=ok, error result=error with error message)
4969 function api_friendica_direct_messages_setseen($type)
4972 if (api_user() === false) {
4973 throw new ForbiddenException();
4977 $user_info = api_get_user($a);
4978 $uid = $user_info['uid'];
4979 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4981 // return error if id is zero
4983 $answer = array('result' => 'error', 'message' => 'message id not specified');
4984 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4987 // get data of the specified message id
4989 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
4994 // error message if specified id is not in database
4995 if (!DBM::is_result($r)) {
4996 $answer = array('result' => 'error', 'message' => 'message id not in database');
4997 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5000 // update seen indicator
5002 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5009 $answer = array('result' => 'ok', 'message' => 'message set to seen');
5010 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
5012 $answer = array('result' => 'error', 'message' => 'unknown error');
5013 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5017 /// @TODO move to top of file or somwhere better
5018 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5021 * @brief search for direct_messages containing a searchstring through api
5023 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5024 * @return string (success: success=true if found and search_result contains found messages
5025 * success=false if nothing was found, search_result='nothing found',
5026 * error: result=error with error message)
5028 function api_friendica_direct_messages_search($type)
5032 if (api_user() === false) {
5033 throw new ForbiddenException();
5037 $user_info = api_get_user($a);
5038 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5039 $uid = $user_info['uid'];
5041 // error if no searchstring specified
5042 if ($searchstring == "") {
5043 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
5044 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
5047 // get data for the specified searchstring
5049 "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",
5051 dbesc('%'.$searchstring.'%')
5054 $profile_url = $user_info["url"];
5056 // message if nothing was found
5057 if (!DBM::is_result($r)) {
5058 $success = array('success' => false, 'search_results' => 'problem with query');
5059 } elseif (count($r) == 0) {
5060 $success = array('success' => false, 'search_results' => 'nothing found');
5063 foreach ($r as $item) {
5064 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5065 $recipient = $user_info;
5066 $sender = api_get_user($a, normalise_link($item['contact-url']));
5067 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5068 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5069 $sender = $user_info;
5072 $ret[] = api_format_messages($item, $recipient, $sender);
5074 $success = array('success' => true, 'search_results' => $ret);
5077 return api_format_data("direct_message_search", $type, array('$result' => $success));
5080 /// @TODO move to top of file or somwhere better
5081 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5084 * @brief return data of all the profiles a user has to the client
5086 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5089 function api_friendica_profile_show($type)
5093 if (api_user() === false) {
5094 throw new ForbiddenException();
5098 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5100 // retrieve general information about profiles for user
5101 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5102 $directory = Config::get('system', 'directory');
5104 // get data of the specified profile id or all profiles of the user if not specified
5105 if ($profileid != 0) {
5107 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5112 // error message if specified gid is not in database
5113 if (!DBM::is_result($r)) {
5114 throw new BadRequestException("profile_id not available");
5118 "SELECT * FROM `profile` WHERE `uid` = %d",
5122 // loop through all returned profiles and retrieve data and users
5124 foreach ($r as $rr) {
5125 $profile = api_format_items_profiles($rr, $type);
5127 // select all users from contact table, loop and prepare standard return for user data
5130 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5132 intval($rr['profile_id'])
5135 foreach ($r as $rr) {
5136 $user = api_get_user($a, $rr['nurl']);
5137 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5139 $profile['users'] = $users;
5141 // add prepared profile data to array for final return
5142 if ($type == "xml") {
5143 $profiles[$k++ . ":profile"] = $profile;
5145 $profiles[] = $profile;
5149 // return settings, authenticated user and profiles data
5150 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5152 $result = array('multi_profiles' => $multi_profiles ? true : false,
5153 'global_dir' => $directory,
5154 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5155 'profiles' => $profiles);
5156 return api_format_data("friendica_profiles", $type, array('$result' => $result));
5158 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5161 @TODO Maybe open to implement?
5163 [pagename] => api/1.1/statuses/lookup.json
5164 [id] => 605138389168451584
5165 [include_cards] => true
5166 [cards_platform] => Android-12
5167 [include_entities] => true
5168 [include_my_retweet] => 1
5170 [include_reply_count] => true
5171 [include_descendent_reply_count] => true
5175 Not implemented by now:
5176 statuses/retweets_of_me
5181 account/update_location
5182 account/update_profile_background_image
5185 friendica/profile/update
5186 friendica/profile/create
5187 friendica/profile/delete
5189 Not implemented in status.net:
5190 statuses/retweeted_to_me
5191 statuses/retweeted_by_me
5192 direct_messages/destroy
5194 account/update_delivery_device
5195 notifications/follow