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;
14 use Friendica\Database\DBM;
15 use Friendica\Network\HTTPException;
16 use Friendica\Network\HTTPException\BadRequestException;
17 use Friendica\Network\HTTPException\ForbiddenException;
18 use Friendica\Network\HTTPException\InternalServerErrorException;
19 use Friendica\Network\HTTPException\MethodNotAllowedException;
20 use Friendica\Network\HTTPException\NotFoundException;
21 use Friendica\Network\HTTPException\NotImplementedException;
22 use Friendica\Network\HTTPException\UnauthorizedException;
23 use Friendica\Network\HTTPException\TooManyRequestsException;
24 use Friendica\Object\Contact;
25 use Friendica\Protocol\Diaspora;
26 use Friendica\Util\XML;
28 require_once 'include/bbcode.php';
29 require_once 'include/datetime.php';
30 require_once 'include/conversation.php';
31 require_once 'include/oauth.php';
32 require_once 'include/html2plain.php';
33 require_once 'mod/share.php';
34 require_once 'include/Photo.php';
35 require_once 'mod/item.php';
36 require_once 'include/security.php';
37 require_once 'include/contact_selectors.php';
38 require_once 'include/html2bbcode.php';
39 require_once 'mod/wall_upload.php';
40 require_once 'mod/proxy.php';
41 require_once 'include/message.php';
42 require_once 'include/group.php';
43 require_once 'include/like.php';
44 require_once 'include/plaintext.php';
46 define('API_METHOD_ANY', '*');
47 define('API_METHOD_GET', 'GET');
48 define('API_METHOD_POST', 'POST,PUT');
49 define('API_METHOD_DELETE', 'POST,DELETE');
55 * @brief Auth API user
57 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
58 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
59 * into a page, and visitors will post something without noticing it).
63 if (x($_SESSION, 'allow_api')) {
71 * @brief Get source name from API client
73 * Clients can send 'source' parameter to be show in post metadata
74 * as "sent via <source>".
75 * Some clients doesn't send a source param, we support ones we know
79 * Client source name, default to "api" if unset/unknown
83 if (requestdata('source')) {
84 return requestdata('source');
87 // Support for known clients that doesn't send a source name
88 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
92 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
98 * @brief Format date for API
100 * @param string $str Source date, as UTC
101 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
103 function api_date($str)
105 // Wed May 23 06:01:13 +0000 2007
106 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y");
110 * @brief Register API endpoint
112 * Register a function to be the endpont for defined API path.
114 * @param string $path API URL path, relative to System::baseUrl()
115 * @param string $func Function name to call on path request
116 * @param bool $auth API need logged user
117 * @param string $method HTTP method reqiured to call this endpoint.
118 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
119 * Default to API_METHOD_ANY
121 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
131 // Workaround for hotot
132 $path = str_replace("api/", "api/1.1/", $path);
142 * @brief Login API user
144 * Log in user via OAuth1 or Simple HTTP Auth.
145 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
147 * @param object $a App
148 * @hook 'authenticate'
150 * 'username' => username from login form
151 * 'password' => password from login form
152 * 'authenticated' => return status,
153 * 'user_record' => return authenticated user record
155 * array $user logged user record
157 function api_login(App $a)
161 $oauth = new FKOAuth1();
162 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
163 if (!is_null($token)) {
164 $oauth->loginUser($token->uid);
165 call_hooks('logged_in', $a->user);
168 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
169 var_dump($consumer, $token);
171 } catch (Exception $e) {
175 // workaround for HTTP-auth in CGI mode
176 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
177 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
178 if (strlen($userpass)) {
179 list($name, $password) = explode(':', $userpass);
180 $_SERVER['PHP_AUTH_USER'] = $name;
181 $_SERVER['PHP_AUTH_PW'] = $password;
185 if (!x($_SERVER, 'PHP_AUTH_USER')) {
186 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
187 header('WWW-Authenticate: Basic realm="Friendica"');
188 throw new UnauthorizedException("This API requires login");
191 $user = $_SERVER['PHP_AUTH_USER'];
192 $password = $_SERVER['PHP_AUTH_PW'];
193 $encrypted = hash('whirlpool', trim($password));
195 // allow "user@server" login (but ignore 'server' part)
196 $at = strstr($user, "@", true);
201 // next code from mod/auth.php. needs better solution
205 'username' => trim($user),
206 'password' => trim($password),
207 'authenticated' => 0,
208 'user_record' => null,
212 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
213 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
214 * and later plugins should not interfere with an earlier one that succeeded.
216 call_hooks('authenticate', $addon_auth);
218 if (($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
219 $record = $addon_auth['user_record'];
221 // process normal login request
223 "SELECT * FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')
224 AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
229 if (DBM::is_result($r)) {
234 if ((! $record) || (! count($record))) {
235 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
236 header('WWW-Authenticate: Basic realm="Friendica"');
237 //header('HTTP/1.0 401 Unauthorized');
238 //die('This api requires login');
239 throw new UnauthorizedException("This API requires login");
242 authenticate_success($record);
244 $_SESSION["allow_api"] = true;
246 call_hooks('logged_in', $a->user);
250 * @brief Check HTTP method of called API
252 * API endpoints can define which HTTP method to accept when called.
253 * This function check the current HTTP method agains endpoint
256 * @param string $method Required methods, uppercase, separated by comma
259 function api_check_method($method)
261 if ($method == "*") {
264 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
268 * @brief Main API entry point
270 * Authenticate user, call registered API function, set HTTP headers
272 * @param object $a App
273 * @return string API call result
275 function api_call(App $a)
277 global $API, $called_api;
280 if (strpos($a->query_string, ".xml") > 0) {
283 if (strpos($a->query_string, ".json") > 0) {
286 if (strpos($a->query_string, ".rss") > 0) {
289 if (strpos($a->query_string, ".atom") > 0) {
294 foreach ($API as $p => $info) {
295 if (strpos($a->query_string, $p) === 0) {
296 if (!api_check_method($info['method'])) {
297 throw new MethodNotAllowedException();
300 $called_api = explode("/", $p);
301 //unset($_SERVER['PHP_AUTH_USER']);
303 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
304 if ($info['auth'] === true && api_user() === false) {
308 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
309 logger('API parameters: ' . print_r($_REQUEST, true));
311 $stamp = microtime(true);
312 $r = call_user_func($info['func'], $type);
313 $duration = (float) (microtime(true) - $stamp);
314 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
316 if (Config::get("system", "profiler")) {
317 $duration = microtime(true)-$a->performance["start"];
319 /// @TODO round() really everywhere?
321 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
322 "Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
323 round($a->performance["database"] - $a->performance["database_write"], 3),
324 round($a->performance["database_write"], 3),
325 round($a->performance["network"], 2),
326 round($a->performance["file"], 2),
327 round($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
333 if (Config::get("rendertime", "callstack")) {
334 $o = "Database Read:\n";
335 foreach ($a->callstack["database"] as $func => $time) {
336 $time = round($time, 3);
338 $o .= $func . ": " . $time . "\n";
341 $o .= "\nDatabase Write:\n";
342 foreach ($a->callstack["database_write"] as $func => $time) {
343 $time = round($time, 3);
345 $o .= $func . ": " . $time . "\n";
349 $o .= "\nNetwork:\n";
350 foreach ($a->callstack["network"] as $func => $time) {
351 $time = round($time, 3);
353 $o .= $func . ": " . $time . "\n";
356 logger($o, LOGGER_DEBUG);
362 * api function returned false withour throw an
363 * exception. This should not happend, throw a 500
365 throw new InternalServerErrorException();
370 header("Content-Type: text/xml");
374 header("Content-Type: application/json");
376 $json = json_encode($rr);
377 if (x($_GET, 'callback')) {
378 $json = $_GET['callback'] . "(" . $json . ")";
383 header("Content-Type: application/rss+xml");
384 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
387 header("Content-Type: application/atom+xml");
388 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
394 logger('API call not implemented: ' . $a->query_string);
395 throw new NotImplementedException();
396 } catch (HTTPException $e) {
397 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
398 return api_error($type, $e);
403 * @brief Format API error string
405 * @param string $type Return type (xml, json, rss, as)
406 * @param object $e HTTPException Error object
407 * @return strin error message formatted as $type
409 function api_error($type, $e)
413 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
414 /// @TODO: https://dev.twitter.com/overview/api/response-codes
416 $error = array("error" => $error,
417 "code" => $e->httpcode . " " . $e->httpdesc,
418 "request" => $a->query_string);
420 $ret = api_format_data('status', $type, array('status' => $error));
424 header("Content-Type: text/xml");
428 header("Content-Type: application/json");
429 return json_encode($ret);
432 header("Content-Type: application/rss+xml");
436 header("Content-Type: application/atom+xml");
443 * @brief Set values for RSS template
446 * @param array $arr Array to be passed to template
447 * @param array $user_info User info
449 * @todo find proper type-hints
451 function api_rss_extra(App $a, $arr, $user_info)
453 if (is_null($user_info)) {
454 $user_info = api_get_user($a);
457 $arr['$user'] = $user_info;
458 $arr['$rss'] = array(
459 'alternate' => $user_info['url'],
460 'self' => System::baseUrl() . "/" . $a->query_string,
461 'base' => System::baseUrl(),
462 'updated' => api_date(null),
463 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
464 'language' => $user_info['language'],
465 'logo' => System::baseUrl() . "/images/friendica-32.png",
473 * @brief Unique contact to contact url.
475 * @param int $id Contact id
476 * @return bool|string
477 * Contact url or False if contact id is unknown
479 function api_unique_id_to_url($id)
481 $r = dba::select('contact', array('url'), array('uid' => 0, 'id' => $id), array('limit' => 1));
483 if (DBM::is_result($r)) {
491 * @brief Get user info array.
493 * @param object $a App
494 * @param int|string $contact_id Contact ID or URL
495 * @param string $type Return type (for errors)
497 function api_get_user(App $a, $contact_id = null, $type = "json")
506 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
508 // Searching for contact URL
509 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
510 $user = dbesc(normalise_link($contact_id));
512 $extra_query = "AND `contact`.`nurl` = '%s' ";
513 if (api_user() !== false) {
514 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
518 // Searching for contact id with uid = 0
519 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
520 $user = dbesc(api_unique_id_to_url($contact_id));
523 throw new BadRequestException("User not found.");
527 $extra_query = "AND `contact`.`nurl` = '%s' ";
528 if (api_user() !== false) {
529 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
533 if (is_null($user) && x($_GET, 'user_id')) {
534 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
537 throw new BadRequestException("User not found.");
541 $extra_query = "AND `contact`.`nurl` = '%s' ";
542 if (api_user() !== false) {
543 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
546 if (is_null($user) && x($_GET, 'screen_name')) {
547 $user = dbesc($_GET['screen_name']);
549 $extra_query = "AND `contact`.`nick` = '%s' ";
550 if (api_user() !== false) {
551 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
555 if (is_null($user) && x($_GET, 'profileurl')) {
556 $user = dbesc(normalise_link($_GET['profileurl']));
558 $extra_query = "AND `contact`.`nurl` = '%s' ";
559 if (api_user() !== false) {
560 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
564 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
565 $argid = count($called_api);
566 list($user, $null) = explode(".", $a->argv[$argid]);
567 if (is_numeric($user)) {
568 $user = dbesc(api_unique_id_to_url($user));
575 $extra_query = "AND `contact`.`nurl` = '%s' ";
576 if (api_user() !== false) {
577 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
580 $user = dbesc($user);
582 $extra_query = "AND `contact`.`nick` = '%s' ";
583 if (api_user() !== false) {
584 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
589 logger("api_get_user: user ".$user, LOGGER_DEBUG);
592 if (api_user() === false) {
596 $user = $_SESSION['uid'];
597 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
601 logger('api_user: ' . $extra_query . ', user: ' . $user);
605 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
611 // Selecting the id by priority, friendica first
612 api_best_nickname($uinfo);
614 // if the contact wasn't found, fetch it from the contacts with uid = 0
615 if (!DBM::is_result($uinfo)) {
619 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
622 if (DBM::is_result($r)) {
623 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
625 // If no nick where given, extract it from the address
626 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
627 $r[0]['nick'] = api_get_nick($r[0]["url"]);
632 'id_str' => (string) $r[0]["id"],
633 'name' => $r[0]["name"],
634 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
635 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
636 'description' => $r[0]["about"],
637 'profile_image_url' => $r[0]["micro"],
638 'profile_image_url_https' => $r[0]["micro"],
639 'url' => $r[0]["url"],
640 'protected' => false,
641 'followers_count' => 0,
642 'friends_count' => 0,
644 'created_at' => api_date($r[0]["created"]),
645 'favourites_count' => 0,
647 'time_zone' => 'UTC',
648 'geo_enabled' => false,
650 'statuses_count' => 0,
652 'contributors_enabled' => false,
653 'is_translator' => false,
654 'is_translation_enabled' => false,
655 'following' => false,
656 'follow_request_sent' => false,
657 'statusnet_blocking' => false,
658 'notifications' => false,
659 'statusnet_profile_url' => $r[0]["url"],
661 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
663 'network' => $r[0]["network"],
668 throw new BadRequestException("User not found.");
672 if ($uinfo[0]['self']) {
673 if ($uinfo[0]['network'] == "") {
674 $uinfo[0]['network'] = NETWORK_DFRN;
678 "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
682 "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
686 /// @TODO old-lost code? (twice)
687 // Counting is deactivated by now, due to performance issues
688 // count public wall messages
689 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
690 // intval($uinfo[0]['uid'])
692 //$countitms = $r[0]['count'];
695 // Counting is deactivated by now, due to performance issues
696 //$r = q("SELECT count(*) as `count` FROM `item`
697 // WHERE `contact-id` = %d",
698 // intval($uinfo[0]['id'])
700 //$countitms = $r[0]['count'];
704 /// @TODO old-lost code? (twice)
706 // Counting is deactivated by now, due to performance issues
708 $r = q("SELECT count(*) as `count` FROM `contact`
709 WHERE `uid` = %d AND `rel` IN ( %d, %d )
710 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
711 intval($uinfo[0]['uid']),
712 intval(CONTACT_IS_SHARING),
713 intval(CONTACT_IS_FRIEND)
715 $countfriends = $r[0]['count'];
717 $r = q("SELECT count(*) as `count` FROM `contact`
718 WHERE `uid` = %d AND `rel` IN ( %d, %d )
719 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
720 intval($uinfo[0]['uid']),
721 intval(CONTACT_IS_FOLLOWER),
722 intval(CONTACT_IS_FRIEND)
724 $countfollowers = $r[0]['count'];
726 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
727 intval($uinfo[0]['uid'])
729 $starred = $r[0]['count'];
732 if (! $uinfo[0]['self']) {
742 // Add a nick if it isn't present there
743 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
744 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
747 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
749 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
752 'id' => intval($pcontact_id),
753 'id_str' => (string) intval($pcontact_id),
754 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
755 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
756 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
757 'description' => (($profile) ? $profile[0]['pdesc'] : null),
758 'profile_image_url' => $uinfo[0]['micro'],
759 'profile_image_url_https' => $uinfo[0]['micro'],
760 'url' => $uinfo[0]['url'],
761 'protected' => false,
762 'followers_count' => intval($countfollowers),
763 'friends_count' => intval($countfriends),
765 'created_at' => api_date($uinfo[0]['created']),
766 'favourites_count' => intval($starred),
768 'time_zone' => 'UTC',
769 'geo_enabled' => false,
771 'statuses_count' => intval($countitms),
773 'contributors_enabled' => false,
774 'is_translator' => false,
775 'is_translation_enabled' => false,
776 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
777 'follow_request_sent' => false,
778 'statusnet_blocking' => false,
779 'notifications' => false,
781 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
782 'statusnet_profile_url' => $uinfo[0]['url'],
783 'uid' => intval($uinfo[0]['uid']),
784 'cid' => intval($uinfo[0]['cid']),
785 'self' => $uinfo[0]['self'],
786 'network' => $uinfo[0]['network'],
793 * @brief return api-formatted array for item's author and owner
795 * @param object $a App
796 * @param array $item item from db
797 * @return array(array:author, array:owner)
799 function api_item_get_user(App $a, $item)
801 $status_user = api_get_user($a, $item["author-link"]);
803 $status_user["protected"] = (($item["allow_cid"] != "") ||
804 ($item["allow_gid"] != "") ||
805 ($item["deny_cid"] != "") ||
806 ($item["deny_gid"] != "") ||
809 if ($item['thr-parent'] == $item['uri']) {
810 $owner_user = api_get_user($a, $item["owner-link"]);
812 $owner_user = $status_user;
815 return (array($status_user, $owner_user));
819 * @brief walks recursively through an array with the possibility to change value and key
821 * @param array $array The array to walk through
822 * @param string $callback The callback function
824 * @return array the transformed array
826 function api_walk_recursive(array &$array, callable $callback)
828 $new_array = array();
830 foreach ($array as $k => $v) {
832 if ($callback($v, $k)) {
833 $new_array[$k] = api_walk_recursive($v, $callback);
836 if ($callback($v, $k)) {
847 * @brief Callback function to transform the array in an array that can be transformed in a XML file
849 * @param mixed $item Array item value
850 * @param string $key Array key
852 * @return boolean Should the array item be deleted?
854 function api_reformat_xml(&$item, &$key)
856 if (is_bool($item)) {
857 $item = ($item ? "true" : "false");
860 if (substr($key, 0, 10) == "statusnet_") {
861 $key = "statusnet:".substr($key, 10);
862 } elseif (substr($key, 0, 10) == "friendica_") {
863 $key = "friendica:".substr($key, 10);
865 /// @TODO old-lost code?
867 // $key = "default:".$key;
873 * @brief Creates the XML from a JSON style array
875 * @param array $data JSON style array
876 * @param string $root_element Name of the root element
878 * @return string The XML data
880 function api_create_xml($data, $root_element)
882 $childname = key($data);
883 $data2 = array_pop($data);
886 $namespaces = array("" => "http://api.twitter.com",
887 "statusnet" => "http://status.net/schema/api/1/",
888 "friendica" => "http://friendi.ca/schema/api/1/",
889 "georss" => "http://www.georss.org/georss");
891 /// @todo Auto detection of needed namespaces
892 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
893 $namespaces = array();
896 if (is_array($data2)) {
897 api_walk_recursive($data2, "api_reformat_xml");
904 foreach ($data2 as $item) {
905 $data4[$i++.":".$childname] = $item;
911 $data3 = array($root_element => $data2);
913 $ret = XML::fromArray($data3, $xml, false, $namespaces);
918 * @brief Formats the data according to the data type
920 * @param string $root_element Name of the root element
921 * @param string $type Return type (atom, rss, xml, json)
922 * @param array $data JSON style array
924 * @return (string|object) XML data or JSON data
926 function api_format_data($root_element, $type, $data)
934 $ret = api_create_xml($data, $root_element);
949 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
950 * returns a 401 status code and an error message if not.
951 * http://developer.twitter.com/doc/get/account/verify_credentials
953 function api_account_verify_credentials($type)
958 if (api_user() === false) {
959 throw new ForbiddenException();
962 unset($_REQUEST["user_id"]);
963 unset($_GET["user_id"]);
965 unset($_REQUEST["screen_name"]);
966 unset($_GET["screen_name"]);
968 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
970 $user_info = api_get_user($a);
972 // "verified" isn't used here in the standard
973 unset($user_info["verified"]);
975 // - Adding last status
977 $user_info["status"] = api_status_show("raw");
978 if (!count($user_info["status"])) {
979 unset($user_info["status"]);
981 unset($user_info["status"]["user"]);
985 // "uid" and "self" are only needed for some internal stuff, so remove it from here
986 unset($user_info["uid"]);
987 unset($user_info["self"]);
989 return api_format_data("user", $type, array('user' => $user_info));
992 /// @TODO move to top of file or somwhere better
993 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
996 * Get data from $_POST or $_GET
998 function requestdata($k)
1000 if (x($_POST, $k)) {
1009 /*Waitman Gobble Mod*/
1010 function api_statuses_mediap($type)
1014 if (api_user() === false) {
1015 logger('api_statuses_update: no user');
1016 throw new ForbiddenException();
1018 $user_info = api_get_user($a);
1020 $_REQUEST['type'] = 'wall';
1021 $_REQUEST['profile_uid'] = api_user();
1022 $_REQUEST['api_source'] = true;
1023 $txt = requestdata('status');
1024 /// @TODO old-lost code?
1025 //$txt = urldecode(requestdata('status'));
1027 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1028 $txt = html2bb_video($txt);
1029 $config = HTMLPurifier_Config::createDefault();
1030 $config->set('Cache.DefinitionImpl', null);
1031 $purifier = new HTMLPurifier($config);
1032 $txt = $purifier->purify($txt);
1034 $txt = html2bbcode($txt);
1036 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1038 // tell wall_upload function to return img info instead of echo
1039 $_REQUEST['hush'] = 'yeah';
1040 $bebop = wall_upload_post($a);
1042 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1043 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1046 // this should output the last post (the one we just posted).
1047 return api_status_show($type);
1050 /// @TODO move this to top of file or somewhere better!
1051 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1053 function api_statuses_update($type)
1058 if (api_user() === false) {
1059 logger('api_statuses_update: no user');
1060 throw new ForbiddenException();
1063 $user_info = api_get_user($a);
1065 // convert $_POST array items to the form we use for web posts.
1067 // logger('api_post: ' . print_r($_POST,true));
1069 if (requestdata('htmlstatus')) {
1070 $txt = requestdata('htmlstatus');
1071 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1072 $txt = html2bb_video($txt);
1074 $config = HTMLPurifier_Config::createDefault();
1075 $config->set('Cache.DefinitionImpl', null);
1077 $purifier = new HTMLPurifier($config);
1078 $txt = $purifier->purify($txt);
1080 $_REQUEST['body'] = html2bbcode($txt);
1083 $_REQUEST['body'] = requestdata('status');
1086 $_REQUEST['title'] = requestdata('title');
1088 $parent = requestdata('in_reply_to_status_id');
1090 // Twidere sends "-1" if it is no reply ...
1091 if ($parent == -1) {
1095 if (ctype_digit($parent)) {
1096 $_REQUEST['parent'] = $parent;
1098 $_REQUEST['parent_uri'] = $parent;
1101 if (requestdata('lat') && requestdata('long')) {
1102 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1104 $_REQUEST['profile_uid'] = api_user();
1107 $_REQUEST['type'] = 'net-comment';
1109 // Check for throttling (maximum posts per day, week and month)
1110 $throttle_day = Config::get('system', 'throttle_limit_day');
1111 if ($throttle_day > 0) {
1112 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1115 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1116 AND `created` > '%s' AND `id` = `parent`",
1121 if (DBM::is_result($r)) {
1122 $posts_day = $r[0]["posts_day"];
1127 if ($posts_day > $throttle_day) {
1128 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1129 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1130 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1134 $throttle_week = Config::get('system', 'throttle_limit_week');
1135 if ($throttle_week > 0) {
1136 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1139 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1140 AND `created` > '%s' AND `id` = `parent`",
1145 if (DBM::is_result($r)) {
1146 $posts_week = $r[0]["posts_week"];
1151 if ($posts_week > $throttle_week) {
1152 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1153 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1154 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1158 $throttle_month = Config::get('system', 'throttle_limit_month');
1159 if ($throttle_month > 0) {
1160 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1163 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1164 AND `created` > '%s' AND `id` = `parent`",
1169 if (DBM::is_result($r)) {
1170 $posts_month = $r[0]["posts_month"];
1175 if ($posts_month > $throttle_month) {
1176 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1177 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1178 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1182 $_REQUEST['type'] = 'wall';
1185 if (x($_FILES, 'media')) {
1186 // upload the image if we have one
1187 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1188 $media = wall_upload_post($a);
1189 if (strlen($media) > 0) {
1190 $_REQUEST['body'] .= "\n\n" . $media;
1194 // To-Do: Multiple IDs
1195 if (requestdata('media_ids')) {
1197 "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",
1198 intval(requestdata('media_ids')),
1201 if (DBM::is_result($r)) {
1202 $phototypes = Photo::supportedTypes();
1203 $ext = $phototypes[$r[0]['type']];
1204 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1205 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1209 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1211 $_REQUEST['api_source'] = true;
1213 if (!x($_REQUEST, "source")) {
1214 $_REQUEST["source"] = api_source();
1217 // call out normal post function
1220 // this should output the last post (the one we just posted).
1221 return api_status_show($type);
1224 /// @TODO move to top of file or somwhere better
1225 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1226 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1228 function api_media_upload($type)
1232 if (api_user() === false) {
1234 throw new ForbiddenException();
1237 $user_info = api_get_user($a);
1239 if (!x($_FILES, 'media')) {
1241 throw new BadRequestException("No media.");
1244 $media = wall_upload_post($a, false);
1247 throw new InternalServerErrorException();
1250 $returndata = array();
1251 $returndata["media_id"] = $media["id"];
1252 $returndata["media_id_string"] = (string)$media["id"];
1253 $returndata["size"] = $media["size"];
1254 $returndata["image"] = array("w" => $media["width"],
1255 "h" => $media["height"],
1256 "image_type" => $media["type"]);
1258 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1260 return array("media" => $returndata);
1263 /// @TODO move to top of file or somwhere better
1264 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1266 function api_status_show($type)
1270 $user_info = api_get_user($a);
1272 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1274 if ($type == "raw") {
1275 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1280 // get last public wall message
1284 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1285 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1286 AND `item`.`type` != 'activity' $privacy_sql
1287 ORDER BY `item`.`id` DESC
1289 intval($user_info['cid']),
1291 dbesc($user_info['url']),
1292 dbesc(normalise_link($user_info['url'])),
1293 dbesc($user_info['url']),
1294 dbesc(normalise_link($user_info['url']))
1297 if (DBM::is_result($lastwall)) {
1298 $lastwall = $lastwall[0];
1300 $in_reply_to = api_in_reply_to($lastwall);
1302 $converted = api_convert_item($lastwall);
1304 if ($type == "xml") {
1305 $geo = "georss:point";
1310 $status_info = array(
1311 'created_at' => api_date($lastwall['created']),
1312 'id' => intval($lastwall['id']),
1313 'id_str' => (string) $lastwall['id'],
1314 'text' => $converted["text"],
1315 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1316 'truncated' => false,
1317 'in_reply_to_status_id' => $in_reply_to['status_id'],
1318 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1319 'in_reply_to_user_id' => $in_reply_to['user_id'],
1320 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1321 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1322 'user' => $user_info,
1324 'coordinates' => "",
1326 'contributors' => "",
1327 'is_quote_status' => false,
1328 'retweet_count' => 0,
1329 'favorite_count' => 0,
1330 'favorited' => $lastwall['starred'] ? true : false,
1331 'retweeted' => false,
1332 'possibly_sensitive' => false,
1334 'statusnet_html' => $converted["html"],
1335 'statusnet_conversation_id' => $lastwall['parent'],
1338 if (count($converted["attachments"]) > 0) {
1339 $status_info["attachments"] = $converted["attachments"];
1342 if (count($converted["entities"]) > 0) {
1343 $status_info["entities"] = $converted["entities"];
1346 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1347 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1348 } elseif (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1349 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1352 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1353 unset($status_info["user"]["uid"]);
1354 unset($status_info["user"]["self"]);
1357 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1359 if ($type == "raw") {
1360 return $status_info;
1363 return api_format_data("statuses", $type, array('status' => $status_info));
1367 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1368 * The author's most recent status will be returned inline.
1369 * http://developer.twitter.com/doc/get/users/show
1371 function api_users_show($type)
1375 $user_info = api_get_user($a);
1379 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1380 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1381 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1382 AND `type`!='activity'
1383 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1387 dbesc(ACTIVITY_POST),
1388 intval($user_info['cid']),
1389 dbesc($user_info['url']),
1390 dbesc(normalise_link($user_info['url'])),
1391 dbesc($user_info['url']),
1392 dbesc(normalise_link($user_info['url']))
1395 if (DBM::is_result($lastwall)) {
1396 $lastwall = $lastwall[0];
1398 $in_reply_to = api_in_reply_to($lastwall);
1400 $converted = api_convert_item($lastwall);
1402 if ($type == "xml") {
1403 $geo = "georss:point";
1408 $user_info['status'] = array(
1409 'text' => $converted["text"],
1410 'truncated' => false,
1411 'created_at' => api_date($lastwall['created']),
1412 'in_reply_to_status_id' => $in_reply_to['status_id'],
1413 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1414 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1415 'id' => intval($lastwall['contact-id']),
1416 'id_str' => (string) $lastwall['contact-id'],
1417 'in_reply_to_user_id' => $in_reply_to['user_id'],
1418 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1419 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1421 'favorited' => $lastwall['starred'] ? true : false,
1422 'statusnet_html' => $converted["html"],
1423 'statusnet_conversation_id' => $lastwall['parent'],
1426 if (count($converted["attachments"]) > 0) {
1427 $user_info["status"]["attachments"] = $converted["attachments"];
1430 if (count($converted["entities"]) > 0) {
1431 $user_info["status"]["entities"] = $converted["entities"];
1434 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1435 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1438 if (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1439 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
1443 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1444 unset($user_info["uid"]);
1445 unset($user_info["self"]);
1447 return api_format_data("user", $type, array('user' => $user_info));
1450 /// @TODO move to top of file or somewhere better
1451 api_register_func('api/users/show', 'api_users_show');
1452 api_register_func('api/externalprofile/show', 'api_users_show');
1454 function api_users_search($type)
1458 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1460 $userlist = array();
1462 if (x($_GET, 'q')) {
1463 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1465 if (!DBM::is_result($r)) {
1466 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1469 if (DBM::is_result($r)) {
1471 foreach ($r as $user) {
1472 $user_info = api_get_user($a, $user["id"], "json");
1474 if ($type == "xml") {
1475 $userlist[$k++.":user"] = $user_info;
1477 $userlist[] = $user_info;
1480 $userlist = array("users" => $userlist);
1482 throw new BadRequestException("User not found.");
1485 throw new BadRequestException("User not found.");
1487 return api_format_data("users", $type, $userlist);
1490 /// @TODO move to top of file or somewhere better
1491 api_register_func('api/users/search', 'api_users_search');
1495 * http://developer.twitter.com/doc/get/statuses/home_timeline
1497 * TODO: Optional parameters
1498 * TODO: Add reply info
1500 function api_statuses_home_timeline($type)
1504 if (api_user() === false) {
1505 throw new ForbiddenException();
1508 unset($_REQUEST["user_id"]);
1509 unset($_GET["user_id"]);
1511 unset($_REQUEST["screen_name"]);
1512 unset($_GET["screen_name"]);
1514 $user_info = api_get_user($a);
1515 // get last newtork messages
1518 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1519 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1523 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1524 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1525 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1526 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1527 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1529 $start = $page * $count;
1533 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1535 if ($exclude_replies > 0) {
1536 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1538 if ($conversation_id > 0) {
1539 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1543 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1544 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1545 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1546 `contact`.`id` AS `cid`
1548 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1549 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1550 WHERE `item`.`uid` = %d AND `verb` = '%s'
1551 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1554 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1556 dbesc(ACTIVITY_POST),
1562 $ret = api_format_items($r, $user_info, false, $type);
1564 // Set all posts from the query above to seen
1566 foreach ($r as $item) {
1567 $idarray[] = intval($item["id"]);
1570 $idlist = implode(",", $idarray);
1572 if ($idlist != "") {
1573 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1576 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1580 $data = array('status' => $ret);
1584 $data = api_rss_extra($a, $data, $user_info);
1588 return api_format_data("statuses", $type, $data);
1591 /// @TODO move to top of file or somewhere better
1592 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1593 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1595 function api_statuses_public_timeline($type)
1599 if (api_user() === false) {
1600 throw new ForbiddenException();
1603 $user_info = api_get_user($a);
1604 // get last newtork messages
1607 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1608 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1612 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1613 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1614 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1615 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1616 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1618 $start = $page * $count;
1621 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1623 if ($exclude_replies > 0) {
1624 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1626 if ($conversation_id > 0) {
1627 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1631 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1632 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1633 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1634 `contact`.`id` AS `cid`,
1635 `user`.`nickname`, `user`.`hidewall`
1637 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1638 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1639 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1640 AND NOT `user`.`hidewall`
1641 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1642 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1643 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1644 AND NOT `item`.`private` AND `item`.`wall`
1647 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1648 dbesc(ACTIVITY_POST),
1654 $ret = api_format_items($r, $user_info, false, $type);
1656 $data = array('status' => $ret);
1660 $data = api_rss_extra($a, $data, $user_info);
1664 return api_format_data("statuses", $type, $data);
1667 /// @TODO move to top of file or somewhere better
1668 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1671 * @TODO nothing to say?
1673 function api_statuses_show($type)
1677 if (api_user() === false) {
1678 throw new ForbiddenException();
1681 $user_info = api_get_user($a);
1684 $id = intval($a->argv[3]);
1687 $id = intval($_REQUEST["id"]);
1692 $id = intval($a->argv[4]);
1695 logger('API: api_statuses_show: ' . $id);
1697 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1700 if ($conversation) {
1701 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1703 $sql_extra .= " AND `item`.`id` = %d";
1707 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1708 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1709 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1710 `contact`.`id` AS `cid`
1712 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1713 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1714 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1715 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1718 dbesc(ACTIVITY_POST),
1722 /// @TODO How about copying this to above methods which don't check $r ?
1723 if (!DBM::is_result($r)) {
1724 throw new BadRequestException("There is no status with this id.");
1727 $ret = api_format_items($r, $user_info, false, $type);
1729 if ($conversation) {
1730 $data = array('status' => $ret);
1731 return api_format_data("statuses", $type, $data);
1733 $data = array('status' => $ret[0]);
1734 return api_format_data("status", $type, $data);
1738 /// @TODO move to top of file or somewhere better
1739 api_register_func('api/statuses/show', 'api_statuses_show', true);
1742 * @TODO nothing to say?
1744 function api_conversation_show($type)
1748 if (api_user() === false) {
1749 throw new ForbiddenException();
1752 $user_info = api_get_user($a);
1755 $id = intval($a->argv[3]);
1756 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1757 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1761 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1762 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1764 $start = $page*$count;
1767 $id = intval($_REQUEST["id"]);
1772 $id = intval($a->argv[4]);
1775 logger('API: api_conversation_show: '.$id);
1777 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1778 if (DBM::is_result($r)) {
1779 $id = $r[0]["parent"];
1785 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1788 // Not sure why this query was so complicated. We should keep it here for a while,
1789 // just to make sure that we really don't need it.
1790 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1791 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1794 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1795 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1796 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1797 `contact`.`id` AS `cid`
1799 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1800 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1801 WHERE `item`.`parent` = %d AND `item`.`visible`
1802 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1803 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1804 AND `item`.`id`>%d $sql_extra
1805 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1806 intval($id), intval(api_user()),
1807 dbesc(ACTIVITY_POST),
1809 intval($start), intval($count)
1812 if (!DBM::is_result($r)) {
1813 throw new BadRequestException("There is no status with this id.");
1816 $ret = api_format_items($r, $user_info, false, $type);
1818 $data = array('status' => $ret);
1819 return api_format_data("statuses", $type, $data);
1822 /// @TODO move to top of file or somewhere better
1823 api_register_func('api/conversation/show', 'api_conversation_show', true);
1824 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1827 * @TODO nothing to say?
1829 function api_statuses_repeat($type)
1835 if (api_user() === false) {
1836 throw new ForbiddenException();
1839 $user_info = api_get_user($a);
1842 $id = intval($a->argv[3]);
1845 $id = intval($_REQUEST["id"]);
1850 $id = intval($a->argv[4]);
1853 logger('API: api_statuses_repeat: '.$id);
1856 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1857 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1858 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1859 `contact`.`id` AS `cid`
1861 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1862 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1863 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1864 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1865 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1867 AND `item`.`id`=%d",
1871 /// @TODO other style than above functions!
1872 if (DBM::is_result($r) && $r[0]['body'] != "") {
1873 if (strpos($r[0]['body'], "[/share]") !== false) {
1874 $pos = strpos($r[0]['body'], "[share");
1875 $post = substr($r[0]['body'], $pos);
1877 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1879 $post .= $r[0]['body'];
1880 $post .= "[/share]";
1882 $_REQUEST['body'] = $post;
1883 $_REQUEST['profile_uid'] = api_user();
1884 $_REQUEST['type'] = 'wall';
1885 $_REQUEST['api_source'] = true;
1887 if (!x($_REQUEST, "source")) {
1888 $_REQUEST["source"] = api_source();
1893 throw new ForbiddenException();
1896 // this should output the last post (the one we just posted).
1898 return api_status_show($type);
1901 /// @TODO move to top of file or somewhere better
1902 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1905 * @TODO nothing to say?
1907 function api_statuses_destroy($type)
1911 if (api_user() === false) {
1912 throw new ForbiddenException();
1915 $user_info = api_get_user($a);
1918 $id = intval($a->argv[3]);
1921 $id = intval($_REQUEST["id"]);
1926 $id = intval($a->argv[4]);
1929 logger('API: api_statuses_destroy: '.$id);
1931 $ret = api_statuses_show($type);
1933 drop_item($id, false);
1938 /// @TODO move to top of file or somewhere better
1939 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1942 * @TODO Nothing more than an URL to say?
1943 * http://developer.twitter.com/doc/get/statuses/mentions
1945 function api_statuses_mentions($type)
1949 if (api_user() === false) {
1950 throw new ForbiddenException();
1953 unset($_REQUEST["user_id"]);
1954 unset($_GET["user_id"]);
1956 unset($_REQUEST["screen_name"]);
1957 unset($_GET["screen_name"]);
1959 $user_info = api_get_user($a);
1960 // get last newtork messages
1964 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1965 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1969 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1970 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1971 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1973 $start = $page * $count;
1975 // Ugly code - should be changed
1976 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
1977 $myurl = substr($myurl, strpos($myurl, '://') + 3);
1978 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1979 $myurl = str_replace('www.', '', $myurl);
1980 $diasp_url = str_replace('/profile/', '/u/', $myurl);
1983 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1987 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1988 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1989 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1990 `contact`.`id` AS `cid`
1991 FROM `item` FORCE INDEX (`uid_id`)
1992 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1993 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1994 WHERE `item`.`uid` = %d AND `verb` = '%s'
1995 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1996 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1997 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2000 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2002 dbesc(ACTIVITY_POST),
2003 dbesc(protect_sprintf($myurl)),
2004 dbesc(protect_sprintf($myurl)),
2011 $ret = api_format_items($r, $user_info, false, $type);
2013 $data = array('status' => $ret);
2017 $data = api_rss_extra($a, $data, $user_info);
2021 return api_format_data("statuses", $type, $data);
2024 /// @TODO move to top of file or somewhere better
2025 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2026 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2028 function api_statuses_user_timeline($type)
2032 if (api_user() === false) {
2033 throw new ForbiddenException();
2036 $user_info = api_get_user($a);
2037 // get last network messages
2040 "api_statuses_user_timeline: api_user: ". api_user() .
2041 "\nuser_info: ".print_r($user_info, true) .
2042 "\n_REQUEST: ".print_r($_REQUEST, true),
2047 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2048 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2052 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2053 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2054 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
2055 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
2057 $start = $page * $count;
2060 if ($user_info['self'] == 1) {
2061 $sql_extra .= " AND `item`.`wall` = 1 ";
2064 if ($exclude_replies > 0) {
2065 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2067 if ($conversation_id > 0) {
2068 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2072 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2073 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2074 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2075 `contact`.`id` AS `cid`
2076 FROM `item` FORCE INDEX (`uid_contactid_id`)
2077 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2078 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2079 WHERE `item`.`uid` = %d AND `verb` = '%s'
2080 AND `item`.`contact-id` = %d
2081 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2084 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2086 dbesc(ACTIVITY_POST),
2087 intval($user_info['cid']),
2093 $ret = api_format_items($r, $user_info, true, $type);
2095 $data = array('status' => $ret);
2099 $data = api_rss_extra($a, $data, $user_info);
2103 return api_format_data("statuses", $type, $data);
2106 /// @TODO move to top of file or somwhere better
2107 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2110 * Star/unstar an item
2111 * param: id : id of the item
2113 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2115 function api_favorites_create_destroy($type)
2119 if (api_user() === false) {
2120 throw new ForbiddenException();
2123 // for versioned api.
2124 /// @TODO We need a better global soluton
2125 $action_argv_id = 2;
2126 if ($a->argv[1] == "1.1") {
2127 $action_argv_id = 3;
2130 if ($a->argc <= $action_argv_id) {
2131 throw new BadRequestException("Invalid request.");
2133 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2134 if ($a->argc == $action_argv_id + 2) {
2135 $itemid = intval($a->argv[$action_argv_id + 1]);
2137 /// @TODO use x() to check if _REQUEST contains 'id'
2138 $itemid = intval($_REQUEST['id']);
2141 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2143 if (!DBM::is_result($item) || count($item) == 0) {
2144 throw new BadRequestException("Invalid item.");
2149 $item[0]['starred'] = 1;
2152 $item[0]['starred'] = 0;
2155 throw new BadRequestException("Invalid action ".$action);
2158 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2160 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2163 throw new InternalServerErrorException("DB error");
2167 $user_info = api_get_user($a);
2168 $rets = api_format_items($item, $user_info, false, $type);
2171 $data = array('status' => $ret);
2175 $data = api_rss_extra($a, $data, $user_info);
2178 return api_format_data("status", $type, $data);
2181 /// @TODO move to top of file or somwhere better
2182 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2183 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2185 function api_favorites($type)
2191 if (api_user() === false) {
2192 throw new ForbiddenException();
2195 $called_api = array();
2197 $user_info = api_get_user($a);
2199 // in friendica starred item are private
2200 // return favorites only for self
2201 logger('api_favorites: self:' . $user_info['self']);
2203 if ($user_info['self'] == 0) {
2209 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2210 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2211 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2212 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2217 $start = $page*$count;
2220 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2224 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2225 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2226 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2227 `contact`.`id` AS `cid`
2228 FROM `item`, `contact`
2229 WHERE `item`.`uid` = %d
2230 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2231 AND `item`.`starred` = 1
2232 AND `contact`.`id` = `item`.`contact-id`
2233 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2236 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2243 $ret = api_format_items($r, $user_info, false, $type);
2246 $data = array('status' => $ret);
2250 $data = api_rss_extra($a, $data, $user_info);
2253 return api_format_data("statuses", $type, $data);
2256 /// @TODO move to top of file or somwhere better
2257 api_register_func('api/favorites', 'api_favorites', true);
2259 function api_format_messages($item, $recipient, $sender)
2261 // standard meta information
2263 'id' => $item['id'],
2264 'sender_id' => $sender['id'] ,
2266 'recipient_id' => $recipient['id'],
2267 'created_at' => api_date($item['created']),
2268 'sender_screen_name' => $sender['screen_name'],
2269 'recipient_screen_name' => $recipient['screen_name'],
2270 'sender' => $sender,
2271 'recipient' => $recipient,
2273 'friendica_seen' => $item['seen'],
2274 'friendica_parent_uri' => $item['parent-uri'],
2277 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2278 unset($ret["sender"]["uid"]);
2279 unset($ret["sender"]["self"]);
2280 unset($ret["recipient"]["uid"]);
2281 unset($ret["recipient"]["self"]);
2283 //don't send title to regular StatusNET requests to avoid confusing these apps
2284 if (x($_GET, 'getText')) {
2285 $ret['title'] = $item['title'];
2286 if ($_GET['getText'] == 'html') {
2287 $ret['text'] = bbcode($item['body'], false, false);
2288 } elseif ($_GET['getText'] == 'plain') {
2289 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2290 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2293 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2295 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2296 unset($ret['sender']);
2297 unset($ret['recipient']);
2303 function api_convert_item($item)
2305 $body = $item['body'];
2306 $attachments = api_get_attachments($body);
2308 // Workaround for ostatus messages where the title is identically to the body
2309 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2310 $statusbody = trim(html2plain($html, 0));
2312 // handle data: images
2313 $statusbody = api_format_items_embeded_images($item, $statusbody);
2315 $statustitle = trim($item['title']);
2317 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2318 $statustext = trim($statusbody);
2320 $statustext = trim($statustitle."\n\n".$statusbody);
2323 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2324 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2327 $statushtml = trim(bbcode($body, false, false));
2329 // Workaround for clients with limited HTML parser functionality
2330 $search = array("<br>", "<blockquote>", "</blockquote>",
2331 "<h1>", "</h1>", "<h2>", "</h2>",
2332 "<h3>", "</h3>", "<h4>", "</h4>",
2333 "<h5>", "</h5>", "<h6>", "</h6>");
2334 $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2335 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2336 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2337 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2338 $statushtml = str_replace($search, $replace, $statushtml);
2340 if ($item['title'] != "") {
2341 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2345 $oldtext = $statushtml;
2346 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2347 } while ($oldtext != $statushtml);
2349 if (substr($statushtml, 0, 4) == '<br>') {
2350 $statushtml = substr($statushtml, 4);
2353 if (substr($statushtml, 0, -4) == '<br>') {
2354 $statushtml = substr($statushtml, -4);
2357 // feeds without body should contain the link
2358 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2359 $statushtml .= bbcode($item['plink']);
2362 $entities = api_get_entitities($statustext, $body);
2365 "text" => $statustext,
2366 "html" => $statushtml,
2367 "attachments" => $attachments,
2368 "entities" => $entities
2372 function api_get_attachments(&$body)
2375 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2377 $URLSearchString = "^\[\]";
2378 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2384 $attachments = array();
2386 foreach ($images[1] as $image) {
2387 $imagedata = get_photo_info($image);
2390 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2394 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2395 foreach ($images[0] as $orig) {
2396 $body = str_replace($orig, "", $body);
2400 return $attachments;
2403 function api_get_entitities(&$text, $bbcode)
2407 * Links at the first character of the post
2412 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2414 if ($include_entities != "true") {
2415 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2417 foreach ($images[1] as $image) {
2418 $replace = proxy_url($image);
2419 $text = str_replace($image, $replace, $text);
2424 $bbcode = bb_CleanPictureLinks($bbcode);
2426 // Change pure links in text to bbcode uris
2427 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2429 $entities = array();
2430 $entities["hashtags"] = array();
2431 $entities["symbols"] = array();
2432 $entities["urls"] = array();
2433 $entities["user_mentions"] = array();
2435 $URLSearchString = "^\[\]";
2437 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2439 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2440 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2441 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2443 $bbcode = preg_replace(
2444 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2445 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2448 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2450 $bbcode = preg_replace(
2451 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2452 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2455 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2457 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2459 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2460 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2462 $ordered_urls = array();
2463 foreach ($urls[1] as $id => $url) {
2464 //$start = strpos($text, $url, $offset);
2465 $start = iconv_strpos($text, $url, 0, "UTF-8");
2466 if (!($start === false)) {
2467 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2471 ksort($ordered_urls);
2474 //foreach ($urls[1] AS $id=>$url) {
2475 foreach ($ordered_urls as $url) {
2476 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2477 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2479 $display_url = $url["title"];
2481 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2482 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2484 if (strlen($display_url) > 26)
2485 $display_url = substr($display_url, 0, 25)."…";
2488 //$start = strpos($text, $url, $offset);
2489 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2490 if (!($start === false)) {
2491 $entities["urls"][] = array("url" => $url["url"],
2492 "expanded_url" => $url["url"],
2493 "display_url" => $display_url,
2494 "indices" => array($start, $start+strlen($url["url"])));
2495 $offset = $start + 1;
2499 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2500 $ordered_images = array();
2501 foreach ($images[1] as $image) {
2502 //$start = strpos($text, $url, $offset);
2503 $start = iconv_strpos($text, $image, 0, "UTF-8");
2504 if (!($start === false))
2505 $ordered_images[$start] = $image;
2507 //$entities["media"] = array();
2510 foreach ($ordered_images as $url) {
2511 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2512 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2514 if (strlen($display_url) > 26)
2515 $display_url = substr($display_url, 0, 25)."…";
2517 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2518 if (!($start === false)) {
2519 $image = get_photo_info($url);
2521 // If image cache is activated, then use the following sizes:
2522 // thumb (150), small (340), medium (600) and large (1024)
2523 if (!Config::get("system", "proxy_disabled")) {
2524 $media_url = proxy_url($url);
2527 $scale = scale_image($image[0], $image[1], 150);
2528 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2530 if (($image[0] > 150) || ($image[1] > 150)) {
2531 $scale = scale_image($image[0], $image[1], 340);
2532 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2535 $scale = scale_image($image[0], $image[1], 600);
2536 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2538 if (($image[0] > 600) || ($image[1] > 600)) {
2539 $scale = scale_image($image[0], $image[1], 1024);
2540 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2544 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2547 $entities["media"][] = array(
2549 "id_str" => (string)$start+1,
2550 "indices" => array($start, $start+strlen($url)),
2551 "media_url" => normalise_link($media_url),
2552 "media_url_https" => $media_url,
2554 "display_url" => $display_url,
2555 "expanded_url" => $url,
2559 $offset = $start + 1;
2565 function api_format_items_embeded_images(&$item, $text)
2567 $text = preg_replace_callback(
2568 "|data:image/([^;]+)[^=]+=*|m",
2569 function ($match) use ($item) {
2570 return System::baseUrl()."/display/".$item['guid'];
2579 * @brief return <a href='url'>name</a> as array
2581 * @param string $txt text
2586 function api_contactlink_to_array($txt)
2589 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2590 if ($r && count($match)==3) {
2592 'name' => $match[2],
2606 * @brief return likes, dislikes and attend status for item
2608 * @param array $item array
2610 * likes => int count
2611 * dislikes => int count
2613 function api_format_items_activities(&$item, $type = "json")
2617 $activities = array(
2619 'dislike' => array(),
2620 'attendyes' => array(),
2621 'attendno' => array(),
2622 'attendmaybe' => array(),
2627 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2628 intval($item['uid']),
2632 foreach ($items as $i) {
2633 // not used as result should be structured like other user data
2634 //builtin_activity_puller($i, $activities);
2636 // get user data and add it to the array of the activity
2637 $user = api_get_user($a, $i['author-link']);
2638 switch ($i['verb']) {
2640 $activities['like'][] = $user;
2642 case ACTIVITY_DISLIKE:
2643 $activities['dislike'][] = $user;
2645 case ACTIVITY_ATTEND:
2646 $activities['attendyes'][] = $user;
2648 case ACTIVITY_ATTENDNO:
2649 $activities['attendno'][] = $user;
2651 case ACTIVITY_ATTENDMAYBE:
2652 $activities['attendmaybe'][] = $user;
2659 if ($type == "xml") {
2660 $xml_activities = array();
2661 foreach ($activities as $k => $v) {
2662 // change xml element from "like" to "friendica:like"
2663 $xml_activities["friendica:".$k] = $v;
2664 // add user data into xml output
2666 foreach ($v as $user)
2667 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2669 $activities = $xml_activities;
2677 * @brief return data from profiles
2679 * @param array $profile array containing data from db table 'profile'
2680 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2683 function api_format_items_profiles(&$profile = null, $type = "json")
2685 if ($profile != null) {
2686 $profile = array('profile_id' => $profile['id'],
2687 'profile_name' => $profile['profile-name'],
2688 'is_default' => $profile['is-default'] ? true : false,
2689 'hide_friends'=> $profile['hide-friends'] ? true : false,
2690 'profile_photo' => $profile['photo'],
2691 'profile_thumb' => $profile['thumb'],
2692 'publish' => $profile['publish'] ? true : false,
2693 'net_publish' => $profile['net-publish'] ? true : false,
2694 'description' => $profile['pdesc'],
2695 'date_of_birth' => $profile['dob'],
2696 'address' => $profile['address'],
2697 'city' => $profile['locality'],
2698 'region' => $profile['region'],
2699 'postal_code' => $profile['postal-code'],
2700 'country' => $profile['country-name'],
2701 'hometown' => $profile['hometown'],
2702 'gender' => $profile['gender'],
2703 'marital' => $profile['marital'],
2704 'marital_with' => $profile['with'],
2705 'marital_since' => $profile['howlong'],
2706 'sexual' => $profile['sexual'],
2707 'politic' => $profile['politic'],
2708 'religion' => $profile['religion'],
2709 'public_keywords' => $profile['pub_keywords'],
2710 'private_keywords' => $profile['prv_keywords'],
2711 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2712 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2713 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2714 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2715 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2716 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2717 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2718 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2719 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2720 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2721 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2722 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2723 'homepage' => $profile['homepage'],
2730 * @brief format items to be returned by api
2732 * @param array $r array of items
2733 * @param array $user_info
2734 * @param bool $filter_user filter items by $user_info
2736 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2742 foreach ($r as $item) {
2743 localize_item($item);
2744 list($status_user, $owner_user) = api_item_get_user($a, $item);
2746 // Look if the posts are matching if they should be filtered by user id
2747 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2751 $in_reply_to = api_in_reply_to($item);
2753 $converted = api_convert_item($item);
2755 if ($type == "xml") {
2756 $geo = "georss:point";
2762 'text' => $converted["text"],
2763 'truncated' => false,
2764 'created_at'=> api_date($item['created']),
2765 'in_reply_to_status_id' => $in_reply_to['status_id'],
2766 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2767 'source' => (($item['app']) ? $item['app'] : 'web'),
2768 'id' => intval($item['id']),
2769 'id_str' => (string) intval($item['id']),
2770 'in_reply_to_user_id' => $in_reply_to['user_id'],
2771 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2772 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2774 'favorited' => $item['starred'] ? true : false,
2775 'user' => $status_user ,
2776 'friendica_owner' => $owner_user,
2777 //'entities' => NULL,
2778 'statusnet_html' => $converted["html"],
2779 'statusnet_conversation_id' => $item['parent'],
2780 'friendica_activities' => api_format_items_activities($item, $type),
2783 if (count($converted["attachments"]) > 0) {
2784 $status["attachments"] = $converted["attachments"];
2787 if (count($converted["entities"]) > 0) {
2788 $status["entities"] = $converted["entities"];
2791 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
2792 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2793 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2794 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2798 // Retweets are only valid for top postings
2799 // It doesn't work reliable with the link if its a feed
2800 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2802 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
2805 if ($item["id"] == $item["parent"]) {
2806 $retweeted_item = api_share_as_retweet($item);
2807 if ($retweeted_item !== false) {
2808 $retweeted_status = $status;
2810 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
2811 } catch (BadRequestException $e) {
2812 // user not found. should be found?
2813 /// @todo check if the user should be always found
2814 $retweeted_status["user"] = array();
2817 $rt_converted = api_convert_item($retweeted_item);
2819 $retweeted_status['text'] = $rt_converted["text"];
2820 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2821 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2822 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2823 $status['retweeted_status'] = $retweeted_status;
2827 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2828 unset($status["user"]["uid"]);
2829 unset($status["user"]["self"]);
2831 if ($item["coord"] != "") {
2832 $coords = explode(' ', $item["coord"]);
2833 if (count($coords) == 2) {
2834 if ($type == "json")
2835 $status["geo"] = array('type' => 'Point',
2836 'coordinates' => array((float) $coords[0],
2837 (float) $coords[1]));
2838 else // Not sure if this is the official format - if someone founds a documentation we can check
2839 $status["georss:point"] = $item["coord"];
2847 function api_account_rate_limit_status($type)
2849 if ($type == "xml") {
2851 'remaining-hits' => '150',
2852 '@attributes' => array("type" => "integer"),
2853 'hourly-limit' => '150',
2854 '@attributes2' => array("type" => "integer"),
2855 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
2856 '@attributes3' => array("type" => "datetime"),
2857 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2858 '@attributes4' => array("type" => "integer"),
2862 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2863 'remaining_hits' => '150',
2864 'hourly_limit' => '150',
2865 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
2869 return api_format_data('hash', $type, array('hash' => $hash));
2872 /// @TODO move to top of file or somwhere better
2873 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
2875 function api_help_test($type)
2877 if ($type == 'xml') {
2883 return api_format_data('ok', $type, array("ok" => $ok));
2886 /// @TODO move to top of file or somwhere better
2887 api_register_func('api/help/test', 'api_help_test', false);
2889 function api_lists($type)
2892 /// @TODO $ret is not filled here?
2893 return api_format_data('lists', $type, array("lists_list" => $ret));
2896 /// @TODO move to top of file or somwhere better
2897 api_register_func('api/lists', 'api_lists', true);
2899 function api_lists_list($type)
2902 /// @TODO $ret is not filled here?
2903 return api_format_data('lists', $type, array("lists_list" => $ret));
2906 /// @TODO move to top of file or somwhere better
2907 api_register_func('api/lists/list', 'api_lists_list', true);
2910 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2911 * This function is deprecated by Twitter
2912 * returns: json, xml
2914 function api_statuses_f($type, $qtype)
2918 if (api_user() === false) {
2919 throw new ForbiddenException();
2922 $user_info = api_get_user($a);
2924 if (x($_GET, 'cursor') && $_GET['cursor']=='undefined') {
2925 /* this is to stop Hotot to load friends multiple times
2926 * I'm not sure if I'm missing return something or
2927 * is a bug in hotot. Workaround, meantime
2931 return array('$users' => $ret);*/
2935 if ($qtype == 'friends') {
2936 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2938 if ($qtype == 'followers') {
2939 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2942 // friends and followers only for self
2943 if ($user_info['self'] == 0) {
2944 $sql_extra = " AND false ";
2948 "SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra ORDER BY `nick`",
2953 foreach ($r as $cid) {
2954 $user = api_get_user($a, $cid['nurl']);
2955 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2956 unset($user["uid"]);
2957 unset($user["self"]);
2964 return array('user' => $ret);
2968 function api_statuses_friends($type)
2970 $data = api_statuses_f($type, "friends");
2971 if ($data === false) {
2974 return api_format_data("users", $type, $data);
2977 function api_statuses_followers($type)
2979 $data = api_statuses_f($type, "followers");
2980 if ($data === false) {
2983 return api_format_data("users", $type, $data);
2986 /// @TODO move to top of file or somewhere better
2987 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
2988 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
2990 function api_statusnet_config($type)
2994 $name = $a->config['sitename'];
2995 $server = $a->get_hostname();
2996 $logo = System::baseUrl() . '/images/friendica-64.png';
2997 $email = $a->config['admin_email'];
2998 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2999 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3000 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3001 if ($a->config['api_import_size']) {
3002 $texlimit = string($a->config['api_import_size']);
3004 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3005 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3008 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3009 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3010 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3011 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3012 'shorturllength' => '30',
3013 'friendica' => array(
3014 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3015 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3016 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3017 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3022 return api_format_data('config', $type, array('config' => $config));
3025 /// @TODO move to top of file or somewhere better
3026 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3027 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3029 function api_statusnet_version($type)
3032 $fake_statusnet_version = "0.9.7";
3034 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
3037 /// @TODO move to top of file or somewhere better
3038 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3039 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3042 * @todo use api_format_data() to return data
3044 function api_ff_ids($type,$qtype)
3049 throw new ForbiddenException();
3052 $user_info = api_get_user($a);
3054 if ($qtype == 'friends') {
3055 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3057 if ($qtype == 'followers') {
3058 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3061 if (!$user_info["self"]) {
3062 $sql_extra = " AND false ";
3065 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3068 "SELECT `pcontact`.`id` FROM `contact`
3069 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3070 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3074 if (!DBM::is_result($r)) {
3079 foreach ($r as $rr) {
3080 if ($stringify_ids) {
3083 $ids[] = intval($rr['id']);
3087 return api_format_data("ids", $type, array('id' => $ids));
3090 function api_friends_ids($type)
3092 return api_ff_ids($type, 'friends');
3095 function api_followers_ids($type)
3097 return api_ff_ids($type, 'followers');
3100 /// @TODO move to top of file or somewhere better
3101 api_register_func('api/friends/ids', 'api_friends_ids', true);
3102 api_register_func('api/followers/ids', 'api_followers_ids', true);
3104 function api_direct_messages_new($type)
3109 if (api_user() === false) throw new ForbiddenException();
3111 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) return;
3113 $sender = api_get_user($a);
3115 if ($_POST['screen_name']) {
3117 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3119 dbesc($_POST['screen_name'])
3122 // Selecting the id by priority, friendica first
3123 api_best_nickname($r);
3125 $recipient = api_get_user($a, $r[0]['nurl']);
3127 $recipient = api_get_user($a, $_POST['user_id']);
3132 if (x($_REQUEST, 'replyto')) {
3134 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3136 intval($_REQUEST['replyto'])
3138 $replyto = $r[0]['parent-uri'];
3139 $sub = $r[0]['title'];
3141 if (x($_REQUEST, 'title')) {
3142 $sub = $_REQUEST['title'];
3144 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3148 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3151 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3152 $ret = api_format_messages($r[0], $recipient, $sender);
3154 $ret = array("error"=>$id);
3157 $data = array('direct_message'=>$ret);
3162 $data = api_rss_extra($a, $data, $user_info);
3165 return api_format_data("direct-messages", $type, $data);
3169 /// @TODO move to top of file or somewhere better
3170 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3173 * @brief delete a direct_message from mail table through api
3175 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3178 function api_direct_messages_destroy($type)
3182 if (api_user() === false) {
3183 throw new ForbiddenException();
3187 $user_info = api_get_user($a);
3189 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3191 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3192 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3193 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3195 $uid = $user_info['uid'];
3196 // error if no id or parenturi specified (for clients posting parent-uri as well)
3197 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3198 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3199 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3202 // BadRequestException if no id specified (for clients using Twitter API)
3204 throw new BadRequestException('Message id not specified');
3207 // add parent-uri to sql command if specified by calling app
3208 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3210 // get data of the specified message id
3212 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3217 // error message if specified id is not in database
3218 if (!DBM::is_result($r)) {
3219 if ($verbose == "true") {
3220 $answer = array('result' => 'error', 'message' => 'message id not in database');
3221 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3223 /// @todo BadRequestException ok for Twitter API clients?
3224 throw new BadRequestException('message id not in database');
3229 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3234 if ($verbose == "true") {
3237 $answer = array('result' => 'ok', 'message' => 'message deleted');
3238 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3240 $answer = array('result' => 'error', 'message' => 'unknown error');
3241 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3244 /// @todo return JSON data like Twitter API not yet implemented
3248 /// @TODO move to top of file or somewhere better
3249 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3251 function api_direct_messages_box($type, $box, $verbose)
3255 if (api_user() === false) {
3256 throw new ForbiddenException();
3260 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3261 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3266 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3267 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3269 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3270 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3273 unset($_REQUEST["user_id"]);
3274 unset($_GET["user_id"]);
3276 unset($_REQUEST["screen_name"]);
3277 unset($_GET["screen_name"]);
3279 $user_info = api_get_user($a);
3280 $profile_url = $user_info["url"];
3283 $start = $page * $count;
3286 if ($box=="sentbox") {
3287 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3288 } elseif ($box == "conversation") {
3289 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3290 } elseif ($box == "all") {
3291 $sql_extra = "true";
3292 } elseif ($box == "inbox") {
3293 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3297 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3300 if ($user_id != "") {
3301 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3302 } elseif ($screen_name !="") {
3303 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3307 "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",
3313 if ($verbose == "true" && !DBM::is_result($r)) {
3314 $answer = array('result' => 'error', 'message' => 'no mails available');
3315 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3319 foreach ($r as $item) {
3320 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3321 $recipient = $user_info;
3322 $sender = api_get_user($a, normalise_link($item['contact-url']));
3323 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3324 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3325 $sender = $user_info;
3328 $ret[] = api_format_messages($item, $recipient, $sender);
3332 $data = array('direct_message' => $ret);
3336 $data = api_rss_extra($a, $data, $user_info);
3339 return api_format_data("direct-messages", $type, $data);
3342 function api_direct_messages_sentbox($type)
3344 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3345 return api_direct_messages_box($type, "sentbox", $verbose);
3348 function api_direct_messages_inbox($type)
3350 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3351 return api_direct_messages_box($type, "inbox", $verbose);
3354 function api_direct_messages_all($type)
3356 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3357 return api_direct_messages_box($type, "all", $verbose);
3360 function api_direct_messages_conversation($type)
3362 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3363 return api_direct_messages_box($type, "conversation", $verbose);
3366 /// @TODO move to top of file or somewhere better
3367 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3368 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3369 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3370 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3372 function api_oauth_request_token($type)
3375 $oauth = new FKOAuth1();
3376 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
3377 } catch (Exception $e) {
3378 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3385 function api_oauth_access_token($type)
3388 $oauth = new FKOAuth1();
3389 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
3390 } catch (Exception $e) {
3391 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3398 /// @TODO move to top of file or somewhere better
3399 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3400 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3404 * @brief delete a complete photoalbum with all containing photos from database through api
3406 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3409 function api_fr_photoalbum_delete($type)
3411 if (api_user() === false) {
3412 throw new ForbiddenException();
3415 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3417 // we do not allow calls without album string
3419 throw new BadRequestException("no albumname specified");
3421 // check if album is existing
3423 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3427 if (!DBM::is_result($r))
3428 throw new BadRequestException("album not available");
3430 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3431 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3432 foreach ($r as $rr) {
3434 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3435 intval(local_user()),
3436 dbesc($rr['resource-id'])
3439 if (!DBM::is_result($photo_item)) {
3440 throw new InternalServerErrorException("problem with deleting items occured");
3442 drop_item($photo_item[0]['id'], false);
3445 // now let's delete all photos from the album
3446 $result = dba::delete('photo', array('uid' => api_user(), 'album' => $album));
3448 // return success of deletion or error message
3450 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3451 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3453 throw new InternalServerErrorException("unknown error - deleting from database failed");
3458 * @brief update the name of the album for all photos of an album
3460 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3463 function api_fr_photoalbum_update($type)
3465 if (api_user() === false) {
3466 throw new ForbiddenException();
3469 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3470 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3472 // we do not allow calls without album string
3474 throw new BadRequestException("no albumname specified");
3476 if ($album_new == "") {
3477 throw new BadRequestException("no new albumname specified");
3479 // check if album is existing
3481 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3485 if (!DBM::is_result($r)) {
3486 throw new BadRequestException("album not available");
3488 // now let's update all photos to the albumname
3490 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3496 // return success of updating or error message
3498 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3499 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3501 throw new InternalServerErrorException("unknown error - updating in database failed");
3507 * @brief list all photos of the authenticated user
3509 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3512 function api_fr_photos_list($type)
3514 if (api_user() === false) {
3515 throw new ForbiddenException();
3518 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3519 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3520 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3521 intval(local_user())
3524 'image/jpeg' => 'jpg',
3525 'image/png' => 'png',
3526 'image/gif' => 'gif'
3528 $data = array('photo'=>array());
3529 if (DBM::is_result($r)) {
3530 foreach ($r as $rr) {
3532 $photo['id'] = $rr['resource-id'];
3533 $photo['album'] = $rr['album'];
3534 $photo['filename'] = $rr['filename'];
3535 $photo['type'] = $rr['type'];
3536 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3537 $photo['created'] = $rr['created'];
3538 $photo['edited'] = $rr['edited'];
3539 $photo['desc'] = $rr['desc'];
3541 if ($type == "xml") {
3542 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3544 $photo['thumb'] = $thumb;
3545 $data['photo'][] = $photo;
3549 return api_format_data("photos", $type, $data);
3553 * @brief upload a new photo or change an existing photo
3555 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3558 function api_fr_photo_create_update($type)
3560 if (api_user() === false) {
3561 throw new ForbiddenException();
3564 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3565 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3566 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3567 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3568 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3569 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3570 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3571 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3572 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3574 // do several checks on input parameters
3575 // we do not allow calls without album string
3576 if ($album == null) {
3577 throw new BadRequestException("no albumname specified");
3579 // if photo_id == null --> we are uploading a new photo
3580 if ($photo_id == null) {
3583 // error if no media posted in create-mode
3584 if (!x($_FILES, 'media')) {
3586 throw new BadRequestException("no media data submitted");
3589 // album_new will be ignored in create-mode
3594 // check if photo is existing in database
3596 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3601 if (!DBM::is_result($r)) {
3602 throw new BadRequestException("photo not available");
3606 // checks on acl strings provided by clients
3607 $acl_input_error = false;
3608 $acl_input_error |= check_acl_input($allow_cid);
3609 $acl_input_error |= check_acl_input($deny_cid);
3610 $acl_input_error |= check_acl_input($allow_gid);
3611 $acl_input_error |= check_acl_input($deny_gid);
3612 if ($acl_input_error) {
3613 throw new BadRequestException("acl data invalid");
3615 // now let's upload the new media in create-mode
3616 if ($mode == "create") {
3617 $media = $_FILES['media'];
3618 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3620 // return success of updating or error message
3621 if (!is_null($data)) {
3622 return api_format_data("photo_create", $type, $data);
3624 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3628 // now let's do the changes in update-mode
3629 if ($mode == "update") {
3632 if (!is_null($desc)) {
3633 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3636 if (!is_null($album_new)) {
3637 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3640 if (!is_null($allow_cid)) {
3641 $allow_cid = trim($allow_cid);
3642 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3645 if (!is_null($deny_cid)) {
3646 $deny_cid = trim($deny_cid);
3647 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3650 if (!is_null($allow_gid)) {
3651 $allow_gid = trim($allow_gid);
3652 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3655 if (!is_null($deny_gid)) {
3656 $deny_gid = trim($deny_gid);
3657 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3661 if ($sql_extra != "") {
3662 $nothingtodo = false;
3664 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3666 datetime_convert(), // update edited timestamp
3672 $nothingtodo = true;
3675 if (x($_FILES, 'media')) {
3676 $nothingtodo = false;
3677 $media = $_FILES['media'];
3678 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3679 if (!is_null($data)) {
3680 return api_format_data("photo_update", $type, $data);
3684 // return success of updating or error message
3686 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
3687 return api_format_data("photo_update", $type, array('$result' => $answer));
3690 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
3691 return api_format_data("photo_update", $type, array('$result' => $answer));
3693 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3696 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3701 * @brief delete a single photo from the database through api
3703 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3706 function api_fr_photo_delete($type)
3708 if (api_user() === false) {
3709 throw new ForbiddenException();
3712 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3714 // do several checks on input parameters
3715 // we do not allow calls without photo id
3716 if ($photo_id == null) {
3717 throw new BadRequestException("no photo_id specified");
3719 // check if photo is existing in database
3721 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3725 if (!DBM::is_result($r)) {
3726 throw new BadRequestException("photo not available");
3728 // now we can perform on the deletion of the photo
3729 $result = dba::delete('photo', array('uid' => api_user(), 'resource-id' => $photo_id));
3731 // return success of deletion or error message
3733 // retrieve the id of the parent element (the photo element)
3735 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3736 intval(local_user()),
3740 if (!DBM::is_result($photo_item)) {
3741 throw new InternalServerErrorException("problem with deleting items occured");
3743 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3744 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
3745 drop_item($photo_item[0]['id'], false);
3747 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
3748 return api_format_data("photo_delete", $type, array('$result' => $answer));
3750 throw new InternalServerErrorException("unknown error on deleting photo from database table");
3756 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3758 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3761 function api_fr_photo_detail($type)
3763 if (api_user() === false) {
3764 throw new ForbiddenException();
3766 if (!x($_REQUEST, 'photo_id')) {
3767 throw new BadRequestException("No photo id.");
3770 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3771 $photo_id = $_REQUEST['photo_id'];
3773 // prepare json/xml output with data from database for the requested photo
3774 $data = prepare_photo_data($type, $scale, $photo_id);
3776 return api_format_data("photo_detail", $type, $data);
3781 * @brief updates the profile image for the user (either a specified profile or the default profile)
3783 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3786 function api_account_update_profile_image($type)
3788 if (api_user() === false) {
3789 throw new ForbiddenException();
3792 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
3794 // error if image data is missing
3795 if (!x($_FILES, 'image')) {
3796 throw new BadRequestException("no media data submitted");
3799 // check if specified profile id is valid
3800 if ($profileid != 0) {
3802 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
3806 // error message if specified profile id is not in database
3807 if (!DBM::is_result($r)) {
3808 throw new BadRequestException("profile_id not available");
3810 $is_default_profile = $r['profile'];
3812 $is_default_profile = 1;
3815 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3817 if (x($_FILES, 'image')) {
3818 $media = $_FILES['image'];
3819 } elseif (x($_FILES, 'media')) {
3820 $media = $_FILES['media'];
3822 // save new profile image
3823 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
3826 if (is_array($media['type'])) {
3827 $filetype = $media['type'][0];
3829 $filetype = $media['type'];
3831 if ($filetype == "image/jpeg") {
3833 } elseif ($filetype == "image/png") {
3836 // change specified profile or all profiles to the new resource-id
3837 if ($is_default_profile) {
3839 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
3840 dbesc($data['photo']['id']),
3841 intval(local_user())
3845 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
3846 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
3847 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
3848 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
3849 intval(local_user())
3853 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
3854 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
3855 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
3856 intval($_REQUEST['profile']),
3857 intval(local_user())
3861 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
3862 // so that browsers will do a cache update unconditionally
3865 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
3866 dbesc(datetime_convert()),
3867 intval(local_user())
3870 // Update global directory in background
3871 //$user = api_get_user(get_app());
3872 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
3873 if ($url && strlen(Config::get('system', 'directory'))) {
3874 Worker::add(PRIORITY_LOW, "Directory", $url);
3877 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
3879 // output for client
3881 return api_account_verify_credentials($type);
3883 // SaveMediaToDatabase failed for some reason
3884 throw new InternalServerErrorException("image upload failed");
3888 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3889 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
3890 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
3891 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3892 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3893 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3894 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
3895 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3896 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3899 function check_acl_input($acl_string)
3901 if ($acl_string == null || $acl_string == " ") {
3904 $contact_not_found = false;
3906 // split <x><y><z> into array of cid's
3907 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3909 // check for each cid if it is available on server
3910 $cid_array = $array[0];
3911 foreach ($cid_array as $cid) {
3912 $cid = str_replace("<", "", $cid);
3913 $cid = str_replace(">", "", $cid);
3915 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3919 $contact_not_found |= !DBM::is_result($contact);
3921 return $contact_not_found;
3924 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)
3932 if (is_array($media)) {
3933 if (is_array($media['tmp_name'])) {
3934 $src = $media['tmp_name'][0];
3936 $src = $media['tmp_name'];
3938 if (is_array($media['name'])) {
3939 $filename = basename($media['name'][0]);
3941 $filename = basename($media['name']);
3943 if (is_array($media['size'])) {
3944 $filesize = intval($media['size'][0]);
3946 $filesize = intval($media['size']);
3948 if (is_array($media['type'])) {
3949 $filetype = $media['type'][0];
3951 $filetype = $media['type'];
3955 if ($filetype == "") {
3956 $filetype=guess_image_type($filename);
3958 $imagedata = getimagesize($src);
3960 $filetype = $imagedata['mime'];
3963 "File upload src: " . $src . " - filename: " . $filename .
3964 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG
3967 // check if there was a php upload error
3968 if ($filesize == 0 && $media['error'] == 1) {
3969 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3971 // check against max upload size within Friendica instance
3972 $maximagesize = Config::get('system', 'maximagesize');
3973 if (($maximagesize) && ($filesize > $maximagesize)) {
3974 $formattedBytes = formatBytes($maximagesize);
3975 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3978 // create Photo instance with the data of the image
3979 $imagedata = @file_get_contents($src);
3980 $ph = new Photo($imagedata, $filetype);
3981 if (! $ph->is_valid()) {
3982 throw new InternalServerErrorException("unable to process image data");
3985 // check orientation of image
3989 // check max length of images on server
3990 $max_length = Config::get('system', 'max_image_length');
3991 if (! $max_length) {
3992 $max_length = MAX_IMAGE_LENGTH;
3994 if ($max_length > 0) {
3995 $ph->scaleImage($max_length);
3996 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
3998 $width = $ph->getWidth();
3999 $height = $ph->getHeight();
4001 // create a new resource-id if not already provided
4002 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
4004 if ($mediatype == "photo") {
4005 // upload normal image (scales 0, 1, 2)
4006 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4008 $r =$ph->store(local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4010 logger("photo upload: image upload with scale 0 (original size) failed");
4012 if ($width > 640 || $height > 640) {
4013 $ph->scaleImage(640);
4014 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4016 logger("photo upload: image upload with scale 1 (640x640) failed");
4020 if ($width > 320 || $height > 320) {
4021 $ph->scaleImage(320);
4022 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4024 logger("photo upload: image upload with scale 2 (320x320) failed");
4027 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4028 } elseif ($mediatype == "profileimage") {
4029 // upload profile image (scales 4, 5, 6)
4030 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4032 if ($width > 175 || $height > 175) {
4033 $ph->scaleImage(175);
4034 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4036 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4040 if ($width > 80 || $height > 80) {
4041 $ph->scaleImage(80);
4042 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4044 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4048 if ($width > 48 || $height > 48) {
4049 $ph->scaleImage(48);
4050 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4052 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4056 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4060 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4061 if ($photo_id == null && $mediatype == "photo") {
4062 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4064 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4065 return prepare_photo_data($type, false, $hash);
4067 throw new InternalServerErrorException("image upload failed");
4071 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4073 // get data about the api authenticated user
4074 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4075 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4078 $arr['guid'] = get_guid(32);
4079 $arr['uid'] = intval(api_user());
4081 $arr['parent-uri'] = $uri;
4082 $arr['type'] = 'photo';
4084 $arr['resource-id'] = $hash;
4085 $arr['contact-id'] = $owner_record[0]['id'];
4086 $arr['owner-name'] = $owner_record[0]['name'];
4087 $arr['owner-link'] = $owner_record[0]['url'];
4088 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4089 $arr['author-name'] = $owner_record[0]['name'];
4090 $arr['author-link'] = $owner_record[0]['url'];
4091 $arr['author-avatar'] = $owner_record[0]['thumb'];
4093 $arr['allow_cid'] = $allow_cid;
4094 $arr['allow_gid'] = $allow_gid;
4095 $arr['deny_cid'] = $deny_cid;
4096 $arr['deny_gid'] = $deny_gid;
4097 $arr['last-child'] = 1;
4098 $arr['visible'] = $visibility;
4102 'image/jpeg' => 'jpg',
4103 'image/png' => 'png',
4104 'image/gif' => 'gif'
4107 // adds link to the thumbnail scale photo
4108 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4109 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4112 // do the magic for storing the item in the database and trigger the federation to other contacts
4116 function prepare_photo_data($type, $scale, $photo_id)
4118 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4119 $data_sql = ($scale === false ? "" : "data, ");
4121 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4122 // clients needs to convert this in their way for further processing
4124 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4125 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4126 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4127 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4129 intval(local_user()),
4135 'image/jpeg' => 'jpg',
4136 'image/png' => 'png',
4137 'image/gif' => 'gif'
4140 // prepare output data for photo
4141 if (DBM::is_result($r)) {
4142 $data = array('photo' => $r[0]);
4143 $data['photo']['id'] = $data['photo']['resource-id'];
4144 if ($scale !== false) {
4145 $data['photo']['data'] = base64_encode($data['photo']['data']);
4147 unset($data['photo']['datasize']); //needed only with scale param
4149 if ($type == "xml") {
4150 $data['photo']['links'] = array();
4151 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4152 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4154 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4157 $data['photo']['link'] = array();
4158 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4160 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4161 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4165 unset($data['photo']['resource-id']);
4166 unset($data['photo']['minscale']);
4167 unset($data['photo']['maxscale']);
4169 throw new NotFoundException();
4172 // retrieve item element for getting activities (like, dislike etc.) related to photo
4174 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4175 intval(local_user()),
4178 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4180 // retrieve comments on photo
4182 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4183 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4184 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4185 `contact`.`id` AS `cid`
4187 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4188 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4189 WHERE `item`.`parent` = %d AND `item`.`visible`
4190 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4191 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4192 intval($item[0]['parent']),
4194 dbesc(ACTIVITY_POST)
4197 // prepare output of comments
4198 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4199 $comments = array();
4200 if ($type == "xml") {
4202 foreach ($commentData as $comment) {
4203 $comments[$k++ . ":comment"] = $comment;
4206 foreach ($commentData as $comment) {
4207 $comments[] = $comment;
4210 $data['photo']['friendica_comments'] = $comments;
4212 // include info if rights on photo and rights on item are mismatching
4213 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4214 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4215 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4216 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4217 $data['photo']['rights_mismatch'] = $rights_mismatch;
4224 * Similar as /mod/redir.php
4225 * redirect to 'url' after dfrn auth
4227 * Why this when there is mod/redir.php already?
4228 * This use api_user() and api_login()
4231 * c_url: url of remote contact to auth to
4232 * url: string, url to redirect after auth
4234 function api_friendica_remoteauth()
4236 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4237 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4239 if ($url === '' || $c_url === '') {
4240 throw new BadRequestException("Wrong parameters.");
4243 $c_url = normalise_link($c_url);
4248 "SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4253 if ((! DBM::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4254 throw new BadRequestException("Unknown contact");
4259 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4261 if ($r[0]['duplex'] && $r[0]['issued-id']) {
4262 $orig_id = $r[0]['issued-id'];
4263 $dfrn_id = '1:' . $orig_id;
4265 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4266 $orig_id = $r[0]['dfrn-id'];
4267 $dfrn_id = '0:' . $orig_id;
4270 $sec = random_string();
4273 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4274 VALUES( %d, %s, '%s', '%s', %d )",
4282 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4283 $dest = (($url) ? '&destination_url=' . $url : '');
4285 $r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4286 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4287 . '&type=profile&sec=' . $sec . $dest . $quiet
4290 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4293 * @brief Return the item shared, if the item contains only the [share] tag
4295 * @param array $item Sharer item
4296 * @return array Shared item or false if not a reshare
4298 function api_share_as_retweet(&$item)
4300 $body = trim($item["body"]);
4302 if (Diaspora::isReshare($body, false)===false) {
4306 /// @TODO "$1" should maybe mean '$1' ?
4307 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4309 * Skip if there is no shared message in there
4310 * we already checked this in diaspora::isReshare()
4311 * but better one more than one less...
4313 if ($body == $attributes) {
4318 // build the fake reshared item
4319 $reshared_item = $item;
4322 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4323 if ($matches[1] != "") {
4324 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4327 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4328 if ($matches[1] != "") {
4329 $author = $matches[1];
4333 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4334 if ($matches[1] != "") {
4335 $profile = $matches[1];
4338 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4339 if ($matches[1] != "") {
4340 $profile = $matches[1];
4344 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4345 if ($matches[1] != "") {
4346 $avatar = $matches[1];
4349 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4350 if ($matches[1] != "") {
4351 $avatar = $matches[1];
4355 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4356 if ($matches[1] != "") {
4357 $link = $matches[1];
4360 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4361 if ($matches[1] != "") {
4362 $link = $matches[1];
4366 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4367 if ($matches[1] != "")
4368 $posted = $matches[1];
4370 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4371 if ($matches[1] != "") {
4372 $posted = $matches[1];
4375 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4377 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4381 $reshared_item["body"] = $shared_body;
4382 $reshared_item["author-name"] = $author;
4383 $reshared_item["author-link"] = $profile;
4384 $reshared_item["author-avatar"] = $avatar;
4385 $reshared_item["plink"] = $link;
4386 $reshared_item["created"] = $posted;
4387 $reshared_item["edited"] = $posted;
4389 return $reshared_item;
4393 function api_get_nick($profile)
4396 - remove trailing junk from profile url
4397 - pump.io check has to check the website
4403 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4404 dbesc(normalise_link($profile))
4407 if (DBM::is_result($r)) {
4408 $nick = $r[0]["nick"];
4413 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4414 dbesc(normalise_link($profile))
4417 if (DBM::is_result($r)) {
4418 $nick = $r[0]["nick"];
4423 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4424 if ($friendica != $profile) {
4430 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4431 if ($diaspora != $profile) {
4437 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4438 if ($twitter != $profile) {
4445 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4446 if ($StatusnetHost != $profile) {
4447 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4448 if ($StatusnetUser != $profile) {
4449 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4450 $user = json_decode($UserData);
4452 $nick = $user->screen_name;
4458 // To-Do: look at the page if its really a pumpio site
4459 //if (!$nick == "") {
4460 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4461 // if ($pumpio != $profile)
4463 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4474 function api_in_reply_to($item)
4476 $in_reply_to = array();
4478 $in_reply_to['status_id'] = null;
4479 $in_reply_to['user_id'] = null;
4480 $in_reply_to['status_id_str'] = null;
4481 $in_reply_to['user_id_str'] = null;
4482 $in_reply_to['screen_name'] = null;
4484 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4485 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4486 intval($item['uid']),
4487 dbesc($item['thr-parent']));
4489 if (DBM::is_result($r)) {
4490 $in_reply_to['status_id'] = intval($r[0]['id']);
4492 $in_reply_to['status_id'] = intval($item['parent']);
4495 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4497 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4498 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4499 WHERE `item`.`id` = %d LIMIT 1",
4500 intval($in_reply_to['status_id'])
4503 if (DBM::is_result($r)) {
4504 if ($r[0]['nick'] == "") {
4505 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4508 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4509 $in_reply_to['user_id'] = intval($r[0]['id']);
4510 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4513 // There seems to be situation, where both fields are identical:
4514 // https://github.com/friendica/friendica/issues/1010
4515 // This is a bugfix for that.
4516 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4517 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4518 $in_reply_to['status_id'] = null;
4519 $in_reply_to['user_id'] = null;
4520 $in_reply_to['status_id_str'] = null;
4521 $in_reply_to['user_id_str'] = null;
4522 $in_reply_to['screen_name'] = null;
4526 return $in_reply_to;
4529 function api_clean_plain_items($Text)
4531 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4533 $Text = bb_CleanPictureLinks($Text);
4534 $URLSearchString = "^\[\]";
4536 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
4538 if ($include_entities == "true") {
4539 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
4542 // Simplify "attachment" element
4543 $Text = api_clean_attachments($Text);
4549 * @brief Removes most sharing information for API text export
4551 * @param string $body The original body
4553 * @return string Cleaned body
4555 function api_clean_attachments($body)
4557 $data = get_attachment_data($body);
4564 if (isset($data["text"]))
4565 $body = $data["text"];
4567 if (($body == "") && (isset($data["title"])))
4568 $body = $data["title"];
4570 if (isset($data["url"]))
4571 $body .= "\n".$data["url"];
4573 $body .= $data["after"];
4578 function api_best_nickname(&$contacts)
4580 $best_contact = array();
4582 if (count($contact) == 0)
4585 foreach ($contacts as $contact)
4586 if ($contact["network"] == "") {
4587 $contact["network"] = "dfrn";
4588 $best_contact = array($contact);
4591 if (sizeof($best_contact) == 0)
4592 foreach ($contacts as $contact)
4593 if ($contact["network"] == "dfrn")
4594 $best_contact = array($contact);
4596 if (sizeof($best_contact) == 0)
4597 foreach ($contacts as $contact)
4598 if ($contact["network"] == "dspr")
4599 $best_contact = array($contact);
4601 if (sizeof($best_contact) == 0)
4602 foreach ($contacts as $contact)
4603 if ($contact["network"] == "stat")
4604 $best_contact = array($contact);
4606 if (sizeof($best_contact) == 0)
4607 foreach ($contacts as $contact)
4608 if ($contact["network"] == "pump")
4609 $best_contact = array($contact);
4611 if (sizeof($best_contact) == 0)
4612 foreach ($contacts as $contact)
4613 if ($contact["network"] == "twit")
4614 $best_contact = array($contact);
4616 if (sizeof($best_contact) == 1) {
4617 $contacts = $best_contact;
4619 $contacts = array($contacts[0]);
4623 // return all or a specified group of the user with the containing contacts
4624 function api_friendica_group_show($type)
4628 if (api_user() === false) throw new ForbiddenException();
4631 $user_info = api_get_user($a);
4632 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4633 $uid = $user_info['uid'];
4635 // get data of the specified group id or all groups if not specified
4638 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4642 // error message if specified gid is not in database
4643 if (!DBM::is_result($r))
4644 throw new BadRequestException("gid not available");
4647 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4652 // loop through all groups and retrieve all members for adding data in the user array
4653 foreach ($r as $rr) {
4654 $members = group_get_members($rr['id']);
4657 if ($type == "xml") {
4658 $user_element = "users";
4660 foreach ($members as $member) {
4661 $user = api_get_user($a, $member['nurl']);
4662 $users[$k++.":user"] = $user;
4665 $user_element = "user";
4666 foreach ($members as $member) {
4667 $user = api_get_user($a, $member['nurl']);
4671 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4673 return api_format_data("groups", $type, array('group' => $grps));
4675 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4678 // delete the specified group of the user
4679 function api_friendica_group_delete($type)
4683 if (api_user() === false) throw new ForbiddenException();
4686 $user_info = api_get_user($a);
4687 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4688 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4689 $uid = $user_info['uid'];
4691 // error if no gid specified
4692 if ($gid == 0 || $name == "")
4693 throw new BadRequestException('gid or name not specified');
4695 // get data of the specified group id
4697 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
4701 // error message if specified gid is not in database
4702 if (!DBM::is_result($r))
4703 throw new BadRequestException('gid not available');
4705 // get data of the specified group id and group name
4707 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
4712 // error message if specified gid is not in database
4713 if (!DBM::is_result($rname))
4714 throw new BadRequestException('wrong group name');
4717 $ret = group_rmv($uid, $name);
4720 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
4721 return api_format_data("group_delete", $type, array('result' => $success));
4723 throw new BadRequestException('other API error');
4726 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4729 // create the specified group with the posted array of contacts
4730 function api_friendica_group_create($type)
4734 if (api_user() === false) throw new ForbiddenException();
4737 $user_info = api_get_user($a);
4738 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4739 $uid = $user_info['uid'];
4740 $json = json_decode($_POST['json'], true);
4741 $users = $json['user'];
4743 // error if no name specified
4745 throw new BadRequestException('group name not specified');
4747 // get data of the specified group name
4749 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
4753 // error message if specified group name already exists
4754 if (DBM::is_result($rname))
4755 throw new BadRequestException('group name already exists');
4757 // check if specified group name is a deleted group
4759 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
4763 // error message if specified group name already exists
4764 if (DBM::is_result($rname))
4765 $reactivate_group = true;
4768 $ret = group_add($uid, $name);
4770 $gid = group_byname($uid, $name);
4772 throw new BadRequestException('other API error');
4776 $erroraddinguser = false;
4777 $errorusers = array();
4778 foreach ($users as $user) {
4779 $cid = $user['cid'];
4780 // check if user really exists as contact
4782 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4786 if (count($contact))
4787 $result = group_add_member($uid, $name, $cid, $gid);
4789 $erroraddinguser = true;
4790 $errorusers[] = $cid;
4794 // return success message incl. missing users in array
4795 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
4796 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4797 return api_format_data("group_create", $type, array('result' => $success));
4799 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4802 // update the specified group with the posted array of contacts
4803 function api_friendica_group_update($type)
4807 if (api_user() === false) throw new ForbiddenException();
4810 $user_info = api_get_user($a);
4811 $uid = $user_info['uid'];
4812 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4813 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4814 $json = json_decode($_POST['json'], true);
4815 $users = $json['user'];
4817 // error if no name specified
4819 throw new BadRequestException('group name not specified');
4821 // error if no gid specified
4823 throw new BadRequestException('gid not specified');
4826 $members = group_get_members($gid);
4827 foreach ($members as $member) {
4828 $cid = $member['id'];
4829 foreach ($users as $user) {
4830 $found = ($user['cid'] == $cid ? true : false);
4833 $ret = group_rmv_member($uid, $name, $cid);
4838 $erroraddinguser = false;
4839 $errorusers = array();
4840 foreach ($users as $user) {
4841 $cid = $user['cid'];
4842 // check if user really exists as contact
4844 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4849 if (count($contact)) {
4850 $result = group_add_member($uid, $name, $cid, $gid);
4852 $erroraddinguser = true;
4853 $errorusers[] = $cid;
4857 // return success message incl. missing users in array
4858 $status = ($erroraddinguser ? "missing user" : "ok");
4859 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4860 return api_format_data("group_update", $type, array('result' => $success));
4863 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4865 function api_friendica_activity($type)
4869 if (api_user() === false) throw new ForbiddenException();
4870 $verb = strtolower($a->argv[3]);
4871 $verb = preg_replace("|\..*$|", "", $verb);
4873 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4875 $res = do_like($id, $verb);
4878 if ($type == "xml") {
4883 return api_format_data('ok', $type, array('ok' => $ok));
4885 throw new BadRequestException('Error adding activity');
4889 /// @TODO move to top of file or somwhere better
4890 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
4891 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
4892 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
4893 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
4894 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4895 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
4896 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
4897 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
4898 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
4899 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4902 * @brief Returns notifications
4904 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4907 function api_friendica_notification($type)
4911 if (api_user() === false) throw new ForbiddenException();
4912 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
4913 $nm = new NotificationsManager();
4915 $notes = $nm->getAll(array(), "+seen -date", 50);
4917 if ($type == "xml") {
4918 $xmlnotes = array();
4919 foreach ($notes as $note)
4920 $xmlnotes[] = array("@attributes" => $note);
4925 return api_format_data("notes", $type, array('note' => $notes));
4929 * @brief Set notification as seen and returns associated item (if possible)
4931 * POST request with 'id' param as notification id
4933 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4936 function api_friendica_notification_seen($type)
4940 if (api_user() === false) throw new ForbiddenException();
4941 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
4943 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
4945 $nm = new NotificationsManager();
4946 $note = $nm->getByID($id);
4947 if (is_null($note)) throw new BadRequestException("Invalid argument");
4949 $nm->setSeen($note);
4950 if ($note['otype']=='item') {
4951 // would be really better with an ItemsManager and $im->getByID() :-P
4953 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
4954 intval($note['iid']),
4955 intval(local_user())
4958 // we found the item, return it to the user
4959 $user_info = api_get_user($a);
4960 $ret = api_format_items($r, $user_info, false, $type);
4961 $data = array('status' => $ret);
4962 return api_format_data("status", $type, $data);
4964 // the item can't be found, but we set the note as seen, so we count this as a success
4966 return api_format_data('result', $type, array('result' => "success"));
4969 /// @TODO move to top of file or somwhere better
4970 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4971 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
4974 * @brief update a direct_message to seen state
4976 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4977 * @return string (success result=ok, error result=error with error message)
4979 function api_friendica_direct_messages_setseen($type)
4982 if (api_user() === false) {
4983 throw new ForbiddenException();
4987 $user_info = api_get_user($a);
4988 $uid = $user_info['uid'];
4989 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4991 // return error if id is zero
4993 $answer = array('result' => 'error', 'message' => 'message id not specified');
4994 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4997 // get data of the specified message id
4999 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5004 // error message if specified id is not in database
5005 if (!DBM::is_result($r)) {
5006 $answer = array('result' => 'error', 'message' => 'message id not in database');
5007 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5010 // update seen indicator
5012 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5019 $answer = array('result' => 'ok', 'message' => 'message set to seen');
5020 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
5022 $answer = array('result' => 'error', 'message' => 'unknown error');
5023 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5027 /// @TODO move to top of file or somwhere better
5028 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5031 * @brief search for direct_messages containing a searchstring through api
5033 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5034 * @return string (success: success=true if found and search_result contains found messages
5035 * success=false if nothing was found, search_result='nothing found',
5036 * error: result=error with error message)
5038 function api_friendica_direct_messages_search($type)
5042 if (api_user() === false) {
5043 throw new ForbiddenException();
5047 $user_info = api_get_user($a);
5048 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5049 $uid = $user_info['uid'];
5051 // error if no searchstring specified
5052 if ($searchstring == "") {
5053 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
5054 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
5057 // get data for the specified searchstring
5059 "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",
5061 dbesc('%'.$searchstring.'%')
5064 $profile_url = $user_info["url"];
5066 // message if nothing was found
5067 if (!DBM::is_result($r)) {
5068 $success = array('success' => false, 'search_results' => 'problem with query');
5069 } elseif (count($r) == 0) {
5070 $success = array('success' => false, 'search_results' => 'nothing found');
5073 foreach ($r as $item) {
5074 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5075 $recipient = $user_info;
5076 $sender = api_get_user($a, normalise_link($item['contact-url']));
5077 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5078 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5079 $sender = $user_info;
5082 $ret[] = api_format_messages($item, $recipient, $sender);
5084 $success = array('success' => true, 'search_results' => $ret);
5087 return api_format_data("direct_message_search", $type, array('$result' => $success));
5090 /// @TODO move to top of file or somwhere better
5091 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5094 * @brief return data of all the profiles a user has to the client
5096 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5099 function api_friendica_profile_show($type)
5103 if (api_user() === false) {
5104 throw new ForbiddenException();
5108 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5110 // retrieve general information about profiles for user
5111 $multi_profiles = feature_enabled(api_user(), 'multi_profiles');
5112 $directory = Config::get('system', 'directory');
5114 // get data of the specified profile id or all profiles of the user if not specified
5115 if ($profileid != 0) {
5117 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5122 // error message if specified gid is not in database
5123 if (!DBM::is_result($r)) {
5124 throw new BadRequestException("profile_id not available");
5128 "SELECT * FROM `profile` WHERE `uid` = %d",
5132 // loop through all returned profiles and retrieve data and users
5134 foreach ($r as $rr) {
5135 $profile = api_format_items_profiles($rr, $type);
5137 // select all users from contact table, loop and prepare standard return for user data
5140 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5142 intval($rr['profile_id'])
5145 foreach ($r as $rr) {
5146 $user = api_get_user($a, $rr['nurl']);
5147 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5149 $profile['users'] = $users;
5151 // add prepared profile data to array for final return
5152 if ($type == "xml") {
5153 $profiles[$k++ . ":profile"] = $profile;
5155 $profiles[] = $profile;
5159 // return settings, authenticated user and profiles data
5160 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5162 $result = array('multi_profiles' => $multi_profiles ? true : false,
5163 'global_dir' => $directory,
5164 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5165 'profiles' => $profiles);
5166 return api_format_data("friendica_profiles", $type, array('$result' => $result));
5168 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5171 @TODO Maybe open to implement?
5173 [pagename] => api/1.1/statuses/lookup.json
5174 [id] => 605138389168451584
5175 [include_cards] => true
5176 [cards_platform] => Android-12
5177 [include_entities] => true
5178 [include_my_retweet] => 1
5180 [include_reply_count] => true
5181 [include_descendent_reply_count] => true
5185 Not implemented by now:
5186 statuses/retweets_of_me
5191 account/update_location
5192 account/update_profile_background_image
5195 friendica/profile/update
5196 friendica/profile/create
5197 friendica/profile/delete
5199 Not implemented in status.net:
5200 statuses/retweeted_to_me
5201 statuses/retweeted_by_me
5202 direct_messages/destroy
5204 account/update_delivery_device
5205 notifications/follow