3 * @file include/api.php
4 * Friendica implementation of statusnet/twitter API
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\Core\System;
11 use Friendica\Core\Config;
12 use Friendica\Core\NotificationsManager;
13 use Friendica\Core\Worker;
15 require_once 'include/HTTPExceptions.php';
16 require_once 'include/bbcode.php';
17 require_once 'include/datetime.php';
18 require_once 'include/conversation.php';
19 require_once 'include/oauth.php';
20 require_once 'include/html2plain.php';
21 require_once 'mod/share.php';
22 require_once 'include/Photo.php';
23 require_once 'mod/item.php';
24 require_once 'include/security.php';
25 require_once 'include/contact_selectors.php';
26 require_once 'include/html2bbcode.php';
27 require_once 'mod/wall_upload.php';
28 require_once 'mod/proxy.php';
29 require_once 'include/message.php';
30 require_once 'include/group.php';
31 require_once 'include/like.php';
32 require_once 'include/plaintext.php';
33 require_once 'include/xml.php';
35 define('API_METHOD_ANY', '*');
36 define('API_METHOD_GET', 'GET');
37 define('API_METHOD_POST', 'POST,PUT');
38 define('API_METHOD_DELETE', 'POST,DELETE');
43 /// @TODO Fix intending
45 * @brief Auth API user
47 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
48 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
49 * into a page, and visitors will post something without noticing it).
52 if (x($_SESSION, 'allow_api')) {
60 * @brief Get source name from API client
62 * Clients can send 'source' parameter to be show in post metadata
63 * as "sent via <source>".
64 * Some clients doesn't send a source param, we support ones we know
68 * Client source name, default to "api" if unset/unknown
70 function api_source() {
71 if (requestdata('source')) {
72 return requestdata('source');
75 // Support for known clients that doesn't send a source name
76 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
80 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
86 * @brief Format date for API
88 * @param string $str Source date, as UTC
89 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
91 function api_date($str) {
92 // Wed May 23 06:01:13 +0000 2007
93 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
97 * @brief Register API endpoint
99 * Register a function to be the endpont for defined API path.
101 * @param string $path API URL path, relative to System::baseUrl()
102 * @param string $func Function name to call on path request
103 * @param bool $auth API need logged user
104 * @param string $method HTTP method reqiured to call this endpoint.
106 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
107 * Default to API_METHOD_ANY
109 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY) {
118 // Workaround for hotot
119 $path = str_replace("api/", "api/1.1/", $path);
129 * @brief Login API user
131 * Log in user via OAuth1 or Simple HTTP Auth.
132 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
135 * @hook 'authenticate'
137 * 'username' => username from login form
138 * 'password' => password from login form
139 * 'authenticated' => return status,
140 * 'user_record' => return authenticated user record
142 * array $user logged user record
144 function api_login(App $a) {
147 $oauth = new FKOAuth1();
148 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
149 if (!is_null($token)) {
150 $oauth->loginUser($token->uid);
151 call_hooks('logged_in', $a->user);
154 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
155 var_dump($consumer, $token);
157 } catch (Exception $e) {
161 // workaround for HTTP-auth in CGI mode
162 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
163 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
164 if (strlen($userpass)) {
165 list($name, $password) = explode(':', $userpass);
166 $_SERVER['PHP_AUTH_USER'] = $name;
167 $_SERVER['PHP_AUTH_PW'] = $password;
171 if (!x($_SERVER, 'PHP_AUTH_USER')) {
172 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
173 header('WWW-Authenticate: Basic realm="Friendica"');
174 throw new UnauthorizedException("This API requires login");
177 $user = $_SERVER['PHP_AUTH_USER'];
178 $password = $_SERVER['PHP_AUTH_PW'];
179 $encrypted = hash('whirlpool', trim($password));
181 // allow "user@server" login (but ignore 'server' part)
182 $at = strstr($user, "@", true);
187 // next code from mod/auth.php. needs better solution
191 'username' => trim($user),
192 'password' => trim($password),
193 'authenticated' => 0,
194 'user_record' => null,
198 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
199 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
200 * and later plugins should not interfere with an earlier one that succeeded.
202 call_hooks('authenticate', $addon_auth);
204 if (($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
205 $record = $addon_auth['user_record'];
207 // process normal login request
208 $r = q("SELECT * FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')
209 AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
214 if (dbm::is_result($r)) {
219 if ((! $record) || (! count($record))) {
220 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
221 header('WWW-Authenticate: Basic realm="Friendica"');
222 //header('HTTP/1.0 401 Unauthorized');
223 //die('This api requires login');
224 throw new UnauthorizedException("This API requires login");
227 authenticate_success($record);
229 $_SESSION["allow_api"] = true;
231 call_hooks('logged_in', $a->user);
236 * @brief Check HTTP method of called API
238 * API endpoints can define which HTTP method to accept when called.
239 * This function check the current HTTP method agains endpoint
242 * @param string $method Required methods, uppercase, separated by comma
245 function api_check_method($method) {
246 if ($method == "*") {
249 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
253 * @brief Main API entry point
255 * Authenticate user, call registered API function, set HTTP headers
258 * @return string API call result
260 function api_call(App $a) {
261 global $API, $called_api;
264 if (strpos($a->query_string, ".xml") > 0) {
267 if (strpos($a->query_string, ".json") > 0) {
270 if (strpos($a->query_string, ".rss") > 0) {
273 if (strpos($a->query_string, ".atom") > 0) {
278 foreach ($API as $p => $info) {
279 if (strpos($a->query_string, $p) === 0) {
280 if (!api_check_method($info['method'])) {
281 throw new MethodNotAllowedException();
284 $called_api = explode("/", $p);
285 //unset($_SERVER['PHP_AUTH_USER']);
287 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
288 if ($info['auth'] === true && api_user() === false) {
292 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
293 logger('API parameters: ' . print_r($_REQUEST, true));
295 $stamp = microtime(true);
296 $r = call_user_func($info['func'], $type);
297 $duration = (float) (microtime(true) - $stamp);
298 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
300 if (Config::get("system", "profiler")) {
301 $duration = microtime(true)-$a->performance["start"];
303 /// @TODO round() really everywhere?
304 logger(parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf("Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
305 round($a->performance["database"] - $a->performance["database_write"], 3),
306 round($a->performance["database_write"], 3),
307 round($a->performance["network"], 2),
308 round($a->performance["file"], 2),
309 round($duration - ($a->performance["database"] + $a->performance["network"]
310 + $a->performance["file"]), 2),
311 round($duration, 2)),
315 if (Config::get("rendertime", "callstack")) {
316 $o = "Database Read:\n";
317 foreach ($a->callstack["database"] AS $func => $time) {
318 $time = round($time, 3);
320 $o .= $func . ": " . $time . "\n";
323 $o .= "\nDatabase Write:\n";
324 foreach ($a->callstack["database_write"] AS $func => $time) {
325 $time = round($time, 3);
327 $o .= $func . ": " . $time . "\n";
331 $o .= "\nNetwork:\n";
332 foreach ($a->callstack["network"] AS $func => $time) {
333 $time = round($time, 3);
335 $o .= $func . ": " . $time . "\n";
338 logger($o, LOGGER_DEBUG);
344 * api function returned false withour throw an
345 * exception. This should not happend, throw a 500
347 throw new InternalServerErrorException();
352 header ("Content-Type: text/xml");
356 header ("Content-Type: application/json");
358 $json = json_encode($rr);
359 if (x($_GET, 'callback')) {
360 $json = $_GET['callback'] . "(" . $json . ")";
365 header ("Content-Type: application/rss+xml");
366 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
369 header ("Content-Type: application/atom+xml");
370 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
376 logger('API call not implemented: ' . $a->query_string);
377 throw new NotImplementedException();
378 } catch (HTTPException $e) {
379 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
380 return api_error($type, $e);
385 * @brief Format API error string
387 * @param string $type Return type (xml, json, rss, as)
388 * @param HTTPException $error Error object
389 * @return strin error message formatted as $type
391 function api_error($type, $e) {
395 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
396 /// @TODO: https://dev.twitter.com/overview/api/response-codes
398 $error = array("error" => $error,
399 "code" => $e->httpcode . " " . $e->httpdesc,
400 "request" => $a->query_string);
402 $ret = api_format_data('status', $type, array('status' => $error));
406 header ("Content-Type: text/xml");
410 header ("Content-Type: application/json");
411 return json_encode($ret);
414 header ("Content-Type: application/rss+xml");
418 header ("Content-Type: application/atom+xml");
425 * @brief Set values for RSS template
428 * @param array $arr Array to be passed to template
429 * @param array $user_info
431 * @todo find proper type-hints
433 function api_rss_extra(App $a, $arr, $user_info) {
434 if (is_null($user_info)) {
435 $user_info = api_get_user($a);
438 $arr['$user'] = $user_info;
439 $arr['$rss'] = array(
440 'alternate' => $user_info['url'],
441 'self' => System::baseUrl() . "/" . $a->query_string,
442 'base' => System::baseUrl(),
443 'updated' => api_date(null),
444 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
445 'language' => $user_info['language'],
446 'logo' => System::baseUrl() . "/images/friendica-32.png",
454 * @brief Unique contact to contact url.
456 * @param int $id Contact id
457 * @return bool|string
458 * Contact url or False if contact id is unknown
460 function api_unique_id_to_url($id) {
461 $r = dba::select('contact', array('url'), array('uid' => 0, 'id' => $id), array('limit' => 1));
463 if (dbm::is_result($r)) {
471 * @brief Get user info array.
474 * @param int|string $contact_id Contact ID or URL
475 * @param string $type Return type (for errors)
477 function api_get_user(App $a, $contact_id = null, $type = "json") {
485 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
487 // Searching for contact URL
488 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
489 $user = dbesc(normalise_link($contact_id));
491 $extra_query = "AND `contact`.`nurl` = '%s' ";
492 if (api_user() !== false) {
493 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
497 // Searching for contact id with uid = 0
498 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
499 $user = dbesc(api_unique_id_to_url($contact_id));
502 throw new BadRequestException("User not found.");
506 $extra_query = "AND `contact`.`nurl` = '%s' ";
507 if (api_user() !== false) {
508 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
512 if (is_null($user) && x($_GET, 'user_id')) {
513 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
516 throw new BadRequestException("User not found.");
520 $extra_query = "AND `contact`.`nurl` = '%s' ";
521 if (api_user() !== false) {
522 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
525 if (is_null($user) && x($_GET, 'screen_name')) {
526 $user = dbesc($_GET['screen_name']);
528 $extra_query = "AND `contact`.`nick` = '%s' ";
529 if (api_user() !== false) {
530 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
534 if (is_null($user) && x($_GET, 'profileurl')) {
535 $user = dbesc(normalise_link($_GET['profileurl']));
537 $extra_query = "AND `contact`.`nurl` = '%s' ";
538 if (api_user() !== false) {
539 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
543 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
544 $argid = count($called_api);
545 list($user, $null) = explode(".", $a->argv[$argid]);
546 if (is_numeric($user)) {
547 $user = dbesc(api_unique_id_to_url($user));
554 $extra_query = "AND `contact`.`nurl` = '%s' ";
555 if (api_user() !== false) {
556 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
559 $user = dbesc($user);
561 $extra_query = "AND `contact`.`nick` = '%s' ";
562 if (api_user() !== false) {
563 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
568 logger("api_get_user: user ".$user, LOGGER_DEBUG);
571 if (api_user() === false) {
575 $user = $_SESSION['uid'];
576 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
581 logger('api_user: ' . $extra_query . ', user: ' . $user);
584 $uinfo = q("SELECT *, `contact`.`id` AS `cid` FROM `contact`
590 // Selecting the id by priority, friendica first
591 api_best_nickname($uinfo);
593 // if the contact wasn't found, fetch it from the contacts with uid = 0
594 if (!dbm::is_result($uinfo)) {
598 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
601 if (dbm::is_result($r)) {
602 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
604 // If no nick where given, extract it from the address
605 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
606 $r[0]['nick'] = api_get_nick($r[0]["url"]);
611 'id_str' => (string) $r[0]["id"],
612 'name' => $r[0]["name"],
613 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
614 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
615 'description' => $r[0]["about"],
616 'profile_image_url' => $r[0]["micro"],
617 'profile_image_url_https' => $r[0]["micro"],
618 'url' => $r[0]["url"],
619 'protected' => false,
620 'followers_count' => 0,
621 'friends_count' => 0,
623 'created_at' => api_date($r[0]["created"]),
624 'favourites_count' => 0,
626 'time_zone' => 'UTC',
627 'geo_enabled' => false,
629 'statuses_count' => 0,
631 'contributors_enabled' => false,
632 'is_translator' => false,
633 'is_translation_enabled' => false,
634 'following' => false,
635 'follow_request_sent' => false,
636 'statusnet_blocking' => false,
637 'notifications' => false,
638 'statusnet_profile_url' => $r[0]["url"],
640 'cid' => get_contact($r[0]["url"], api_user(), true),
642 'network' => $r[0]["network"],
647 throw new BadRequestException("User not found.");
651 if ($uinfo[0]['self']) {
653 if ($uinfo[0]['network'] == "") {
654 $uinfo[0]['network'] = NETWORK_DFRN;
657 $usr = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
660 $profile = q("SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
664 /// @TODO old-lost code? (twice)
665 // Counting is deactivated by now, due to performance issues
666 // count public wall messages
667 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
668 // intval($uinfo[0]['uid'])
670 //$countitms = $r[0]['count'];
673 // Counting is deactivated by now, due to performance issues
674 //$r = q("SELECT count(*) as `count` FROM `item`
675 // WHERE `contact-id` = %d",
676 // intval($uinfo[0]['id'])
678 //$countitms = $r[0]['count'];
682 /// @TODO old-lost code? (twice)
684 // Counting is deactivated by now, due to performance issues
686 $r = q("SELECT count(*) as `count` FROM `contact`
687 WHERE `uid` = %d AND `rel` IN ( %d, %d )
688 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
689 intval($uinfo[0]['uid']),
690 intval(CONTACT_IS_SHARING),
691 intval(CONTACT_IS_FRIEND)
693 $countfriends = $r[0]['count'];
695 $r = q("SELECT count(*) as `count` FROM `contact`
696 WHERE `uid` = %d AND `rel` IN ( %d, %d )
697 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
698 intval($uinfo[0]['uid']),
699 intval(CONTACT_IS_FOLLOWER),
700 intval(CONTACT_IS_FRIEND)
702 $countfollowers = $r[0]['count'];
704 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
705 intval($uinfo[0]['uid'])
707 $starred = $r[0]['count'];
710 if (! $uinfo[0]['self']) {
720 // Add a nick if it isn't present there
721 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
722 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
725 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
727 $pcontact_id = get_contact($uinfo[0]['url'], 0, true);
730 'id' => intval($pcontact_id),
731 'id_str' => (string) intval($pcontact_id),
732 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
733 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
734 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
735 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
736 'profile_image_url' => $uinfo[0]['micro'],
737 'profile_image_url_https' => $uinfo[0]['micro'],
738 'url' => $uinfo[0]['url'],
739 'protected' => false,
740 'followers_count' => intval($countfollowers),
741 'friends_count' => intval($countfriends),
743 'created_at' => api_date($uinfo[0]['created']),
744 'favourites_count' => intval($starred),
746 'time_zone' => 'UTC',
747 'geo_enabled' => false,
749 'statuses_count' => intval($countitms),
751 'contributors_enabled' => false,
752 'is_translator' => false,
753 'is_translation_enabled' => false,
754 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
755 'follow_request_sent' => false,
756 'statusnet_blocking' => false,
757 'notifications' => false,
759 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
760 'statusnet_profile_url' => $uinfo[0]['url'],
761 'uid' => intval($uinfo[0]['uid']),
762 'cid' => intval($uinfo[0]['cid']),
763 'self' => $uinfo[0]['self'],
764 'network' => $uinfo[0]['network'],
772 * @brief return api-formatted array for item's author and owner
775 * @param array $item : item from db
776 * @return array(array:author, array:owner)
778 function api_item_get_user(App $a, $item) {
780 $status_user = api_get_user($a, $item["author-link"]);
782 $status_user["protected"] = (($item["allow_cid"] != "") ||
783 ($item["allow_gid"] != "") ||
784 ($item["deny_cid"] != "") ||
785 ($item["deny_gid"] != "") ||
788 if ($item['thr-parent'] == $item['uri']) {
789 $owner_user = api_get_user($a, $item["owner-link"]);
791 $owner_user = $status_user;
794 return (array($status_user, $owner_user));
798 * @brief walks recursively through an array with the possibility to change value and key
800 * @param array $array The array to walk through
801 * @param string $callback The callback function
803 * @return array the transformed array
805 function api_walk_recursive(array &$array, callable $callback) {
807 $new_array = array();
809 foreach ($array as $k => $v) {
811 if ($callback($v, $k)) {
812 $new_array[$k] = api_walk_recursive($v, $callback);
815 if ($callback($v, $k)) {
826 * @brief Callback function to transform the array in an array that can be transformed in a XML file
828 * @param variant $item Array item value
829 * @param string $key Array key
831 * @return boolean Should the array item be deleted?
833 function api_reformat_xml(&$item, &$key) {
834 if (is_bool($item)) {
835 $item = ($item ? "true" : "false");
838 if (substr($key, 0, 10) == "statusnet_") {
839 $key = "statusnet:".substr($key, 10);
840 } elseif (substr($key, 0, 10) == "friendica_") {
841 $key = "friendica:".substr($key, 10);
843 /// @TODO old-lost code?
845 // $key = "default:".$key;
851 * @brief Creates the XML from a JSON style array
853 * @param array $data JSON style array
854 * @param string $root_element Name of the root element
856 * @return string The XML data
858 function api_create_xml($data, $root_element) {
859 $childname = key($data);
860 $data2 = array_pop($data);
863 $namespaces = array("" => "http://api.twitter.com",
864 "statusnet" => "http://status.net/schema/api/1/",
865 "friendica" => "http://friendi.ca/schema/api/1/",
866 "georss" => "http://www.georss.org/georss");
868 /// @todo Auto detection of needed namespaces
869 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
870 $namespaces = array();
873 if (is_array($data2)) {
874 api_walk_recursive($data2, "api_reformat_xml");
881 foreach ($data2 AS $item) {
882 $data4[$i++.":".$childname] = $item;
888 $data3 = array($root_element => $data2);
890 $ret = xml::from_array($data3, $xml, false, $namespaces);
895 * @brief Formats the data according to the data type
897 * @param string $root_element Name of the root element
898 * @param string $type Return type (atom, rss, xml, json)
899 * @param array $data JSON style array
901 * @return (string|object) XML data or JSON data
903 function api_format_data($root_element, $type, $data) {
911 $ret = api_create_xml($data, $root_element);
926 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
927 * returns a 401 status code and an error message if not.
928 * http://developer.twitter.com/doc/get/account/verify_credentials
930 function api_account_verify_credentials($type) {
934 if (api_user() === false) {
935 throw new ForbiddenException();
938 unset($_REQUEST["user_id"]);
939 unset($_GET["user_id"]);
941 unset($_REQUEST["screen_name"]);
942 unset($_GET["screen_name"]);
944 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
946 $user_info = api_get_user($a);
948 // "verified" isn't used here in the standard
949 unset($user_info["verified"]);
951 // - Adding last status
953 $user_info["status"] = api_status_show("raw");
954 if (!count($user_info["status"])) {
955 unset($user_info["status"]);
957 unset($user_info["status"]["user"]);
961 // "uid" and "self" are only needed for some internal stuff, so remove it from here
962 unset($user_info["uid"]);
963 unset($user_info["self"]);
965 return api_format_data("user", $type, array('user' => $user_info));
969 /// @TODO move to top of file or somwhere better
970 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
973 * get data from $_POST or $_GET
975 function requestdata($k) {
985 /*Waitman Gobble Mod*/
986 function api_statuses_mediap($type) {
990 if (api_user() === false) {
991 logger('api_statuses_update: no user');
992 throw new ForbiddenException();
994 $user_info = api_get_user($a);
996 $_REQUEST['type'] = 'wall';
997 $_REQUEST['profile_uid'] = api_user();
998 $_REQUEST['api_source'] = true;
999 $txt = requestdata('status');
1000 /// @TODO old-lost code?
1001 //$txt = urldecode(requestdata('status'));
1003 if ((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
1005 $txt = html2bb_video($txt);
1006 $config = HTMLPurifier_Config::createDefault();
1007 $config->set('Cache.DefinitionImpl', null);
1008 $purifier = new HTMLPurifier($config);
1009 $txt = $purifier->purify($txt);
1011 $txt = html2bbcode($txt);
1013 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1015 // tell wall_upload function to return img info instead of echo
1016 $_REQUEST['hush'] = 'yeah';
1017 $bebop = wall_upload_post($a);
1019 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1020 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1023 // this should output the last post (the one we just posted).
1024 return api_status_show($type);
1027 /// @TODO move this to top of file or somewhere better!
1028 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
1030 function api_statuses_update($type) {
1034 if (api_user() === false) {
1035 logger('api_statuses_update: no user');
1036 throw new ForbiddenException();
1039 $user_info = api_get_user($a);
1041 // convert $_POST array items to the form we use for web posts.
1043 // logger('api_post: ' . print_r($_POST,true));
1045 if (requestdata('htmlstatus')) {
1046 $txt = requestdata('htmlstatus');
1047 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1048 $txt = html2bb_video($txt);
1050 $config = HTMLPurifier_Config::createDefault();
1051 $config->set('Cache.DefinitionImpl', null);
1053 $purifier = new HTMLPurifier($config);
1054 $txt = $purifier->purify($txt);
1056 $_REQUEST['body'] = html2bbcode($txt);
1060 $_REQUEST['body'] = requestdata('status');
1063 $_REQUEST['title'] = requestdata('title');
1065 $parent = requestdata('in_reply_to_status_id');
1067 // Twidere sends "-1" if it is no reply ...
1068 if ($parent == -1) {
1072 if (ctype_digit($parent)) {
1073 $_REQUEST['parent'] = $parent;
1075 $_REQUEST['parent_uri'] = $parent;
1078 if (requestdata('lat') && requestdata('long')) {
1079 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1081 $_REQUEST['profile_uid'] = api_user();
1084 $_REQUEST['type'] = 'net-comment';
1086 // Check for throttling (maximum posts per day, week and month)
1087 $throttle_day = Config::get('system','throttle_limit_day');
1088 if ($throttle_day > 0) {
1089 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1091 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1092 AND `created` > '%s' AND `id` = `parent`",
1093 intval(api_user()), dbesc($datefrom));
1095 if (dbm::is_result($r)) {
1096 $posts_day = $r[0]["posts_day"];
1101 if ($posts_day > $throttle_day) {
1102 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1103 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1104 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1108 $throttle_week = Config::get('system','throttle_limit_week');
1109 if ($throttle_week > 0) {
1110 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1112 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1113 AND `created` > '%s' AND `id` = `parent`",
1114 intval(api_user()), dbesc($datefrom));
1116 if (dbm::is_result($r)) {
1117 $posts_week = $r[0]["posts_week"];
1122 if ($posts_week > $throttle_week) {
1123 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1124 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1125 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1129 $throttle_month = Config::get('system','throttle_limit_month');
1130 if ($throttle_month > 0) {
1131 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1133 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1134 AND `created` > '%s' AND `id` = `parent`",
1135 intval(api_user()), dbesc($datefrom));
1137 if (dbm::is_result($r)) {
1138 $posts_month = $r[0]["posts_month"];
1143 if ($posts_month > $throttle_month) {
1144 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1145 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1146 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1150 $_REQUEST['type'] = 'wall';
1153 if (x($_FILES, 'media')) {
1154 // upload the image if we have one
1155 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1156 $media = wall_upload_post($a);
1157 if (strlen($media) > 0) {
1158 $_REQUEST['body'] .= "\n\n" . $media;
1162 // To-Do: Multiple IDs
1163 if (requestdata('media_ids')) {
1164 $r = q("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",
1165 intval(requestdata('media_ids')), api_user());
1166 if (dbm::is_result($r)) {
1167 $phototypes = Photo::supportedTypes();
1168 $ext = $phototypes[$r[0]['type']];
1169 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1170 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1174 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1176 $_REQUEST['api_source'] = true;
1178 if (!x($_REQUEST, "source")) {
1179 $_REQUEST["source"] = api_source();
1182 // call out normal post function
1185 // this should output the last post (the one we just posted).
1186 return api_status_show($type);
1189 /// @TODO move to top of file or somwhere better
1190 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
1191 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
1193 function api_media_upload($type) {
1197 if (api_user() === false) {
1199 throw new ForbiddenException();
1202 $user_info = api_get_user($a);
1204 if (!x($_FILES, 'media')) {
1206 throw new BadRequestException("No media.");
1209 $media = wall_upload_post($a, false);
1212 throw new InternalServerErrorException();
1215 $returndata = array();
1216 $returndata["media_id"] = $media["id"];
1217 $returndata["media_id_string"] = (string)$media["id"];
1218 $returndata["size"] = $media["size"];
1219 $returndata["image"] = array("w" => $media["width"],
1220 "h" => $media["height"],
1221 "image_type" => $media["type"]);
1223 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1225 return array("media" => $returndata);
1228 /// @TODO move to top of file or somwhere better
1229 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1231 function api_status_show($type) {
1235 $user_info = api_get_user($a);
1237 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1239 if ($type == "raw") {
1240 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1245 // get last public wall message
1246 $lastwall = q("SELECT `item`.*
1248 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1249 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1250 AND `item`.`type` != 'activity' $privacy_sql
1251 ORDER BY `item`.`id` DESC
1253 intval($user_info['cid']),
1255 dbesc($user_info['url']),
1256 dbesc(normalise_link($user_info['url'])),
1257 dbesc($user_info['url']),
1258 dbesc(normalise_link($user_info['url']))
1261 if (dbm::is_result($lastwall)) {
1262 $lastwall = $lastwall[0];
1264 $in_reply_to = api_in_reply_to($lastwall);
1266 $converted = api_convert_item($lastwall);
1268 if ($type == "xml") {
1269 $geo = "georss:point";
1274 $status_info = array(
1275 'created_at' => api_date($lastwall['created']),
1276 'id' => intval($lastwall['id']),
1277 'id_str' => (string) $lastwall['id'],
1278 'text' => $converted["text"],
1279 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1280 'truncated' => false,
1281 'in_reply_to_status_id' => $in_reply_to['status_id'],
1282 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1283 'in_reply_to_user_id' => $in_reply_to['user_id'],
1284 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1285 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1286 'user' => $user_info,
1288 'coordinates' => "",
1290 'contributors' => "",
1291 'is_quote_status' => false,
1292 'retweet_count' => 0,
1293 'favorite_count' => 0,
1294 'favorited' => $lastwall['starred'] ? true : false,
1295 'retweeted' => false,
1296 'possibly_sensitive' => false,
1298 'statusnet_html' => $converted["html"],
1299 'statusnet_conversation_id' => $lastwall['parent'],
1302 if (count($converted["attachments"]) > 0) {
1303 $status_info["attachments"] = $converted["attachments"];
1306 if (count($converted["entities"]) > 0) {
1307 $status_info["entities"] = $converted["entities"];
1310 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1311 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1312 } elseif (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1313 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1316 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1317 unset($status_info["user"]["uid"]);
1318 unset($status_info["user"]["self"]);
1321 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1323 if ($type == "raw") {
1324 return $status_info;
1327 return api_format_data("statuses", $type, array('status' => $status_info));
1332 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1333 * The author's most recent status will be returned inline.
1334 * http://developer.twitter.com/doc/get/users/show
1336 function api_users_show($type) {
1340 $user_info = api_get_user($a);
1341 $lastwall = q("SELECT `item`.*
1343 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1344 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1345 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1346 AND `type`!='activity'
1347 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1351 dbesc(ACTIVITY_POST),
1352 intval($user_info['cid']),
1353 dbesc($user_info['url']),
1354 dbesc(normalise_link($user_info['url'])),
1355 dbesc($user_info['url']),
1356 dbesc(normalise_link($user_info['url']))
1359 if (dbm::is_result($lastwall)) {
1360 $lastwall = $lastwall[0];
1362 $in_reply_to = api_in_reply_to($lastwall);
1364 $converted = api_convert_item($lastwall);
1366 if ($type == "xml") {
1367 $geo = "georss:point";
1372 $user_info['status'] = array(
1373 'text' => $converted["text"],
1374 'truncated' => false,
1375 'created_at' => api_date($lastwall['created']),
1376 'in_reply_to_status_id' => $in_reply_to['status_id'],
1377 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1378 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1379 'id' => intval($lastwall['contact-id']),
1380 'id_str' => (string) $lastwall['contact-id'],
1381 'in_reply_to_user_id' => $in_reply_to['user_id'],
1382 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1383 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1385 'favorited' => $lastwall['starred'] ? true : false,
1386 'statusnet_html' => $converted["html"],
1387 'statusnet_conversation_id' => $lastwall['parent'],
1390 if (count($converted["attachments"]) > 0) {
1391 $user_info["status"]["attachments"] = $converted["attachments"];
1394 if (count($converted["entities"]) > 0) {
1395 $user_info["status"]["entities"] = $converted["entities"];
1398 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1399 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1402 if (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1403 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
1408 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1409 unset($user_info["uid"]);
1410 unset($user_info["self"]);
1412 return api_format_data("user", $type, array('user' => $user_info));
1416 /// @TODO move to top of file or somewhere better
1417 api_register_func('api/users/show','api_users_show');
1418 api_register_func('api/externalprofile/show','api_users_show');
1420 function api_users_search($type) {
1424 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1426 $userlist = array();
1428 if (x($_GET, 'q')) {
1429 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1431 if (!dbm::is_result($r)) {
1432 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1435 if (dbm::is_result($r)) {
1437 foreach ($r AS $user) {
1438 $user_info = api_get_user($a, $user["id"], "json");
1440 if ($type == "xml") {
1441 $userlist[$k++.":user"] = $user_info;
1443 $userlist[] = $user_info;
1446 $userlist = array("users" => $userlist);
1448 throw new BadRequestException("User not found.");
1451 throw new BadRequestException("User not found.");
1453 return api_format_data("users", $type, $userlist);
1456 /// @TODO move to top of file or somewhere better
1457 api_register_func('api/users/search','api_users_search');
1461 * http://developer.twitter.com/doc/get/statuses/home_timeline
1463 * TODO: Optional parameters
1464 * TODO: Add reply info
1466 function api_statuses_home_timeline($type) {
1470 if (api_user() === false) {
1471 throw new ForbiddenException();
1474 unset($_REQUEST["user_id"]);
1475 unset($_GET["user_id"]);
1477 unset($_REQUEST["screen_name"]);
1478 unset($_GET["screen_name"]);
1480 $user_info = api_get_user($a);
1481 // get last newtork messages
1484 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1485 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1489 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1490 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1491 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1492 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1493 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1495 $start = $page * $count;
1499 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1501 if ($exclude_replies > 0) {
1502 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1504 if ($conversation_id > 0) {
1505 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1508 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1509 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1510 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1511 `contact`.`id` AS `cid`
1513 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1514 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1515 WHERE `item`.`uid` = %d AND `verb` = '%s'
1516 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1519 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1521 dbesc(ACTIVITY_POST),
1523 intval($start), intval($count)
1526 $ret = api_format_items($r, $user_info, false, $type);
1528 // Set all posts from the query above to seen
1530 foreach ($r AS $item) {
1531 $idarray[] = intval($item["id"]);
1534 $idlist = implode(",", $idarray);
1536 if ($idlist != "") {
1537 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1540 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1544 $data = array('status' => $ret);
1548 $data = api_rss_extra($a, $data, $user_info);
1552 return api_format_data("statuses", $type, $data);
1555 /// @TODO move to top of file or somewhere better
1556 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1557 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1559 function api_statuses_public_timeline($type) {
1563 if (api_user() === false) {
1564 throw new ForbiddenException();
1567 $user_info = api_get_user($a);
1568 // get last newtork messages
1571 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1572 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1576 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1577 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1578 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1579 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1580 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1582 $start = $page * $count;
1585 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1587 if ($exclude_replies > 0) {
1588 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1590 if ($conversation_id > 0) {
1591 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1594 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1595 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1596 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1597 `contact`.`id` AS `cid`,
1598 `user`.`nickname`, `user`.`hidewall`
1600 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1601 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1602 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1603 AND NOT `user`.`hidewall`
1604 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1605 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1606 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1607 AND NOT `item`.`private` AND `item`.`wall`
1610 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1611 dbesc(ACTIVITY_POST),
1616 $ret = api_format_items($r, $user_info, false, $type);
1618 $data = array('status' => $ret);
1622 $data = api_rss_extra($a, $data, $user_info);
1626 return api_format_data("statuses", $type, $data);
1629 /// @TODO move to top of file or somewhere better
1630 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1633 * @TODO nothing to say?
1635 function api_statuses_show($type) {
1639 if (api_user() === false) {
1640 throw new ForbiddenException();
1643 $user_info = api_get_user($a);
1646 $id = intval($a->argv[3]);
1649 $id = intval($_REQUEST["id"]);
1654 $id = intval($a->argv[4]);
1657 logger('API: api_statuses_show: ' . $id);
1659 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1662 if ($conversation) {
1663 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1665 $sql_extra .= " AND `item`.`id` = %d";
1668 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1669 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1670 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1671 `contact`.`id` AS `cid`
1673 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1674 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1675 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1676 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1679 dbesc(ACTIVITY_POST),
1683 /// @TODO How about copying this to above methods which don't check $r ?
1684 if (!dbm::is_result($r)) {
1685 throw new BadRequestException("There is no status with this id.");
1688 $ret = api_format_items($r,$user_info, false, $type);
1690 if ($conversation) {
1691 $data = array('status' => $ret);
1692 return api_format_data("statuses", $type, $data);
1694 $data = array('status' => $ret[0]);
1695 return api_format_data("status", $type, $data);
1699 /// @TODO move to top of file or somewhere better
1700 api_register_func('api/statuses/show','api_statuses_show', true);
1703 * @TODO nothing to say?
1705 function api_conversation_show($type) {
1709 if (api_user() === false) {
1710 throw new ForbiddenException();
1713 $user_info = api_get_user($a);
1716 $id = intval($a->argv[3]);
1717 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1718 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1722 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1723 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1725 $start = $page*$count;
1728 $id = intval($_REQUEST["id"]);
1733 $id = intval($a->argv[4]);
1736 logger('API: api_conversation_show: '.$id);
1738 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1739 if (dbm::is_result($r)) {
1740 $id = $r[0]["parent"];
1746 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1749 // Not sure why this query was so complicated. We should keep it here for a while,
1750 // just to make sure that we really don't need it.
1751 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1752 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1754 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1755 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1756 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1757 `contact`.`id` AS `cid`
1759 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1760 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1761 WHERE `item`.`parent` = %d AND `item`.`visible`
1762 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1763 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1764 AND `item`.`id`>%d $sql_extra
1765 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1766 intval($id), intval(api_user()),
1767 dbesc(ACTIVITY_POST),
1769 intval($start), intval($count)
1772 if (!dbm::is_result($r)) {
1773 throw new BadRequestException("There is no status with this id.");
1776 $ret = api_format_items($r, $user_info, false, $type);
1778 $data = array('status' => $ret);
1779 return api_format_data("statuses", $type, $data);
1782 /// @TODO move to top of file or somewhere better
1783 api_register_func('api/conversation/show','api_conversation_show', true);
1784 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1787 * @TODO nothing to say?
1789 function api_statuses_repeat($type) {
1794 if (api_user() === false) {
1795 throw new ForbiddenException();
1798 $user_info = api_get_user($a);
1801 $id = intval($a->argv[3]);
1804 $id = intval($_REQUEST["id"]);
1809 $id = intval($a->argv[4]);
1812 logger('API: api_statuses_repeat: '.$id);
1814 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1815 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1816 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1817 `contact`.`id` AS `cid`
1819 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1820 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1821 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1822 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1823 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1825 AND `item`.`id`=%d",
1829 /// @TODO other style than above functions!
1830 if (dbm::is_result($r) && $r[0]['body'] != "") {
1831 if (strpos($r[0]['body'], "[/share]") !== false) {
1832 $pos = strpos($r[0]['body'], "[share");
1833 $post = substr($r[0]['body'], $pos);
1835 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1837 $post .= $r[0]['body'];
1838 $post .= "[/share]";
1840 $_REQUEST['body'] = $post;
1841 $_REQUEST['profile_uid'] = api_user();
1842 $_REQUEST['type'] = 'wall';
1843 $_REQUEST['api_source'] = true;
1845 if (!x($_REQUEST, "source")) {
1846 $_REQUEST["source"] = api_source();
1851 throw new ForbiddenException();
1854 // this should output the last post (the one we just posted).
1856 return api_status_show($type);
1859 /// @TODO move to top of file or somewhere better
1860 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1863 * @TODO nothing to say?
1865 function api_statuses_destroy($type) {
1869 if (api_user() === false) {
1870 throw new ForbiddenException();
1873 $user_info = api_get_user($a);
1876 $id = intval($a->argv[3]);
1879 $id = intval($_REQUEST["id"]);
1884 $id = intval($a->argv[4]);
1887 logger('API: api_statuses_destroy: '.$id);
1889 $ret = api_statuses_show($type);
1891 drop_item($id, false);
1896 /// @TODO move to top of file or somewhere better
1897 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1900 * @TODO Nothing more than an URL to say?
1901 * http://developer.twitter.com/doc/get/statuses/mentions
1903 function api_statuses_mentions($type) {
1907 if (api_user() === false) {
1908 throw new ForbiddenException();
1911 unset($_REQUEST["user_id"]);
1912 unset($_GET["user_id"]);
1914 unset($_REQUEST["screen_name"]);
1915 unset($_GET["screen_name"]);
1917 $user_info = api_get_user($a);
1918 // get last newtork messages
1922 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1923 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1927 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1928 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1929 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1931 $start = $page * $count;
1933 // Ugly code - should be changed
1934 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
1935 $myurl = substr($myurl,strpos($myurl, '://') + 3);
1936 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1937 $myurl = str_replace('www.', '', $myurl);
1938 $diasp_url = str_replace('/profile/', '/u/', $myurl);
1941 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1944 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1945 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1946 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1947 `contact`.`id` AS `cid`
1948 FROM `item` FORCE INDEX (`uid_id`)
1949 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1950 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1951 WHERE `item`.`uid` = %d AND `verb` = '%s'
1952 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1953 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1954 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1957 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1959 dbesc(ACTIVITY_POST),
1960 dbesc(protect_sprintf($myurl)),
1961 dbesc(protect_sprintf($myurl)),
1964 intval($start), intval($count)
1967 $ret = api_format_items($r, $user_info, false, $type);
1969 $data = array('status' => $ret);
1973 $data = api_rss_extra($a, $data, $user_info);
1977 return api_format_data("statuses", $type, $data);
1980 /// @TODO move to top of file or somewhere better
1981 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1982 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1984 function api_statuses_user_timeline($type) {
1988 if (api_user() === false) {
1989 throw new ForbiddenException();
1992 $user_info = api_get_user($a);
1993 // get last network messages
1995 logger("api_statuses_user_timeline: api_user: ". api_user() .
1996 "\nuser_info: ".print_r($user_info, true) .
1997 "\n_REQUEST: ".print_r($_REQUEST, true),
2001 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2002 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2006 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2007 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2008 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
2009 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
2011 $start = $page * $count;
2014 if ($user_info['self'] == 1) {
2015 $sql_extra .= " AND `item`.`wall` = 1 ";
2018 if ($exclude_replies > 0) {
2019 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2021 if ($conversation_id > 0) {
2022 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2025 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2026 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2027 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2028 `contact`.`id` AS `cid`
2029 FROM `item` FORCE INDEX (`uid_contactid_id`)
2030 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2031 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2032 WHERE `item`.`uid` = %d AND `verb` = '%s'
2033 AND `item`.`contact-id` = %d
2034 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2037 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2039 dbesc(ACTIVITY_POST),
2040 intval($user_info['cid']),
2042 intval($start), intval($count)
2045 $ret = api_format_items($r, $user_info, true, $type);
2047 $data = array('status' => $ret);
2051 $data = api_rss_extra($a, $data, $user_info);
2055 return api_format_data("statuses", $type, $data);
2058 /// @TODO move to top of file or somwhere better
2059 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2062 * Star/unstar an item
2063 * param: id : id of the item
2065 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2067 function api_favorites_create_destroy($type) {
2071 if (api_user() === false) {
2072 throw new ForbiddenException();
2075 // for versioned api.
2076 /// @TODO We need a better global soluton
2077 $action_argv_id = 2;
2078 if ($a->argv[1] == "1.1") {
2079 $action_argv_id = 3;
2082 if ($a->argc <= $action_argv_id) {
2083 throw new BadRequestException("Invalid request.");
2085 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2086 if ($a->argc == $action_argv_id + 2) {
2087 $itemid = intval($a->argv[$action_argv_id + 1]);
2089 /// @TODO use x() to check if _REQUEST contains 'id'
2090 $itemid = intval($_REQUEST['id']);
2093 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1",
2094 $itemid, api_user());
2096 if (!dbm::is_result($item) || count($item) == 0) {
2097 throw new BadRequestException("Invalid item.");
2102 $item[0]['starred'] = 1;
2105 $item[0]['starred'] = 0;
2108 throw new BadRequestException("Invalid action ".$action);
2111 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
2112 $item[0]['starred'], $itemid, api_user());
2114 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
2115 $item[0]['starred'], $itemid, api_user());
2118 throw new InternalServerErrorException("DB error");
2122 $user_info = api_get_user($a);
2123 $rets = api_format_items($item, $user_info, false, $type);
2126 $data = array('status' => $ret);
2130 $data = api_rss_extra($a, $data, $user_info);
2133 return api_format_data("status", $type, $data);
2136 /// @TODO move to top of file or somwhere better
2137 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2138 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2140 function api_favorites($type) {
2145 if (api_user() === false) {
2146 throw new ForbiddenException();
2149 $called_api = array();
2151 $user_info = api_get_user($a);
2153 // in friendica starred item are private
2154 // return favorites only for self
2155 logger('api_favorites: self:' . $user_info['self']);
2157 if ($user_info['self'] == 0) {
2163 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2164 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2165 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2166 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2171 $start = $page*$count;
2174 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2177 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2178 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2179 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2180 `contact`.`id` AS `cid`
2181 FROM `item`, `contact`
2182 WHERE `item`.`uid` = %d
2183 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2184 AND `item`.`starred` = 1
2185 AND `contact`.`id` = `item`.`contact-id`
2186 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2189 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2192 intval($start), intval($count)
2195 $ret = api_format_items($r,$user_info, false, $type);
2199 $data = array('status' => $ret);
2203 $data = api_rss_extra($a, $data, $user_info);
2206 return api_format_data("statuses", $type, $data);
2209 /// @TODO move to top of file or somwhere better
2210 api_register_func('api/favorites','api_favorites', true);
2212 function api_format_messages($item, $recipient, $sender) {
2213 // standard meta information
2215 'id' => $item['id'],
2216 'sender_id' => $sender['id'] ,
2218 'recipient_id' => $recipient['id'],
2219 'created_at' => api_date($item['created']),
2220 'sender_screen_name' => $sender['screen_name'],
2221 'recipient_screen_name' => $recipient['screen_name'],
2222 'sender' => $sender,
2223 'recipient' => $recipient,
2225 'friendica_seen' => $item['seen'],
2226 'friendica_parent_uri' => $item['parent-uri'],
2229 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2230 unset($ret["sender"]["uid"]);
2231 unset($ret["sender"]["self"]);
2232 unset($ret["recipient"]["uid"]);
2233 unset($ret["recipient"]["self"]);
2235 //don't send title to regular StatusNET requests to avoid confusing these apps
2236 if (x($_GET, 'getText')) {
2237 $ret['title'] = $item['title'];
2238 if ($_GET['getText'] == 'html') {
2239 $ret['text'] = bbcode($item['body'], false, false);
2240 } elseif ($_GET['getText'] == 'plain') {
2241 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2242 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2245 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2247 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2248 unset($ret['sender']);
2249 unset($ret['recipient']);
2255 function api_convert_item($item) {
2256 $body = $item['body'];
2257 $attachments = api_get_attachments($body);
2259 // Workaround for ostatus messages where the title is identically to the body
2260 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2261 $statusbody = trim(html2plain($html, 0));
2263 // handle data: images
2264 $statusbody = api_format_items_embeded_images($item,$statusbody);
2266 $statustitle = trim($item['title']);
2268 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2269 $statustext = trim($statusbody);
2271 $statustext = trim($statustitle."\n\n".$statusbody);
2274 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2275 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2278 $statushtml = trim(bbcode($body, false, false));
2280 // Workaround for clients with limited HTML parser functionality
2281 $search = array("<br>", "<blockquote>", "</blockquote>",
2282 "<h1>", "</h1>", "<h2>", "</h2>",
2283 "<h3>", "</h3>", "<h4>", "</h4>",
2284 "<h5>", "</h5>", "<h6>", "</h6>");
2285 $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2286 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2287 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2288 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2289 $statushtml = str_replace($search, $replace, $statushtml);
2291 if ($item['title'] != "") {
2292 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2296 $oldtext = $statushtml;
2297 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2298 } while ($oldtext != $statushtml);
2300 if (substr($statushtml, 0, 4) == '<br>') {
2301 $statushtml = substr($statushtml, 4);
2304 if (substr($statushtml, 0, -4) == '<br>') {
2305 $statushtml = substr($statushtml, -4);
2308 // feeds without body should contain the link
2309 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2310 $statushtml .= bbcode($item['plink']);
2313 $entities = api_get_entitities($statustext, $body);
2316 "text" => $statustext,
2317 "html" => $statushtml,
2318 "attachments" => $attachments,
2319 "entities" => $entities
2323 function api_get_attachments(&$body) {
2326 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2328 $URLSearchString = "^\[\]";
2329 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2335 $attachments = array();
2337 foreach ($images[1] AS $image) {
2338 $imagedata = get_photo_info($image);
2341 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2345 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2346 foreach ($images[0] AS $orig) {
2347 $body = str_replace($orig, "", $body);
2351 return $attachments;
2354 function api_get_entitities(&$text, $bbcode) {
2357 * Links at the first character of the post
2362 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2364 if ($include_entities != "true") {
2366 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2368 foreach ($images[1] AS $image) {
2369 $replace = proxy_url($image);
2370 $text = str_replace($image, $replace, $text);
2375 $bbcode = bb_CleanPictureLinks($bbcode);
2377 // Change pure links in text to bbcode uris
2378 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2380 $entities = array();
2381 $entities["hashtags"] = array();
2382 $entities["symbols"] = array();
2383 $entities["urls"] = array();
2384 $entities["user_mentions"] = array();
2386 $URLSearchString = "^\[\]";
2388 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2390 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2391 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2392 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2394 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2395 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2396 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2398 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2399 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2400 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2402 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2404 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2405 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2407 $ordered_urls = array();
2408 foreach ($urls[1] AS $id => $url) {
2409 //$start = strpos($text, $url, $offset);
2410 $start = iconv_strpos($text, $url, 0, "UTF-8");
2411 if (!($start === false)) {
2412 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2416 ksort($ordered_urls);
2419 //foreach ($urls[1] AS $id=>$url) {
2420 foreach ($ordered_urls AS $url) {
2421 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://") &&
2422 !strpos($url["title"], "http://") && !strpos($url["title"], "https://"))
2423 $display_url = $url["title"];
2425 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2426 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2428 if (strlen($display_url) > 26)
2429 $display_url = substr($display_url, 0, 25)."…";
2432 //$start = strpos($text, $url, $offset);
2433 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2434 if (!($start === false)) {
2435 $entities["urls"][] = array("url" => $url["url"],
2436 "expanded_url" => $url["url"],
2437 "display_url" => $display_url,
2438 "indices" => array($start, $start+strlen($url["url"])));
2439 $offset = $start + 1;
2443 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2444 $ordered_images = array();
2445 foreach ($images[1] AS $image) {
2446 //$start = strpos($text, $url, $offset);
2447 $start = iconv_strpos($text, $image, 0, "UTF-8");
2448 if (!($start === false))
2449 $ordered_images[$start] = $image;
2451 //$entities["media"] = array();
2454 foreach ($ordered_images AS $url) {
2455 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2456 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2458 if (strlen($display_url) > 26)
2459 $display_url = substr($display_url, 0, 25)."…";
2461 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2462 if (!($start === false)) {
2463 $image = get_photo_info($url);
2465 // If image cache is activated, then use the following sizes:
2466 // thumb (150), small (340), medium (600) and large (1024)
2467 if (!Config::get("system", "proxy_disabled")) {
2468 $media_url = proxy_url($url);
2471 $scale = scale_image($image[0], $image[1], 150);
2472 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2474 if (($image[0] > 150) || ($image[1] > 150)) {
2475 $scale = scale_image($image[0], $image[1], 340);
2476 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2479 $scale = scale_image($image[0], $image[1], 600);
2480 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2482 if (($image[0] > 600) || ($image[1] > 600)) {
2483 $scale = scale_image($image[0], $image[1], 1024);
2484 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2488 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2491 $entities["media"][] = array(
2493 "id_str" => (string)$start+1,
2494 "indices" => array($start, $start+strlen($url)),
2495 "media_url" => normalise_link($media_url),
2496 "media_url_https" => $media_url,
2498 "display_url" => $display_url,
2499 "expanded_url" => $url,
2503 $offset = $start + 1;
2509 function api_format_items_embeded_images(&$item, $text) {
2510 $text = preg_replace_callback(
2511 "|data:image/([^;]+)[^=]+=*|m",
2512 function($match) use ($item) {
2513 return System::baseUrl()."/display/".$item['guid'];
2521 * @brief return <a href='url'>name</a> as array
2523 * @param string $txt
2528 function api_contactlink_to_array($txt) {
2530 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2531 if ($r && count($match)==3) {
2533 'name' => $match[2],
2547 * @brief return likes, dislikes and attend status for item
2549 * @param array $item
2551 * likes => int count
2552 * dislikes => int count
2554 function api_format_items_activities(&$item, $type = "json") {
2558 $activities = array(
2560 'dislike' => array(),
2561 'attendyes' => array(),
2562 'attendno' => array(),
2563 'attendmaybe' => array(),
2566 $items = q('SELECT * FROM item
2567 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2568 intval($item['uid']),
2569 dbesc($item['uri']));
2571 foreach ($items as $i) {
2572 // not used as result should be structured like other user data
2573 //builtin_activity_puller($i, $activities);
2575 // get user data and add it to the array of the activity
2576 $user = api_get_user($a, $i['author-link']);
2577 switch ($i['verb']) {
2579 $activities['like'][] = $user;
2581 case ACTIVITY_DISLIKE:
2582 $activities['dislike'][] = $user;
2584 case ACTIVITY_ATTEND:
2585 $activities['attendyes'][] = $user;
2587 case ACTIVITY_ATTENDNO:
2588 $activities['attendno'][] = $user;
2590 case ACTIVITY_ATTENDMAYBE:
2591 $activities['attendmaybe'][] = $user;
2598 if ($type == "xml") {
2599 $xml_activities = array();
2600 foreach ($activities as $k => $v) {
2601 // change xml element from "like" to "friendica:like"
2602 $xml_activities["friendica:".$k] = $v;
2603 // add user data into xml output
2605 foreach ($v as $user)
2606 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2608 $activities = $xml_activities;
2617 * @brief return data from profiles
2619 * @param array $profile array containing data from db table 'profile'
2620 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2623 function api_format_items_profiles(&$profile = null, $type = "json") {
2624 if ($profile != null) {
2625 $profile = array('profile_id' => $profile['id'],
2626 'profile_name' => $profile['profile-name'],
2627 'is_default' => $profile['is-default'] ? true : false,
2628 'hide_friends'=> $profile['hide-friends'] ? true : false,
2629 'profile_photo' => $profile['photo'],
2630 'profile_thumb' => $profile['thumb'],
2631 'publish' => $profile['publish'] ? true : false,
2632 'net_publish' => $profile['net-publish'] ? true : false,
2633 'description' => $profile['pdesc'],
2634 'date_of_birth' => $profile['dob'],
2635 'address' => $profile['address'],
2636 'city' => $profile['locality'],
2637 'region' => $profile['region'],
2638 'postal_code' => $profile['postal-code'],
2639 'country' => $profile['country-name'],
2640 'hometown' => $profile['hometown'],
2641 'gender' => $profile['gender'],
2642 'marital' => $profile['marital'],
2643 'marital_with' => $profile['with'],
2644 'marital_since' => $profile['howlong'],
2645 'sexual' => $profile['sexual'],
2646 'politic' => $profile['politic'],
2647 'religion' => $profile['religion'],
2648 'public_keywords' => $profile['pub_keywords'],
2649 'private_keywords' => $profile['prv_keywords'],
2650 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2651 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2652 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2653 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2654 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2655 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2656 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2657 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2658 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2659 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2660 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2661 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2662 'homepage' => $profile['homepage'],
2669 * @brief format items to be returned by api
2671 * @param array $r array of items
2672 * @param array $user_info
2673 * @param bool $filter_user filter items by $user_info
2675 function api_format_items($r,$user_info, $filter_user = false, $type = "json") {
2681 foreach ($r as $item) {
2683 localize_item($item);
2684 list($status_user, $owner_user) = api_item_get_user($a, $item);
2686 // Look if the posts are matching if they should be filtered by user id
2687 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2691 $in_reply_to = api_in_reply_to($item);
2693 $converted = api_convert_item($item);
2695 if ($type == "xml") {
2696 $geo = "georss:point";
2702 'text' => $converted["text"],
2703 'truncated' => False,
2704 'created_at'=> api_date($item['created']),
2705 'in_reply_to_status_id' => $in_reply_to['status_id'],
2706 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2707 'source' => (($item['app']) ? $item['app'] : 'web'),
2708 'id' => intval($item['id']),
2709 'id_str' => (string) intval($item['id']),
2710 'in_reply_to_user_id' => $in_reply_to['user_id'],
2711 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2712 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2714 'favorited' => $item['starred'] ? true : false,
2715 'user' => $status_user ,
2716 'friendica_owner' => $owner_user,
2717 //'entities' => NULL,
2718 'statusnet_html' => $converted["html"],
2719 'statusnet_conversation_id' => $item['parent'],
2720 'friendica_activities' => api_format_items_activities($item, $type),
2723 if (count($converted["attachments"]) > 0) {
2724 $status["attachments"] = $converted["attachments"];
2727 if (count($converted["entities"]) > 0) {
2728 $status["entities"] = $converted["entities"];
2731 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
2732 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2733 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2734 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2738 // Retweets are only valid for top postings
2739 // It doesn't work reliable with the link if its a feed
2740 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2742 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
2745 if ($item["id"] == $item["parent"]) {
2746 $retweeted_item = api_share_as_retweet($item);
2747 if ($retweeted_item !== false) {
2748 $retweeted_status = $status;
2750 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
2751 } catch( BadRequestException $e ) {
2752 // user not found. should be found?
2753 /// @todo check if the user should be always found
2754 $retweeted_status["user"] = array();
2757 $rt_converted = api_convert_item($retweeted_item);
2759 $retweeted_status['text'] = $rt_converted["text"];
2760 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2761 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2762 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2763 $status['retweeted_status'] = $retweeted_status;
2767 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2768 unset($status["user"]["uid"]);
2769 unset($status["user"]["self"]);
2771 if ($item["coord"] != "") {
2772 $coords = explode(' ',$item["coord"]);
2773 if (count($coords) == 2) {
2774 if ($type == "json")
2775 $status["geo"] = array('type' => 'Point',
2776 'coordinates' => array((float) $coords[0],
2777 (float) $coords[1]));
2778 else // Not sure if this is the official format - if someone founds a documentation we can check
2779 $status["georss:point"] = $item["coord"];
2787 function api_account_rate_limit_status($type) {
2789 if ($type == "xml") {
2791 'remaining-hits' => '150',
2792 '@attributes' => array("type" => "integer"),
2793 'hourly-limit' => '150',
2794 '@attributes2' => array("type" => "integer"),
2795 'reset-time' => datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME),
2796 '@attributes3' => array("type" => "datetime"),
2797 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2798 '@attributes4' => array("type" => "integer"),
2802 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2803 'remaining_hits' => '150',
2804 'hourly_limit' => '150',
2805 'reset_time' => api_date(datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME)),
2809 return api_format_data('hash', $type, array('hash' => $hash));
2812 /// @TODO move to top of file or somwhere better
2813 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2815 function api_help_test($type) {
2816 if ($type == 'xml') {
2822 return api_format_data('ok', $type, array("ok" => $ok));
2825 /// @TODO move to top of file or somwhere better
2826 api_register_func('api/help/test','api_help_test', false);
2828 function api_lists($type) {
2830 /// @TODO $ret is not filled here?
2831 return api_format_data('lists', $type, array("lists_list" => $ret));
2834 /// @TODO move to top of file or somwhere better
2835 api_register_func('api/lists','api_lists',true);
2837 function api_lists_list($type) {
2839 /// @TODO $ret is not filled here?
2840 return api_format_data('lists', $type, array("lists_list" => $ret));
2843 /// @TODO move to top of file or somwhere better
2844 api_register_func('api/lists/list','api_lists_list',true);
2847 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2848 * This function is deprecated by Twitter
2849 * returns: json, xml
2851 function api_statuses_f($type, $qtype) {
2855 if (api_user() === false) {
2856 throw new ForbiddenException();
2859 $user_info = api_get_user($a);
2861 if (x($_GET, 'cursor') && $_GET['cursor']=='undefined') {
2862 /* this is to stop Hotot to load friends multiple times
2863 * I'm not sure if I'm missing return something or
2864 * is a bug in hotot. Workaround, meantime
2868 return array('$users' => $ret);*/
2872 if ($qtype == 'friends') {
2873 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2875 if ($qtype == 'followers') {
2876 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2879 // friends and followers only for self
2880 if ($user_info['self'] == 0) {
2881 $sql_extra = " AND false ";
2884 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra ORDER BY `nick`",
2889 foreach ($r as $cid) {
2890 $user = api_get_user($a, $cid['nurl']);
2891 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2892 unset($user["uid"]);
2893 unset($user["self"]);
2900 return array('user' => $ret);
2904 function api_statuses_friends($type) {
2905 $data = api_statuses_f($type, "friends");
2906 if ($data === false) {
2909 return api_format_data("users", $type, $data);
2912 function api_statuses_followers($type) {
2913 $data = api_statuses_f($type, "followers");
2914 if ($data === false) {
2917 return api_format_data("users", $type, $data);
2920 /// @TODO move to top of file or somewhere better
2921 api_register_func('api/statuses/friends','api_statuses_friends',true);
2922 api_register_func('api/statuses/followers','api_statuses_followers',true);
2924 function api_statusnet_config($type) {
2928 $name = $a->config['sitename'];
2929 $server = $a->get_hostname();
2930 $logo = System::baseUrl() . '/images/friendica-64.png';
2931 $email = $a->config['admin_email'];
2932 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2933 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
2934 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2935 if ($a->config['api_import_size']) {
2936 $texlimit = string($a->config['api_import_size']);
2938 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
2939 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',System::baseUrl()) : '');
2942 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2943 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2944 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2945 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2946 'shorturllength' => '30',
2947 'friendica' => array(
2948 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2949 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2950 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2951 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2956 return api_format_data('config', $type, array('config' => $config));
2960 /// @TODO move to top of file or somewhere better
2961 api_register_func('api/gnusocial/config','api_statusnet_config', false);
2962 api_register_func('api/statusnet/config','api_statusnet_config', false);
2964 function api_statusnet_version($type) {
2966 $fake_statusnet_version = "0.9.7";
2968 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
2971 /// @TODO move to top of file or somewhere better
2972 api_register_func('api/gnusocial/version','api_statusnet_version', false);
2973 api_register_func('api/statusnet/version','api_statusnet_version', false);
2976 * @todo use api_format_data() to return data
2978 function api_ff_ids($type,$qtype) {
2983 throw new ForbiddenException();
2986 $user_info = api_get_user($a);
2988 if ($qtype == 'friends') {
2989 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2991 if ($qtype == 'followers') {
2992 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2995 if (!$user_info["self"]) {
2996 $sql_extra = " AND false ";
2999 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3001 $r = q("SELECT `pcontact`.`id` FROM `contact`
3002 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3003 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3007 if (!dbm::is_result($r)) {
3012 foreach ($r as $rr) {
3013 if ($stringify_ids) {
3016 $ids[] = intval($rr['id']);
3020 return api_format_data("ids", $type, array('id' => $ids));
3023 function api_friends_ids($type) {
3024 return api_ff_ids($type,'friends');
3027 function api_followers_ids($type) {
3028 return api_ff_ids($type,'followers');
3031 /// @TODO move to top of file or somewhere better
3032 api_register_func('api/friends/ids','api_friends_ids',true);
3033 api_register_func('api/followers/ids','api_followers_ids',true);
3035 function api_direct_messages_new($type) {
3039 if (api_user() === false) throw new ForbiddenException();
3041 if (!x($_POST, "text") || (!x($_POST,"screen_name") && !x($_POST,"user_id"))) return;
3043 $sender = api_get_user($a);
3045 if ($_POST['screen_name']) {
3046 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3048 dbesc($_POST['screen_name']));
3050 // Selecting the id by priority, friendica first
3051 api_best_nickname($r);
3053 $recipient = api_get_user($a, $r[0]['nurl']);
3055 $recipient = api_get_user($a, $_POST['user_id']);
3060 if (x($_REQUEST, 'replyto')) {
3061 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3063 intval($_REQUEST['replyto']));
3064 $replyto = $r[0]['parent-uri'];
3065 $sub = $r[0]['title'];
3067 if (x($_REQUEST, 'title')) {
3068 $sub = $_REQUEST['title'];
3070 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'],0,10)."...":$_POST['text']);
3074 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3077 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3078 $ret = api_format_messages($r[0], $recipient, $sender);
3080 $ret = array("error"=>$id);
3083 $data = array('direct_message'=>$ret);
3088 $data = api_rss_extra($a, $data, $user_info);
3091 return api_format_data("direct-messages", $type, $data);
3095 /// @TODO move to top of file or somewhere better
3096 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
3099 * @brief delete a direct_message from mail table through api
3101 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3104 function api_direct_messages_destroy($type) {
3107 if (api_user() === false) {
3108 throw new ForbiddenException();
3112 $user_info = api_get_user($a);
3114 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3116 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3117 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3118 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3120 $uid = $user_info['uid'];
3121 // error if no id or parenturi specified (for clients posting parent-uri as well)
3122 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3123 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3124 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3127 // BadRequestException if no id specified (for clients using Twitter API)
3129 throw new BadRequestException('Message id not specified');
3132 // add parent-uri to sql command if specified by calling app
3133 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3135 // get data of the specified message id
3136 $r = q("SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3140 // error message if specified id is not in database
3141 if (!dbm::is_result($r)) {
3142 if ($verbose == "true") {
3143 $answer = array('result' => 'error', 'message' => 'message id not in database');
3144 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3146 /// @todo BadRequestException ok for Twitter API clients?
3147 throw new BadRequestException('message id not in database');
3151 $result = q("DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3155 if ($verbose == "true") {
3158 $answer = array('result' => 'ok', 'message' => 'message deleted');
3159 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3161 $answer = array('result' => 'error', 'message' => 'unknown error');
3162 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3165 /// @todo return JSON data like Twitter API not yet implemented
3169 /// @TODO move to top of file or somewhere better
3170 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3172 function api_direct_messages_box($type, $box, $verbose) {
3176 if (api_user() === false) {
3177 throw new ForbiddenException();
3181 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3182 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3187 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3188 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3190 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3191 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3194 unset($_REQUEST["user_id"]);
3195 unset($_GET["user_id"]);
3197 unset($_REQUEST["screen_name"]);
3198 unset($_GET["screen_name"]);
3200 $user_info = api_get_user($a);
3201 $profile_url = $user_info["url"];
3204 $start = $page * $count;
3207 if ($box=="sentbox") {
3208 $sql_extra = "`mail`.`from-url`='" . dbesc( $profile_url ) . "'";
3209 } elseif ($box == "conversation") {
3210 $sql_extra = "`mail`.`parent-uri`='" . dbesc( $_GET["uri"] ) . "'";
3211 } elseif ($box == "all") {
3212 $sql_extra = "true";
3213 } elseif ($box == "inbox") {
3214 $sql_extra = "`mail`.`from-url`!='" . dbesc( $profile_url ) . "'";
3218 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3221 if ($user_id != "") {
3222 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3223 } elseif ($screen_name !="") {
3224 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3227 $r = q("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",
3230 intval($start), intval($count)
3232 if ($verbose == "true" && !dbm::is_result($r)) {
3233 $answer = array('result' => 'error', 'message' => 'no mails available');
3234 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3238 foreach ($r as $item) {
3239 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3240 $recipient = $user_info;
3241 $sender = api_get_user($a,normalise_link($item['contact-url']));
3242 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3243 $recipient = api_get_user($a,normalise_link($item['contact-url']));
3244 $sender = $user_info;
3247 $ret[] = api_format_messages($item, $recipient, $sender);
3251 $data = array('direct_message' => $ret);
3255 $data = api_rss_extra($a, $data, $user_info);
3258 return api_format_data("direct-messages", $type, $data);
3262 function api_direct_messages_sentbox($type) {
3263 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3264 return api_direct_messages_box($type, "sentbox", $verbose);
3267 function api_direct_messages_inbox($type) {
3268 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3269 return api_direct_messages_box($type, "inbox", $verbose);
3272 function api_direct_messages_all($type) {
3273 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3274 return api_direct_messages_box($type, "all", $verbose);
3277 function api_direct_messages_conversation($type) {
3278 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3279 return api_direct_messages_box($type, "conversation", $verbose);
3282 /// @TODO move to top of file or somewhere better
3283 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
3284 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
3285 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
3286 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
3288 function api_oauth_request_token($type) {
3290 $oauth = new FKOAuth1();
3291 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
3292 } catch (Exception $e) {
3293 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3300 function api_oauth_access_token($type) {
3302 $oauth = new FKOAuth1();
3303 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
3304 } catch (Exception $e) {
3305 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
3311 /// @TODO move to top of file or somewhere better
3312 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3313 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3317 * @brief delete a complete photoalbum with all containing photos from database through api
3319 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3322 function api_fr_photoalbum_delete($type) {
3323 if (api_user() === false) {
3324 throw new ForbiddenException();
3327 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : "");
3329 // we do not allow calls without album string
3331 throw new BadRequestException("no albumname specified");
3333 // check if album is existing
3334 $r = q("SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3337 if (!dbm::is_result($r))
3338 throw new BadRequestException("album not available");
3340 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3341 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3342 foreach ($r as $rr) {
3343 $photo_item = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3344 intval(local_user()),
3345 dbesc($rr['resource-id'])
3348 if (!dbm::is_result($photo_item)) {
3349 throw new InternalServerErrorException("problem with deleting items occured");
3351 drop_item($photo_item[0]['id'],false);
3354 // now let's delete all photos from the album
3355 $result = q("DELETE FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3359 // return success of deletion or error message
3361 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3362 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3364 throw new InternalServerErrorException("unknown error - deleting from database failed");
3370 * @brief update the name of the album for all photos of an album
3372 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3375 function api_fr_photoalbum_update($type) {
3376 if (api_user() === false) {
3377 throw new ForbiddenException();
3380 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : "");
3381 $album_new = (x($_REQUEST,'album_new') ? $_REQUEST['album_new'] : "");
3383 // we do not allow calls without album string
3385 throw new BadRequestException("no albumname specified");
3387 if ($album_new == "") {
3388 throw new BadRequestException("no new albumname specified");
3390 // check if album is existing
3391 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3394 if (!dbm::is_result($r)) {
3395 throw new BadRequestException("album not available");
3397 // now let's update all photos to the albumname
3398 $result = q("UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3403 // return success of updating or error message
3405 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3406 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3408 throw new InternalServerErrorException("unknown error - updating in database failed");
3414 * @brief list all photos of the authenticated user
3416 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3419 function api_fr_photos_list($type) {
3420 if (api_user() === false) {
3421 throw new ForbiddenException();
3423 $r = q("SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3424 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3425 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3426 intval(local_user())
3429 'image/jpeg' => 'jpg',
3430 'image/png' => 'png',
3431 'image/gif' => 'gif'
3433 $data = array('photo'=>array());
3434 if (dbm::is_result($r)) {
3435 foreach ($r as $rr) {
3437 $photo['id'] = $rr['resource-id'];
3438 $photo['album'] = $rr['album'];
3439 $photo['filename'] = $rr['filename'];
3440 $photo['type'] = $rr['type'];
3441 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3442 $photo['created'] = $rr['created'];
3443 $photo['edited'] = $rr['edited'];
3444 $photo['desc'] = $rr['desc'];
3446 if ($type == "xml") {
3447 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3449 $photo['thumb'] = $thumb;
3450 $data['photo'][] = $photo;
3454 return api_format_data("photos", $type, $data);
3458 * @brief upload a new photo or change an existing photo
3460 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3463 function api_fr_photo_create_update($type) {
3464 if (api_user() === false) {
3465 throw new ForbiddenException();
3468 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3469 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3470 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : null);
3471 $album_new = (x($_REQUEST,'album_new') ? $_REQUEST['album_new'] : null);
3472 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3473 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3474 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3475 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3476 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3478 // do several checks on input parameters
3479 // we do not allow calls without album string
3480 if ($album == null) {
3481 throw new BadRequestException("no albumname specified");
3483 // if photo_id == null --> we are uploading a new photo
3484 if ($photo_id == null) {
3487 // error if no media posted in create-mode
3488 if (!x($_FILES,'media')) {
3490 throw new BadRequestException("no media data submitted");
3493 // album_new will be ignored in create-mode
3498 // check if photo is existing in database
3499 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3503 if (!dbm::is_result($r)) {
3504 throw new BadRequestException("photo not available");
3508 // checks on acl strings provided by clients
3509 $acl_input_error = false;
3510 $acl_input_error |= check_acl_input($allow_cid);
3511 $acl_input_error |= check_acl_input($deny_cid);
3512 $acl_input_error |= check_acl_input($allow_gid);
3513 $acl_input_error |= check_acl_input($deny_gid);
3514 if ($acl_input_error) {
3515 throw new BadRequestException("acl data invalid");
3517 // now let's upload the new media in create-mode
3518 if ($mode == "create") {
3519 $media = $_FILES['media'];
3520 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3522 // return success of updating or error message
3523 if (!is_null($data)) {
3524 return api_format_data("photo_create", $type, $data);
3526 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3530 // now let's do the changes in update-mode
3531 if ($mode == "update") {
3534 if (!is_null($desc)) {
3535 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3538 if (!is_null($album_new)) {
3539 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3542 if (!is_null($allow_cid)) {
3543 $allow_cid = trim($allow_cid);
3544 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3547 if (!is_null($deny_cid)) {
3548 $deny_cid = trim($deny_cid);
3549 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3552 if (!is_null($allow_gid)) {
3553 $allow_gid = trim($allow_gid);
3554 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3557 if (!is_null($deny_gid)) {
3558 $deny_gid = trim($deny_gid);
3559 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3563 if ($sql_extra != "") {
3564 $nothingtodo = false;
3565 $result = q("UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3567 datetime_convert(), // update edited timestamp
3572 $nothingtodo = true;
3575 if (x($_FILES,'media')) {
3576 $nothingtodo = false;
3577 $media = $_FILES['media'];
3578 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3579 if (!is_null($data)) {
3580 return api_format_data("photo_update", $type, $data);
3584 // return success of updating or error message
3586 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
3587 return api_format_data("photo_update", $type, array('$result' => $answer));
3590 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
3591 return api_format_data("photo_update", $type, array('$result' => $answer));
3593 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3596 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3601 * @brief delete a single photo from the database through api
3603 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3606 function api_fr_photo_delete($type) {
3607 if (api_user() === false) {
3608 throw new ForbiddenException();
3611 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3613 // do several checks on input parameters
3614 // we do not allow calls without photo id
3615 if ($photo_id == null) {
3616 throw new BadRequestException("no photo_id specified");
3618 // check if photo is existing in database
3619 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3623 if (!dbm::is_result($r)) {
3624 throw new BadRequestException("photo not available");
3626 // now we can perform on the deletion of the photo
3627 $result = q("DELETE FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3631 // return success of deletion or error message
3633 // retrieve the id of the parent element (the photo element)
3634 $photo_item = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3635 intval(local_user()),
3639 if (!dbm::is_result($photo_item)) {
3640 throw new InternalServerErrorException("problem with deleting items occured");
3642 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3643 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
3644 drop_item($photo_item[0]['id'], false);
3646 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
3647 return api_format_data("photo_delete", $type, array('$result' => $answer));
3649 throw new InternalServerErrorException("unknown error on deleting photo from database table");
3655 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3657 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3660 function api_fr_photo_detail($type) {
3661 if (api_user() === false) {
3662 throw new ForbiddenException();
3664 if (!x($_REQUEST, 'photo_id')) {
3665 throw new BadRequestException("No photo id.");
3668 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3669 $photo_id = $_REQUEST['photo_id'];
3671 // prepare json/xml output with data from database for the requested photo
3672 $data = prepare_photo_data($type, $scale, $photo_id);
3674 return api_format_data("photo_detail", $type, $data);
3679 * @brief updates the profile image for the user (either a specified profile or the default profile)
3681 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3684 function api_account_update_profile_image($type) {
3685 if (api_user() === false) {
3686 throw new ForbiddenException();
3689 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
3691 // error if image data is missing
3692 if (!x($_FILES, 'image')) {
3693 throw new BadRequestException("no media data submitted");
3696 // check if specified profile id is valid
3697 if ($profileid != 0) {
3698 $r = q("SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
3700 intval($profileid));
3701 // error message if specified profile id is not in database
3702 if (!dbm::is_result($r)) {
3703 throw new BadRequestException("profile_id not available");
3705 $is_default_profile = $r['profile'];
3707 $is_default_profile = 1;
3710 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3712 if (x($_FILES, 'image')) {
3713 $media = $_FILES['image'];
3714 } elseif (x($_FILES, 'media')) {
3715 $media = $_FILES['media'];
3717 // save new profile image
3718 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
3721 if (is_array($media['type'])) {
3722 $filetype = $media['type'][0];
3724 $filetype = $media['type'];
3726 if ($filetype == "image/jpeg") {
3728 } elseif ($filetype == "image/png") {
3731 // change specified profile or all profiles to the new resource-id
3732 if ($is_default_profile) {
3733 $r = q("UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
3734 dbesc($data['photo']['id']),
3735 intval(local_user())
3738 $r = q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
3739 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
3740 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
3741 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
3742 intval(local_user())
3745 $r = q("UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
3746 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
3747 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
3748 intval($_REQUEST['profile']),
3749 intval(local_user())
3753 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
3754 // so that browsers will do a cache update unconditionally
3756 $r = q("UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
3757 dbesc(datetime_convert()),
3758 intval(local_user())
3761 // Update global directory in background
3762 //$user = api_get_user(get_app());
3763 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
3764 if ($url && strlen(Config::get('system', 'directory'))) {
3765 Worker::add(PRIORITY_LOW, "directory", $url);
3768 Worker::add(PRIORITY_LOW, 'profile_update', api_user());
3770 // output for client
3772 return api_account_verify_credentials($type);
3774 // SaveMediaToDatabase failed for some reason
3775 throw new InternalServerErrorException("image upload failed");
3779 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3780 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
3781 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
3782 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3783 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3784 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3785 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
3786 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3787 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3790 function check_acl_input($acl_string) {
3791 if ($acl_string == null || $acl_string == " ") {
3794 $contact_not_found = false;
3796 // split <x><y><z> into array of cid's
3797 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3799 // check for each cid if it is available on server
3800 $cid_array = $array[0];
3801 foreach ($cid_array as $cid) {
3802 $cid = str_replace("<", "", $cid);
3803 $cid = str_replace(">", "", $cid);
3804 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3806 intval(api_user()));
3807 $contact_not_found |= !dbm::is_result($contact);
3809 return $contact_not_found;
3812 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) {
3819 if (is_array($media)) {
3820 if (is_array($media['tmp_name'])) {
3821 $src = $media['tmp_name'][0];
3823 $src = $media['tmp_name'];
3825 if (is_array($media['name'])) {
3826 $filename = basename($media['name'][0]);
3828 $filename = basename($media['name']);
3830 if (is_array($media['size'])) {
3831 $filesize = intval($media['size'][0]);
3833 $filesize = intval($media['size']);
3835 if (is_array($media['type'])) {
3836 $filetype = $media['type'][0];
3838 $filetype = $media['type'];
3842 if ($filetype == "") {
3843 $filetype=guess_image_type($filename);
3845 $imagedata = getimagesize($src);
3847 $filetype = $imagedata['mime'];
3849 logger("File upload src: " . $src . " - filename: " . $filename .
3850 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG);
3852 // check if there was a php upload error
3853 if ($filesize == 0 && $media['error'] == 1) {
3854 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3856 // check against max upload size within Friendica instance
3857 $maximagesize = Config::get('system', 'maximagesize');
3858 if (($maximagesize) && ($filesize > $maximagesize)) {
3859 $formattedBytes = formatBytes($maximagesize);
3860 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3863 // create Photo instance with the data of the image
3864 $imagedata = @file_get_contents($src);
3865 $ph = new Photo($imagedata, $filetype);
3866 if (! $ph->is_valid()) {
3867 throw new InternalServerErrorException("unable to process image data");
3870 // check orientation of image
3874 // check max length of images on server
3875 $max_length = Config::get('system', 'max_image_length');
3876 if (! $max_length) {
3877 $max_length = MAX_IMAGE_LENGTH;
3879 if ($max_length > 0) {
3880 $ph->scaleImage($max_length);
3881 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
3883 $width = $ph->getWidth();
3884 $height = $ph->getHeight();
3886 // create a new resource-id if not already provided
3887 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
3889 if ($mediatype == "photo") {
3890 // upload normal image (scales 0, 1, 2)
3891 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
3893 $r =$ph->store(local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3895 logger("photo upload: image upload with scale 0 (original size) failed");
3897 if($width > 640 || $height > 640) {
3898 $ph->scaleImage(640);
3899 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3901 logger("photo upload: image upload with scale 1 (640x640) failed");
3905 if ($width > 320 || $height > 320) {
3906 $ph->scaleImage(320);
3907 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3909 logger("photo upload: image upload with scale 2 (320x320) failed");
3912 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
3913 } elseif ($mediatype == "profileimage") {
3914 // upload profile image (scales 4, 5, 6)
3915 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
3917 if ($width > 175 || $height > 175) {
3918 $ph->scaleImage(175);
3919 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3921 logger("photo upload: profile image upload with scale 4 (175x175) failed");
3925 if ($width > 80 || $height > 80) {
3926 $ph->scaleImage(80);
3927 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3929 logger("photo upload: profile image upload with scale 5 (80x80) failed");
3933 if ($width > 48 || $height > 48) {
3934 $ph->scaleImage(48);
3935 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3937 logger("photo upload: profile image upload with scale 6 (48x48) failed");
3941 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
3945 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
3946 if ($photo_id == null && $mediatype == "photo") {
3947 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
3949 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
3950 return prepare_photo_data($type, false, $hash);
3952 throw new InternalServerErrorException("image upload failed");
3956 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false) {
3957 // get data about the api authenticated user
3958 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
3959 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
3962 $arr['guid'] = get_guid(32);
3963 $arr['uid'] = intval(api_user());
3965 $arr['parent-uri'] = $uri;
3966 $arr['type'] = 'photo';
3968 $arr['resource-id'] = $hash;
3969 $arr['contact-id'] = $owner_record[0]['id'];
3970 $arr['owner-name'] = $owner_record[0]['name'];
3971 $arr['owner-link'] = $owner_record[0]['url'];
3972 $arr['owner-avatar'] = $owner_record[0]['thumb'];
3973 $arr['author-name'] = $owner_record[0]['name'];
3974 $arr['author-link'] = $owner_record[0]['url'];
3975 $arr['author-avatar'] = $owner_record[0]['thumb'];
3977 $arr['allow_cid'] = $allow_cid;
3978 $arr['allow_gid'] = $allow_gid;
3979 $arr['deny_cid'] = $deny_cid;
3980 $arr['deny_gid'] = $deny_gid;
3981 $arr['last-child'] = 1;
3982 $arr['visible'] = $visibility;
3986 'image/jpeg' => 'jpg',
3987 'image/png' => 'png',
3988 'image/gif' => 'gif'
3991 // adds link to the thumbnail scale photo
3992 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
3993 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
3996 // do the magic for storing the item in the database and trigger the federation to other contacts
4000 function prepare_photo_data($type, $scale, $photo_id) {
4001 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4002 $data_sql = ($scale === false ? "" : "data, ");
4004 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4005 // clients needs to convert this in their way for further processing
4006 $r = q("SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4007 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4008 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4009 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4011 intval(local_user()),
4017 'image/jpeg' => 'jpg',
4018 'image/png' => 'png',
4019 'image/gif' => 'gif'
4022 // prepare output data for photo
4023 if (dbm::is_result($r)) {
4024 $data = array('photo' => $r[0]);
4025 $data['photo']['id'] = $data['photo']['resource-id'];
4026 if ($scale !== false) {
4027 $data['photo']['data'] = base64_encode($data['photo']['data']);
4029 unset($data['photo']['datasize']); //needed only with scale param
4031 if ($type == "xml") {
4032 $data['photo']['links'] = array();
4033 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4034 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4036 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4039 $data['photo']['link'] = array();
4040 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4042 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4043 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4047 unset($data['photo']['resource-id']);
4048 unset($data['photo']['minscale']);
4049 unset($data['photo']['maxscale']);
4052 throw new NotFoundException();
4055 // retrieve item element for getting activities (like, dislike etc.) related to photo
4056 $item = q("SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4057 intval(local_user()),
4060 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4062 // retrieve comments on photo
4063 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4064 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4065 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4066 `contact`.`id` AS `cid`
4068 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4069 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4070 WHERE `item`.`parent` = %d AND `item`.`visible`
4071 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4072 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4073 intval($item[0]['parent']),
4075 dbesc(ACTIVITY_POST)
4078 // prepare output of comments
4079 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4080 $comments = array();
4081 if ($type == "xml") {
4083 foreach ($commentData as $comment) {
4084 $comments[$k++ . ":comment"] = $comment;
4087 foreach ($commentData as $comment) {
4088 $comments[] = $comment;
4091 $data['photo']['friendica_comments'] = $comments;
4093 // include info if rights on photo and rights on item are mismatching
4094 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4095 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4096 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4097 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4098 $data['photo']['rights_mismatch'] = $rights_mismatch;
4105 * similar as /mod/redir.php
4106 * redirect to 'url' after dfrn auth
4108 * why this when there is mod/redir.php already?
4109 * This use api_user() and api_login()
4112 * c_url: url of remote contact to auth to
4113 * url: string, url to redirect after auth
4115 function api_friendica_remoteauth() {
4116 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4117 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4119 if ($url === '' || $c_url === '') {
4120 throw new BadRequestException("Wrong parameters.");
4123 $c_url = normalise_link($c_url);
4127 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4132 if ((! dbm::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4133 throw new BadRequestException("Unknown contact");
4138 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4140 if ($r[0]['duplex'] && $r[0]['issued-id']) {
4141 $orig_id = $r[0]['issued-id'];
4142 $dfrn_id = '1:' . $orig_id;
4144 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4145 $orig_id = $r[0]['dfrn-id'];
4146 $dfrn_id = '0:' . $orig_id;
4149 $sec = random_string();
4151 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4152 VALUES( %d, %s, '%s', '%s', %d )",
4160 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4161 $dest = (($url) ? '&destination_url=' . $url : '');
4162 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4163 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4164 . '&type=profile&sec=' . $sec . $dest . $quiet );
4166 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4169 * @brief Return the item shared, if the item contains only the [share] tag
4171 * @param array $item Sharer item
4172 * @return array Shared item or false if not a reshare
4174 function api_share_as_retweet(&$item) {
4175 $body = trim($item["body"]);
4177 if (Diaspora::is_reshare($body, false)===false) {
4181 /// @TODO "$1" should maybe mean '$1' ?
4182 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4184 * Skip if there is no shared message in there
4185 * we already checked this in diaspora::is_reshare()
4186 * but better one more than one less...
4188 if ($body == $attributes) {
4193 // build the fake reshared item
4194 $reshared_item = $item;
4197 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4198 if ($matches[1] != "") {
4199 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4202 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4203 if ($matches[1] != "") {
4204 $author = $matches[1];
4208 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4209 if ($matches[1] != "") {
4210 $profile = $matches[1];
4213 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4214 if ($matches[1] != "") {
4215 $profile = $matches[1];
4219 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4220 if ($matches[1] != "") {
4221 $avatar = $matches[1];
4224 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4225 if ($matches[1] != "") {
4226 $avatar = $matches[1];
4230 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4231 if ($matches[1] != "") {
4232 $link = $matches[1];
4235 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4236 if ($matches[1] != "") {
4237 $link = $matches[1];
4241 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4242 if ($matches[1] != "")
4243 $posted = $matches[1];
4245 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4246 if ($matches[1] != "") {
4247 $posted = $matches[1];
4250 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
4252 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4256 $reshared_item["body"] = $shared_body;
4257 $reshared_item["author-name"] = $author;
4258 $reshared_item["author-link"] = $profile;
4259 $reshared_item["author-avatar"] = $avatar;
4260 $reshared_item["plink"] = $link;
4261 $reshared_item["created"] = $posted;
4262 $reshared_item["edited"] = $posted;
4264 return $reshared_item;
4268 function api_get_nick($profile) {
4270 - remove trailing junk from profile url
4271 - pump.io check has to check the website
4276 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4277 dbesc(normalise_link($profile)));
4279 if (dbm::is_result($r)) {
4280 $nick = $r[0]["nick"];
4284 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4285 dbesc(normalise_link($profile)));
4287 if (dbm::is_result($r)) {
4288 $nick = $r[0]["nick"];
4293 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4294 if ($friendica != $profile) {
4300 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4301 if ($diaspora != $profile) {
4307 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4308 if ($twitter != $profile) {
4315 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4316 if ($StatusnetHost != $profile) {
4317 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4318 if ($StatusnetUser != $profile) {
4319 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4320 $user = json_decode($UserData);
4322 $nick = $user->screen_name;
4328 // To-Do: look at the page if its really a pumpio site
4329 //if (!$nick == "") {
4330 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4331 // if ($pumpio != $profile)
4333 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4344 function api_in_reply_to($item) {
4345 $in_reply_to = array();
4347 $in_reply_to['status_id'] = NULL;
4348 $in_reply_to['user_id'] = NULL;
4349 $in_reply_to['status_id_str'] = NULL;
4350 $in_reply_to['user_id_str'] = NULL;
4351 $in_reply_to['screen_name'] = NULL;
4353 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4354 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4355 intval($item['uid']),
4356 dbesc($item['thr-parent']));
4358 if (dbm::is_result($r)) {
4359 $in_reply_to['status_id'] = intval($r[0]['id']);
4361 $in_reply_to['status_id'] = intval($item['parent']);
4364 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4366 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4367 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4368 WHERE `item`.`id` = %d LIMIT 1",
4369 intval($in_reply_to['status_id'])
4372 if (dbm::is_result($r)) {
4373 if ($r[0]['nick'] == "") {
4374 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4377 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4378 $in_reply_to['user_id'] = intval($r[0]['id']);
4379 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4382 // There seems to be situation, where both fields are identical:
4383 // https://github.com/friendica/friendica/issues/1010
4384 // This is a bugfix for that.
4385 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4386 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4387 $in_reply_to['status_id'] = NULL;
4388 $in_reply_to['user_id'] = NULL;
4389 $in_reply_to['status_id_str'] = NULL;
4390 $in_reply_to['user_id_str'] = NULL;
4391 $in_reply_to['screen_name'] = NULL;
4395 return $in_reply_to;
4398 function api_clean_plain_items($Text) {
4399 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4401 $Text = bb_CleanPictureLinks($Text);
4402 $URLSearchString = "^\[\]";
4404 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
4406 if ($include_entities == "true") {
4407 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
4410 // Simplify "attachment" element
4411 $Text = api_clean_attachments($Text);
4417 * @brief Removes most sharing information for API text export
4419 * @param string $body The original body
4421 * @return string Cleaned body
4423 function api_clean_attachments($body) {
4424 $data = get_attachment_data($body);
4431 if (isset($data["text"]))
4432 $body = $data["text"];
4434 if (($body == "") && (isset($data["title"])))
4435 $body = $data["title"];
4437 if (isset($data["url"]))
4438 $body .= "\n".$data["url"];
4440 $body .= $data["after"];
4445 function api_best_nickname(&$contacts) {
4446 $best_contact = array();
4448 if (count($contact) == 0)
4451 foreach ($contacts AS $contact)
4452 if ($contact["network"] == "") {
4453 $contact["network"] = "dfrn";
4454 $best_contact = array($contact);
4457 if (sizeof($best_contact) == 0)
4458 foreach ($contacts AS $contact)
4459 if ($contact["network"] == "dfrn")
4460 $best_contact = array($contact);
4462 if (sizeof($best_contact) == 0)
4463 foreach ($contacts AS $contact)
4464 if ($contact["network"] == "dspr")
4465 $best_contact = array($contact);
4467 if (sizeof($best_contact) == 0)
4468 foreach ($contacts AS $contact)
4469 if ($contact["network"] == "stat")
4470 $best_contact = array($contact);
4472 if (sizeof($best_contact) == 0)
4473 foreach ($contacts AS $contact)
4474 if ($contact["network"] == "pump")
4475 $best_contact = array($contact);
4477 if (sizeof($best_contact) == 0)
4478 foreach ($contacts AS $contact)
4479 if ($contact["network"] == "twit")
4480 $best_contact = array($contact);
4482 if (sizeof($best_contact) == 1)
4483 $contacts = $best_contact;
4485 $contacts = array($contacts[0]);
4488 // return all or a specified group of the user with the containing contacts
4489 function api_friendica_group_show($type) {
4493 if (api_user() === false) throw new ForbiddenException();
4496 $user_info = api_get_user($a);
4497 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4498 $uid = $user_info['uid'];
4500 // get data of the specified group id or all groups if not specified
4502 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4505 // error message if specified gid is not in database
4506 if (!dbm::is_result($r))
4507 throw new BadRequestException("gid not available");
4510 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4513 // loop through all groups and retrieve all members for adding data in the user array
4514 foreach ($r as $rr) {
4515 $members = group_get_members($rr['id']);
4518 if ($type == "xml") {
4519 $user_element = "users";
4521 foreach ($members as $member) {
4522 $user = api_get_user($a, $member['nurl']);
4523 $users[$k++.":user"] = $user;
4526 $user_element = "user";
4527 foreach ($members as $member) {
4528 $user = api_get_user($a, $member['nurl']);
4532 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4534 return api_format_data("groups", $type, array('group' => $grps));
4536 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4539 // delete the specified group of the user
4540 function api_friendica_group_delete($type) {
4544 if (api_user() === false) throw new ForbiddenException();
4547 $user_info = api_get_user($a);
4548 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4549 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4550 $uid = $user_info['uid'];
4552 // error if no gid specified
4553 if ($gid == 0 || $name == "")
4554 throw new BadRequestException('gid or name not specified');
4556 // get data of the specified group id
4557 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
4560 // error message if specified gid is not in database
4561 if (!dbm::is_result($r))
4562 throw new BadRequestException('gid not available');
4564 // get data of the specified group id and group name
4565 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
4569 // error message if specified gid is not in database
4570 if (!dbm::is_result($rname))
4571 throw new BadRequestException('wrong group name');
4574 $ret = group_rmv($uid, $name);
4577 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
4578 return api_format_data("group_delete", $type, array('result' => $success));
4581 throw new BadRequestException('other API error');
4583 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4586 // create the specified group with the posted array of contacts
4587 function api_friendica_group_create($type) {
4591 if (api_user() === false) throw new ForbiddenException();
4594 $user_info = api_get_user($a);
4595 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4596 $uid = $user_info['uid'];
4597 $json = json_decode($_POST['json'], true);
4598 $users = $json['user'];
4600 // error if no name specified
4602 throw new BadRequestException('group name not specified');
4604 // get data of the specified group name
4605 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
4608 // error message if specified group name already exists
4609 if (dbm::is_result($rname))
4610 throw new BadRequestException('group name already exists');
4612 // check if specified group name is a deleted group
4613 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
4616 // error message if specified group name already exists
4617 if (dbm::is_result($rname))
4618 $reactivate_group = true;
4621 $ret = group_add($uid, $name);
4623 $gid = group_byname($uid, $name);
4625 throw new BadRequestException('other API error');
4628 $erroraddinguser = false;
4629 $errorusers = array();
4630 foreach ($users as $user) {
4631 $cid = $user['cid'];
4632 // check if user really exists as contact
4633 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4636 if (count($contact))
4637 $result = group_add_member($uid, $name, $cid, $gid);
4639 $erroraddinguser = true;
4640 $errorusers[] = $cid;
4644 // return success message incl. missing users in array
4645 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
4646 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4647 return api_format_data("group_create", $type, array('result' => $success));
4649 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4652 // update the specified group with the posted array of contacts
4653 function api_friendica_group_update($type) {
4657 if (api_user() === false) throw new ForbiddenException();
4660 $user_info = api_get_user($a);
4661 $uid = $user_info['uid'];
4662 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4663 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4664 $json = json_decode($_POST['json'], true);
4665 $users = $json['user'];
4667 // error if no name specified
4669 throw new BadRequestException('group name not specified');
4671 // error if no gid specified
4673 throw new BadRequestException('gid not specified');
4676 $members = group_get_members($gid);
4677 foreach ($members as $member) {
4678 $cid = $member['id'];
4679 foreach ($users as $user) {
4680 $found = ($user['cid'] == $cid ? true : false);
4683 $ret = group_rmv_member($uid, $name, $cid);
4688 $erroraddinguser = false;
4689 $errorusers = array();
4690 foreach ($users as $user) {
4691 $cid = $user['cid'];
4692 // check if user really exists as contact
4693 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4696 if (count($contact))
4697 $result = group_add_member($uid, $name, $cid, $gid);
4699 $erroraddinguser = true;
4700 $errorusers[] = $cid;
4704 // return success message incl. missing users in array
4705 $status = ($erroraddinguser ? "missing user" : "ok");
4706 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4707 return api_format_data("group_update", $type, array('result' => $success));
4710 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4712 function api_friendica_activity($type) {
4716 if (api_user() === false) throw new ForbiddenException();
4717 $verb = strtolower($a->argv[3]);
4718 $verb = preg_replace("|\..*$|", "", $verb);
4720 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4722 $res = do_like($id, $verb);
4729 return api_format_data('ok', $type, array('ok' => $ok));
4731 throw new BadRequestException('Error adding activity');
4736 /// @TODO move to top of file or somwhere better
4737 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
4738 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
4739 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
4740 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
4741 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4742 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
4743 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
4744 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
4745 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
4746 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4749 * @brief Returns notifications
4751 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4754 function api_friendica_notification($type) {
4758 if (api_user() === false) throw new ForbiddenException();
4759 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
4760 $nm = new NotificationsManager();
4762 $notes = $nm->getAll(array(), "+seen -date", 50);
4764 if ($type == "xml") {
4765 $xmlnotes = array();
4766 foreach ($notes AS $note)
4767 $xmlnotes[] = array("@attributes" => $note);
4772 return api_format_data("notes", $type, array('note' => $notes));
4776 * @brief Set notification as seen and returns associated item (if possible)
4778 * POST request with 'id' param as notification id
4780 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4783 function api_friendica_notification_seen($type) {
4787 if (api_user() === false) throw new ForbiddenException();
4788 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
4790 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
4792 $nm = new NotificationsManager();
4793 $note = $nm->getByID($id);
4794 if (is_null($note)) throw new BadRequestException("Invalid argument");
4796 $nm->setSeen($note);
4797 if ($note['otype']=='item') {
4798 // would be really better with an ItemsManager and $im->getByID() :-P
4799 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
4800 intval($note['iid']),
4801 intval(local_user())
4804 // we found the item, return it to the user
4805 $user_info = api_get_user($a);
4806 $ret = api_format_items($r,$user_info, false, $type);
4807 $data = array('status' => $ret);
4808 return api_format_data("status", $type, $data);
4810 // the item can't be found, but we set the note as seen, so we count this as a success
4812 return api_format_data('result', $type, array('result' => "success"));
4815 /// @TODO move to top of file or somwhere better
4816 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4817 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
4820 * @brief update a direct_message to seen state
4822 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4823 * @return string (success result=ok, error result=error with error message)
4825 function api_friendica_direct_messages_setseen($type) {
4827 if (api_user() === false) {
4828 throw new ForbiddenException();
4832 $user_info = api_get_user($a);
4833 $uid = $user_info['uid'];
4834 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4836 // return error if id is zero
4838 $answer = array('result' => 'error', 'message' => 'message id not specified');
4839 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4842 // get data of the specified message id
4843 $r = q("SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
4847 // error message if specified id is not in database
4848 if (!dbm::is_result($r)) {
4849 $answer = array('result' => 'error', 'message' => 'message id not in database');
4850 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4853 // update seen indicator
4854 $result = q("UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
4860 $answer = array('result' => 'ok', 'message' => 'message set to seen');
4861 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
4863 $answer = array('result' => 'error', 'message' => 'unknown error');
4864 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4868 /// @TODO move to top of file or somwhere better
4869 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
4872 * @brief search for direct_messages containing a searchstring through api
4874 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4875 * @return string (success: success=true if found and search_result contains found messages
4876 * success=false if nothing was found, search_result='nothing found',
4877 * error: result=error with error message)
4879 function api_friendica_direct_messages_search($type) {
4882 if (api_user() === false) {
4883 throw new ForbiddenException();
4887 $user_info = api_get_user($a);
4888 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
4889 $uid = $user_info['uid'];
4891 // error if no searchstring specified
4892 if ($searchstring == "") {
4893 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
4894 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
4897 // get data for the specified searchstring
4898 $r = q("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",
4900 dbesc('%'.$searchstring.'%')
4903 $profile_url = $user_info["url"];
4905 // message if nothing was found
4906 if (!dbm::is_result($r)) {
4907 $success = array('success' => false, 'search_results' => 'problem with query');
4908 } elseif (count($r) == 0) {
4909 $success = array('success' => false, 'search_results' => 'nothing found');
4912 foreach ($r as $item) {
4913 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4914 $recipient = $user_info;
4915 $sender = api_get_user($a,normalise_link($item['contact-url']));
4916 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4917 $recipient = api_get_user($a,normalise_link($item['contact-url']));
4918 $sender = $user_info;
4921 $ret[] = api_format_messages($item, $recipient, $sender);
4923 $success = array('success' => true, 'search_results' => $ret);
4926 return api_format_data("direct_message_search", $type, array('$result' => $success));
4929 /// @TODO move to top of file or somwhere better
4930 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
4933 * @brief return data of all the profiles a user has to the client
4935 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4938 function api_friendica_profile_show($type) {
4941 if (api_user() === false) {
4942 throw new ForbiddenException();
4946 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
4948 // retrieve general information about profiles for user
4949 $multi_profiles = feature_enabled(api_user(),'multi_profiles');
4950 $directory = Config::get('system', 'directory');
4952 // get data of the specified profile id or all profiles of the user if not specified
4953 if ($profileid != 0) {
4954 $r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
4956 intval($profileid));
4958 // error message if specified gid is not in database
4959 if (!dbm::is_result($r)) {
4960 throw new BadRequestException("profile_id not available");
4963 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
4964 intval(api_user()));
4966 // loop through all returned profiles and retrieve data and users
4968 foreach ($r as $rr) {
4969 $profile = api_format_items_profiles($rr, $type);
4971 // select all users from contact table, loop and prepare standard return for user data
4973 $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
4975 intval($rr['profile_id']));
4977 foreach ($r as $rr) {
4978 $user = api_get_user($a, $rr['nurl']);
4979 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
4981 $profile['users'] = $users;
4983 // add prepared profile data to array for final return
4984 if ($type == "xml") {
4985 $profiles[$k++ . ":profile"] = $profile;
4987 $profiles[] = $profile;
4991 // return settings, authenticated user and profiles data
4992 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4994 $result = array('multi_profiles' => $multi_profiles ? true : false,
4995 'global_dir' => $directory,
4996 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
4997 'profiles' => $profiles);
4998 return api_format_data("friendica_profiles", $type, array('$result' => $result));
5000 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5003 @TODO Maybe open to implement?
5005 [pagename] => api/1.1/statuses/lookup.json
5006 [id] => 605138389168451584
5007 [include_cards] => true
5008 [cards_platform] => Android-12
5009 [include_entities] => true
5010 [include_my_retweet] => 1
5012 [include_reply_count] => true
5013 [include_descendent_reply_count] => true
5017 Not implemented by now:
5018 statuses/retweets_of_me
5023 account/update_location
5024 account/update_profile_background_image
5027 friendica/profile/update
5028 friendica/profile/create
5029 friendica/profile/delete
5031 Not implemented in status.net:
5032 statuses/retweeted_to_me
5033 statuses/retweeted_by_me
5034 direct_messages/destroy
5036 account/update_delivery_device
5037 notifications/follow