3 * @file include/api.php
\r
4 * Friendica implementation of statusnet/twitter API
\r
6 * @todo Automatically detect if incoming data is HTML or BBCode
\r
9 use \Friendica\Core\Config;
\r
11 require_once 'include/HTTPExceptions.php';
\r
12 require_once 'include/bbcode.php';
\r
13 require_once 'include/datetime.php';
\r
14 require_once 'include/conversation.php';
\r
15 require_once 'include/oauth.php';
\r
16 require_once 'include/html2plain.php';
\r
17 require_once 'mod/share.php';
\r
18 require_once 'include/Photo.php';
\r
19 require_once 'mod/item.php';
\r
20 require_once 'include/security.php';
\r
21 require_once 'include/contact_selectors.php';
\r
22 require_once 'include/html2bbcode.php';
\r
23 require_once 'mod/wall_upload.php';
\r
24 require_once 'mod/proxy.php';
\r
25 require_once 'include/message.php';
\r
26 require_once 'include/group.php';
\r
27 require_once 'include/like.php';
\r
28 require_once 'include/NotificationsManager.php';
\r
29 require_once 'include/plaintext.php';
\r
30 require_once 'include/xml.php';
\r
32 define('API_METHOD_ANY', '*');
\r
33 define('API_METHOD_GET', 'GET');
\r
34 define('API_METHOD_POST', 'POST,PUT');
\r
35 define('API_METHOD_DELETE', 'POST,DELETE');
\r
40 /// @TODO Fix intending
\r
42 * @brief Auth API user
\r
44 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
\r
45 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
\r
46 * into a page, and visitors will post something without noticing it).
\r
48 function api_user() {
\r
49 if (x($_SESSION, 'allow_api')) {
\r
50 return local_user();
\r
57 * @brief Get source name from API client
\r
59 * Clients can send 'source' parameter to be show in post metadata
\r
60 * as "sent via <source>".
\r
61 * Some clients doesn't send a source param, we support ones we know
\r
62 * (only Twidere, atm)
\r
65 * Client source name, default to "api" if unset/unknown
\r
67 function api_source() {
\r
68 if (requestdata('source')) {
\r
69 return requestdata('source');
\r
72 // Support for known clients that doesn't send a source name
\r
73 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
\r
77 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
\r
83 * @brief Format date for API
\r
85 * @param string $str Source date, as UTC
\r
86 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
\r
88 function api_date($str) {
\r
89 // Wed May 23 06:01:13 +0000 2007
\r
90 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
\r
94 * @brief Register API endpoint
\r
96 * Register a function to be the endpont for defined API path.
\r
98 * @param string $path API URL path, relative to App::get_baseurl()
\r
99 * @param string $func Function name to call on path request
\r
100 * @param bool $auth API need logged user
\r
101 * @param string $method HTTP method reqiured to call this endpoint.
\r
103 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
\r
104 * Default to API_METHOD_ANY
\r
106 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY) {
\r
109 $API[$path] = array(
\r
112 'method' => $method,
\r
115 // Workaround for hotot
\r
116 $path = str_replace("api/", "api/1.1/", $path);
\r
118 $API[$path] = array(
\r
121 'method' => $method,
\r
126 * @brief Login API user
\r
128 * Log in user via OAuth1 or Simple HTTP Auth.
\r
129 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
\r
132 * @hook 'authenticate'
\r
133 * array $addon_auth
\r
134 * 'username' => username from login form
\r
135 * 'password' => password from login form
\r
136 * 'authenticated' => return status,
\r
137 * 'user_record' => return authenticated user record
\r
138 * @hook 'logged_in'
\r
139 * array $user logged user record
\r
141 function api_login(App $a) {
\r
142 // login with oauth
\r
144 $oauth = new FKOAuth1();
\r
145 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
\r
146 if (!is_null($token)) {
\r
147 $oauth->loginUser($token->uid);
\r
148 call_hooks('logged_in', $a->user);
\r
151 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
\r
152 var_dump($consumer, $token);
\r
154 } catch (Exception $e) {
\r
158 // workaround for HTTP-auth in CGI mode
\r
159 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
\r
160 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
\r
161 if (strlen($userpass)) {
\r
162 list($name, $password) = explode(':', $userpass);
\r
163 $_SERVER['PHP_AUTH_USER'] = $name;
\r
164 $_SERVER['PHP_AUTH_PW'] = $password;
\r
168 if (!x($_SERVER, 'PHP_AUTH_USER')) {
\r
169 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
\r
170 header('WWW-Authenticate: Basic realm="Friendica"');
\r
171 throw new UnauthorizedException("This API requires login");
\r
174 $user = $_SERVER['PHP_AUTH_USER'];
\r
175 $password = $_SERVER['PHP_AUTH_PW'];
\r
176 $encrypted = hash('whirlpool', trim($password));
\r
178 // allow "user@server" login (but ignore 'server' part)
\r
179 $at = strstr($user, "@", true);
\r
184 // next code from mod/auth.php. needs better solution
\r
187 $addon_auth = array(
\r
188 'username' => trim($user),
\r
189 'password' => trim($password),
\r
190 'authenticated' => 0,
\r
191 'user_record' => null,
\r
195 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
\r
196 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
\r
197 * and later plugins should not interfere with an earlier one that succeeded.
\r
199 call_hooks('authenticate', $addon_auth);
\r
201 if (($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
\r
202 $record = $addon_auth['user_record'];
\r
204 // process normal login request
\r
205 $r = q("SELECT * FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')
\r
206 AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
\r
207 dbesc(trim($user)),
\r
208 dbesc(trim($user)),
\r
211 if (dbm::is_result($r)) {
\r
216 if ((! $record) || (! count($record))) {
\r
217 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
\r
218 header('WWW-Authenticate: Basic realm="Friendica"');
\r
219 //header('HTTP/1.0 401 Unauthorized');
\r
220 //die('This api requires login');
\r
221 throw new UnauthorizedException("This API requires login");
\r
224 authenticate_success($record);
\r
226 $_SESSION["allow_api"] = true;
\r
228 call_hooks('logged_in', $a->user);
\r
233 * @brief Check HTTP method of called API
\r
235 * API endpoints can define which HTTP method to accept when called.
\r
236 * This function check the current HTTP method agains endpoint
\r
237 * registered method.
\r
239 * @param string $method Required methods, uppercase, separated by comma
\r
242 function api_check_method($method) {
\r
243 if ($method == "*") {
\r
246 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
\r
250 * @brief Main API entry point
\r
252 * Authenticate user, call registered API function, set HTTP headers
\r
255 * @return string API call result
\r
257 function api_call(App $a) {
\r
258 global $API, $called_api;
\r
261 if (strpos($a->query_string, ".xml") > 0) {
\r
264 if (strpos($a->query_string, ".json") > 0) {
\r
267 if (strpos($a->query_string, ".rss") > 0) {
\r
270 if (strpos($a->query_string, ".atom") > 0) {
\r
275 foreach ($API as $p => $info) {
\r
276 if (strpos($a->query_string, $p) === 0) {
\r
277 if (!api_check_method($info['method'])) {
\r
278 throw new MethodNotAllowedException();
\r
281 $called_api = explode("/", $p);
\r
282 //unset($_SERVER['PHP_AUTH_USER']);
\r
284 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
\r
285 if ($info['auth'] === true && api_user() === false) {
\r
289 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
\r
290 logger('API parameters: ' . print_r($_REQUEST, true));
\r
292 $stamp = microtime(true);
\r
293 $r = call_user_func($info['func'], $type);
\r
294 $duration = (float) (microtime(true) - $stamp);
\r
295 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
\r
297 if (get_config("system", "profiler")) {
\r
298 $duration = microtime(true)-$a->performance["start"];
\r
300 /// @TODO round() really everywhere?
\r
301 logger(parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf("Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
\r
302 round($a->performance["database"] - $a->performance["database_write"], 3),
\r
303 round($a->performance["database_write"], 3),
\r
304 round($a->performance["network"], 2),
\r
305 round($a->performance["file"], 2),
\r
306 round($duration - ($a->performance["database"] + $a->performance["network"]
\r
307 + $a->performance["file"]), 2),
\r
308 round($duration, 2)),
\r
312 if (get_config("rendertime", "callstack")) {
\r
313 $o = "Database Read:\n";
\r
314 foreach ($a->callstack["database"] AS $func => $time) {
\r
315 $time = round($time, 3);
\r
317 $o .= $func . ": " . $time . "\n";
\r
320 $o .= "\nDatabase Write:\n";
\r
321 foreach ($a->callstack["database_write"] AS $func => $time) {
\r
322 $time = round($time, 3);
\r
324 $o .= $func . ": " . $time . "\n";
\r
328 $o .= "\nNetwork:\n";
\r
329 foreach ($a->callstack["network"] AS $func => $time) {
\r
330 $time = round($time, 3);
\r
332 $o .= $func . ": " . $time . "\n";
\r
335 logger($o, LOGGER_DEBUG);
\r
339 if (false === $r) {
\r
341 * api function returned false withour throw an
\r
342 * exception. This should not happend, throw a 500
\r
344 throw new InternalServerErrorException();
\r
349 header ("Content-Type: text/xml");
\r
353 header ("Content-Type: application/json");
\r
354 foreach ($r as $rr)
\r
355 $json = json_encode($rr);
\r
356 if (x($_GET, 'callback')) {
\r
357 $json = $_GET['callback'] . "(" . $json . ")";
\r
362 header ("Content-Type: application/rss+xml");
\r
363 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
\r
366 header ("Content-Type: application/atom+xml");
\r
367 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
\r
373 logger('API call not implemented: ' . $a->query_string);
\r
374 throw new NotImplementedException();
\r
375 } catch (HTTPException $e) {
\r
376 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
\r
377 return api_error($type, $e);
\r
382 * @brief Format API error string
\r
384 * @param string $type Return type (xml, json, rss, as)
\r
385 * @param HTTPException $error Error object
\r
386 * @return strin error message formatted as $type
\r
388 function api_error($type, $e) {
\r
392 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
\r
393 /// @TODO: https://dev.twitter.com/overview/api/response-codes
\r
395 $error = array("error" => $error,
\r
396 "code" => $e->httpcode . " " . $e->httpdesc,
\r
397 "request" => $a->query_string);
\r
399 $ret = api_format_data('status', $type, array('status' => $error));
\r
403 header ("Content-Type: text/xml");
\r
407 header ("Content-Type: application/json");
\r
408 return json_encode($ret);
\r
411 header ("Content-Type: application/rss+xml");
\r
415 header ("Content-Type: application/atom+xml");
\r
422 * @brief Set values for RSS template
\r
425 * @param array $arr Array to be passed to template
\r
426 * @param array $user_info
\r
428 * @todo find proper type-hints
\r
430 function api_rss_extra(App $a, $arr, $user_info) {
\r
431 if (is_null($user_info)) {
\r
432 $user_info = api_get_user($a);
\r
435 $arr['$user'] = $user_info;
\r
436 $arr['$rss'] = array(
\r
437 'alternate' => $user_info['url'],
\r
438 'self' => App::get_baseurl() . "/" . $a->query_string,
\r
439 'base' => App::get_baseurl(),
\r
440 'updated' => api_date(null),
\r
441 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
\r
442 'language' => $user_info['language'],
\r
443 'logo' => App::get_baseurl() . "/images/friendica-32.png",
\r
451 * @brief Unique contact to contact url.
\r
453 * @param int $id Contact id
\r
454 * @return bool|string
\r
455 * Contact url or False if contact id is unknown
\r
457 function api_unique_id_to_url($id) {
\r
458 $r = q("SELECT `url` FROM `contact` WHERE `uid` = 0 AND `id` = %d LIMIT 1",
\r
461 return (dbm::is_result($r) && $r[0]["url"]);
\r
465 * @brief Get user info array.
\r
468 * @param int|string $contact_id Contact ID or URL
\r
469 * @param string $type Return type (for errors)
\r
471 function api_get_user(App $a, $contact_id = null, $type = "json") {
\r
472 global $called_api;
\r
479 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
\r
481 // Searching for contact URL
\r
482 if (!is_null($contact_id) AND (intval($contact_id) == 0)) {
\r
483 $user = dbesc(normalise_link($contact_id));
\r
485 $extra_query = "AND `contact`.`nurl` = '%s' ";
\r
486 if (api_user() !== false) {
\r
487 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
\r
491 // Searching for contact id with uid = 0
\r
492 if (!is_null($contact_id) AND (intval($contact_id) != 0)) {
\r
493 $user = dbesc(api_unique_id_to_url($contact_id));
\r
496 throw new BadRequestException("User not found.");
\r
500 $extra_query = "AND `contact`.`nurl` = '%s' ";
\r
501 if (api_user() !== false) {
\r
502 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
\r
506 if (is_null($user) && x($_GET, 'user_id')) {
\r
507 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
\r
510 throw new BadRequestException("User not found.");
\r
514 $extra_query = "AND `contact`.`nurl` = '%s' ";
\r
515 if (api_user() !== false) {
\r
516 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
\r
519 if (is_null($user) && x($_GET, 'screen_name')) {
\r
520 $user = dbesc($_GET['screen_name']);
\r
522 $extra_query = "AND `contact`.`nick` = '%s' ";
\r
523 if (api_user() !== false) {
\r
524 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
\r
528 if (is_null($user) AND ($a->argc > (count($called_api) - 1)) AND (count($called_api) > 0)) {
\r
529 $argid = count($called_api);
\r
530 list($user, $null) = explode(".", $a->argv[$argid]);
\r
531 if (is_numeric($user)) {
\r
532 $user = dbesc(api_unique_id_to_url($user));
\r
539 $extra_query = "AND `contact`.`nurl` = '%s' ";
\r
540 if (api_user() !== false) {
\r
541 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
\r
544 $user = dbesc($user);
\r
546 $extra_query = "AND `contact`.`nick` = '%s' ";
\r
547 if (api_user() !== false) {
\r
548 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
\r
553 logger("api_get_user: user ".$user, LOGGER_DEBUG);
\r
556 if (api_user() === false) {
\r
560 $user = $_SESSION['uid'];
\r
561 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
\r
566 logger('api_user: ' . $extra_query . ', user: ' . $user);
\r
569 $uinfo = q("SELECT *, `contact`.`id` AS `cid` FROM `contact`
\r
575 // Selecting the id by priority, friendica first
\r
576 api_best_nickname($uinfo);
\r
578 // if the contact wasn't found, fetch it from the contacts with uid = 0
\r
579 if (!dbm::is_result($uinfo)) {
\r
583 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
\r
586 if (dbm::is_result($r)) {
\r
587 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
\r
589 // If no nick where given, extract it from the address
\r
590 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick'])) {
\r
591 $r[0]['nick'] = api_get_nick($r[0]["url"]);
\r
595 'id' => $r[0]["id"],
\r
596 'id_str' => (string) $r[0]["id"],
\r
597 'name' => $r[0]["name"],
\r
598 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
\r
599 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
\r
600 'description' => $r[0]["about"],
\r
601 'profile_image_url' => $r[0]["micro"],
\r
602 'profile_image_url_https' => $r[0]["micro"],
\r
603 'url' => $r[0]["url"],
\r
604 'protected' => false,
\r
605 'followers_count' => 0,
\r
606 'friends_count' => 0,
\r
607 'listed_count' => 0,
\r
608 'created_at' => api_date($r[0]["created"]),
\r
609 'favourites_count' => 0,
\r
611 'time_zone' => 'UTC',
\r
612 'geo_enabled' => false,
\r
613 'verified' => false,
\r
614 'statuses_count' => 0,
\r
616 'contributors_enabled' => false,
\r
617 'is_translator' => false,
\r
618 'is_translation_enabled' => false,
\r
619 'following' => false,
\r
620 'follow_request_sent' => false,
\r
621 'statusnet_blocking' => false,
\r
622 'notifications' => false,
\r
623 'statusnet_profile_url' => $r[0]["url"],
\r
625 'cid' => get_contact($r[0]["url"], api_user(), true),
\r
627 'network' => $r[0]["network"],
\r
632 throw new BadRequestException("User not found.");
\r
636 if ($uinfo[0]['self']) {
\r
638 if ($uinfo[0]['network'] == "") {
\r
639 $uinfo[0]['network'] = NETWORK_DFRN;
\r
642 $usr = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
\r
645 $profile = q("SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
\r
649 /// @TODO old-lost code? (twice)
\r
650 // Counting is deactivated by now, due to performance issues
\r
651 // count public wall messages
\r
652 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
\r
653 // intval($uinfo[0]['uid'])
\r
655 //$countitms = $r[0]['count'];
\r
658 // Counting is deactivated by now, due to performance issues
\r
659 //$r = q("SELECT count(*) as `count` FROM `item`
\r
660 // WHERE `contact-id` = %d",
\r
661 // intval($uinfo[0]['id'])
\r
663 //$countitms = $r[0]['count'];
\r
667 /// @TODO old-lost code? (twice)
\r
669 // Counting is deactivated by now, due to performance issues
\r
671 $r = q("SELECT count(*) as `count` FROM `contact`
\r
672 WHERE `uid` = %d AND `rel` IN ( %d, %d )
\r
673 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
\r
674 intval($uinfo[0]['uid']),
\r
675 intval(CONTACT_IS_SHARING),
\r
676 intval(CONTACT_IS_FRIEND)
\r
678 $countfriends = $r[0]['count'];
\r
680 $r = q("SELECT count(*) as `count` FROM `contact`
\r
681 WHERE `uid` = %d AND `rel` IN ( %d, %d )
\r
682 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
\r
683 intval($uinfo[0]['uid']),
\r
684 intval(CONTACT_IS_FOLLOWER),
\r
685 intval(CONTACT_IS_FRIEND)
\r
687 $countfollowers = $r[0]['count'];
\r
689 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
\r
690 intval($uinfo[0]['uid'])
\r
692 $starred = $r[0]['count'];
\r
695 if (! $uinfo[0]['self']) {
\r
697 $countfollowers = 0;
\r
702 $countfollowers = 0;
\r
705 // Add a nick if it isn't present there
\r
706 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
\r
707 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
\r
710 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
\r
712 $pcontact_id = get_contact($uinfo[0]['url'], 0, true);
\r
715 'id' => intval($pcontact_id),
\r
716 'id_str' => (string) intval($pcontact_id),
\r
717 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
\r
718 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
\r
719 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
\r
720 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
\r
721 'profile_image_url' => $uinfo[0]['micro'],
\r
722 'profile_image_url_https' => $uinfo[0]['micro'],
\r
723 'url' => $uinfo[0]['url'],
\r
724 'protected' => false,
\r
725 'followers_count' => intval($countfollowers),
\r
726 'friends_count' => intval($countfriends),
\r
727 'listed_count' => 0,
\r
728 'created_at' => api_date($uinfo[0]['created']),
\r
729 'favourites_count' => intval($starred),
\r
730 'utc_offset' => "0",
\r
731 'time_zone' => 'UTC',
\r
732 'geo_enabled' => false,
\r
733 'verified' => true,
\r
734 'statuses_count' => intval($countitms),
\r
736 'contributors_enabled' => false,
\r
737 'is_translator' => false,
\r
738 'is_translation_enabled' => false,
\r
739 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
\r
740 'follow_request_sent' => false,
\r
741 'statusnet_blocking' => false,
\r
742 'notifications' => false,
\r
744 //'statusnet_profile_url' => App::get_baseurl()."/contacts/".$uinfo[0]['cid'],
\r
745 'statusnet_profile_url' => $uinfo[0]['url'],
\r
746 'uid' => intval($uinfo[0]['uid']),
\r
747 'cid' => intval($uinfo[0]['cid']),
\r
748 'self' => $uinfo[0]['self'],
\r
749 'network' => $uinfo[0]['network'],
\r
757 * @brief return api-formatted array for item's author and owner
\r
760 * @param array $item : item from db
\r
761 * @return array(array:author, array:owner)
\r
763 function api_item_get_user(App $a, $item) {
\r
765 $status_user = api_get_user($a, $item["author-link"]);
\r
767 $status_user["protected"] = (($item["allow_cid"] != "") OR
\r
768 ($item["allow_gid"] != "") OR
\r
769 ($item["deny_cid"] != "") OR
\r
770 ($item["deny_gid"] != "") OR
\r
773 if ($item['thr-parent'] == $item['uri']) {
\r
774 $owner_user = api_get_user($a, $item["owner-link"]);
\r
776 $owner_user = $status_user;
\r
779 return (array($status_user, $owner_user));
\r
783 * @brief walks recursively through an array with the possibility to change value and key
\r
785 * @param array $array The array to walk through
\r
786 * @param string $callback The callback function
\r
788 * @return array the transformed array
\r
790 function api_walk_recursive(array &$array, callable $callback) {
\r
792 $new_array = array();
\r
794 foreach ($array as $k => $v) {
\r
795 if (is_array($v)) {
\r
796 if ($callback($v, $k)) {
\r
797 $new_array[$k] = api_walk_recursive($v, $callback);
\r
800 if ($callback($v, $k)) {
\r
801 $new_array[$k] = $v;
\r
805 $array = $new_array;
\r
811 * @brief Callback function to transform the array in an array that can be transformed in a XML file
\r
813 * @param variant $item Array item value
\r
814 * @param string $key Array key
\r
816 * @return boolean Should the array item be deleted?
\r
818 function api_reformat_xml(&$item, &$key) {
\r
819 if (is_bool($item)) {
\r
820 $item = ($item ? "true" : "false");
\r
823 if (substr($key, 0, 10) == "statusnet_") {
\r
824 $key = "statusnet:".substr($key, 10);
\r
825 } elseif (substr($key, 0, 10) == "friendica_") {
\r
826 $key = "friendica:".substr($key, 10);
\r
828 /// @TODO old-lost code?
\r
830 // $key = "default:".$key;
\r
836 * @brief Creates the XML from a JSON style array
\r
838 * @param array $data JSON style array
\r
839 * @param string $root_element Name of the root element
\r
841 * @return string The XML data
\r
843 function api_create_xml($data, $root_element) {
\r
844 $childname = key($data);
\r
845 $data2 = array_pop($data);
\r
846 $key = key($data2);
\r
848 $namespaces = array("" => "http://api.twitter.com",
\r
849 "statusnet" => "http://status.net/schema/api/1/",
\r
850 "friendica" => "http://friendi.ca/schema/api/1/",
\r
851 "georss" => "http://www.georss.org/georss");
\r
853 /// @todo Auto detection of needed namespaces
\r
854 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
\r
855 $namespaces = array();
\r
858 if (is_array($data2)) {
\r
859 api_walk_recursive($data2, "api_reformat_xml");
\r
866 foreach ($data2 AS $item) {
\r
867 $data4[$i++.":".$childname] = $item;
\r
873 $data3 = array($root_element => $data2);
\r
875 $ret = xml::from_array($data3, $xml, false, $namespaces);
\r
880 * @brief Formats the data according to the data type
\r
882 * @param string $root_element Name of the root element
\r
883 * @param string $type Return type (atom, rss, xml, json)
\r
884 * @param array $data JSON style array
\r
886 * @return (string|object) XML data or JSON data
\r
888 function api_format_data($root_element, $type, $data) {
\r
896 $ret = api_create_xml($data, $root_element);
\r
911 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
\r
912 * returns a 401 status code and an error message if not.
\r
913 * http://developer.twitter.com/doc/get/account/verify_credentials
\r
915 function api_account_verify_credentials($type) {
\r
919 if (api_user() === false) {
\r
920 throw new ForbiddenException();
\r
923 unset($_REQUEST["user_id"]);
\r
924 unset($_GET["user_id"]);
\r
926 unset($_REQUEST["screen_name"]);
\r
927 unset($_GET["screen_name"]);
\r
929 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
\r
931 $user_info = api_get_user($a);
\r
933 // "verified" isn't used here in the standard
\r
934 unset($user_info["verified"]);
\r
936 // - Adding last status
\r
937 if (!$skip_status) {
\r
938 $user_info["status"] = api_status_show("raw");
\r
939 if (!count($user_info["status"])) {
\r
940 unset($user_info["status"]);
\r
942 unset($user_info["status"]["user"]);
\r
946 // "uid" and "self" are only needed for some internal stuff, so remove it from here
\r
947 unset($user_info["uid"]);
\r
948 unset($user_info["self"]);
\r
950 return api_format_data("user", $type, array('user' => $user_info));
\r
954 /// @TODO move to top of file or somwhere better
\r
955 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
\r
958 * get data from $_POST or $_GET
\r
960 function requestdata($k) {
\r
961 if (x($_POST, $k)) {
\r
964 if (x($_GET, $k)) {
\r
970 /*Waitman Gobble Mod*/
\r
971 function api_statuses_mediap($type) {
\r
975 if (api_user() === false) {
\r
976 logger('api_statuses_update: no user');
\r
977 throw new ForbiddenException();
\r
979 $user_info = api_get_user($a);
\r
981 $_REQUEST['type'] = 'wall';
\r
982 $_REQUEST['profile_uid'] = api_user();
\r
983 $_REQUEST['api_source'] = true;
\r
984 $txt = requestdata('status');
\r
985 /// @TODO old-lost code?
\r
986 //$txt = urldecode(requestdata('status'));
\r
988 if ((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
\r
990 $txt = html2bb_video($txt);
\r
991 $config = HTMLPurifier_Config::createDefault();
\r
992 $config->set('Cache.DefinitionImpl', null);
\r
993 $purifier = new HTMLPurifier($config);
\r
994 $txt = $purifier->purify($txt);
\r
996 $txt = html2bbcode($txt);
\r
998 $a->argv[1]=$user_info['screen_name']; //should be set to username?
\r
1000 // tell wall_upload function to return img info instead of echo
\r
1001 $_REQUEST['hush'] = 'yeah';
\r
1002 $bebop = wall_upload_post($a);
\r
1004 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
\r
1005 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
\r
1008 // this should output the last post (the one we just posted).
\r
1009 return api_status_show($type);
\r
1012 /// @TODO move this to top of file or somewhere better!
\r
1013 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
\r
1015 function api_statuses_update($type) {
\r
1019 if (api_user() === false) {
\r
1020 logger('api_statuses_update: no user');
\r
1021 throw new ForbiddenException();
\r
1024 $user_info = api_get_user($a);
\r
1026 // convert $_POST array items to the form we use for web posts.
\r
1028 // logger('api_post: ' . print_r($_POST,true));
\r
1030 if (requestdata('htmlstatus')) {
\r
1031 $txt = requestdata('htmlstatus');
\r
1032 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
\r
1033 $txt = html2bb_video($txt);
\r
1035 $config = HTMLPurifier_Config::createDefault();
\r
1036 $config->set('Cache.DefinitionImpl', null);
\r
1038 $purifier = new HTMLPurifier($config);
\r
1039 $txt = $purifier->purify($txt);
\r
1041 $_REQUEST['body'] = html2bbcode($txt);
\r
1045 $_REQUEST['body'] = requestdata('status');
\r
1048 $_REQUEST['title'] = requestdata('title');
\r
1050 $parent = requestdata('in_reply_to_status_id');
\r
1052 // Twidere sends "-1" if it is no reply ...
\r
1053 if ($parent == -1) {
\r
1057 if (ctype_digit($parent)) {
\r
1058 $_REQUEST['parent'] = $parent;
\r
1060 $_REQUEST['parent_uri'] = $parent;
\r
1063 if (requestdata('lat') && requestdata('long')) {
\r
1064 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
\r
1066 $_REQUEST['profile_uid'] = api_user();
\r
1069 $_REQUEST['type'] = 'net-comment';
\r
1071 // Check for throttling (maximum posts per day, week and month)
\r
1072 $throttle_day = get_config('system','throttle_limit_day');
\r
1073 if ($throttle_day > 0) {
\r
1074 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
\r
1076 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
\r
1077 AND `created` > '%s' AND `id` = `parent`",
\r
1078 intval(api_user()), dbesc($datefrom));
\r
1080 if (dbm::is_result($r)) {
\r
1081 $posts_day = $r[0]["posts_day"];
\r
1086 if ($posts_day > $throttle_day) {
\r
1087 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
\r
1088 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
\r
1089 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
\r
1093 $throttle_week = get_config('system','throttle_limit_week');
\r
1094 if ($throttle_week > 0) {
\r
1095 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
\r
1097 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
\r
1098 AND `created` > '%s' AND `id` = `parent`",
\r
1099 intval(api_user()), dbesc($datefrom));
\r
1101 if (dbm::is_result($r)) {
\r
1102 $posts_week = $r[0]["posts_week"];
\r
1107 if ($posts_week > $throttle_week) {
\r
1108 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
\r
1109 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
\r
1110 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
\r
1114 $throttle_month = get_config('system','throttle_limit_month');
\r
1115 if ($throttle_month > 0) {
\r
1116 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
\r
1118 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
\r
1119 AND `created` > '%s' AND `id` = `parent`",
\r
1120 intval(api_user()), dbesc($datefrom));
\r
1122 if (dbm::is_result($r)) {
\r
1123 $posts_month = $r[0]["posts_month"];
\r
1128 if ($posts_month > $throttle_month) {
\r
1129 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
\r
1130 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
\r
1131 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
\r
1135 $_REQUEST['type'] = 'wall';
\r
1138 if (x($_FILES, 'media')) {
\r
1139 // upload the image if we have one
\r
1140 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
\r
1141 $media = wall_upload_post($a);
\r
1142 if (strlen($media) > 0) {
\r
1143 $_REQUEST['body'] .= "\n\n" . $media;
\r
1147 // To-Do: Multiple IDs
\r
1148 if (requestdata('media_ids')) {
\r
1149 $r = q("SELECT `resource-id`, `scale`, `nickname`, `type` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1",
\r
1150 intval(requestdata('media_ids')), api_user());
\r
1151 if (dbm::is_result($r)) {
\r
1152 $phototypes = Photo::supportedTypes();
\r
1153 $ext = $phototypes[$r[0]['type']];
\r
1154 $_REQUEST['body'] .= "\n\n" . '[url=' . App::get_baseurl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
\r
1155 $_REQUEST['body'] .= '[img]' . App::get_baseurl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
\r
1159 // set this so that the item_post() function is quiet and doesn't redirect or emit json
\r
1161 $_REQUEST['api_source'] = true;
\r
1163 if (!x($_REQUEST, "source")) {
\r
1164 $_REQUEST["source"] = api_source();
\r
1167 // call out normal post function
\r
1170 // this should output the last post (the one we just posted).
\r
1171 return api_status_show($type);
\r
1174 /// @TODO move to top of file or somwhere better
\r
1175 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
\r
1176 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
\r
1178 function api_media_upload($type) {
\r
1182 if (api_user() === false) {
\r
1183 logger('no user');
\r
1184 throw new ForbiddenException();
\r
1187 $user_info = api_get_user($a);
\r
1189 if (!x($_FILES, 'media')) {
\r
1191 throw new BadRequestException("No media.");
\r
1194 $media = wall_upload_post($a, false);
\r
1197 throw new InternalServerErrorException();
\r
1200 $returndata = array();
\r
1201 $returndata["media_id"] = $media["id"];
\r
1202 $returndata["media_id_string"] = (string)$media["id"];
\r
1203 $returndata["size"] = $media["size"];
\r
1204 $returndata["image"] = array("w" => $media["width"],
\r
1205 "h" => $media["height"],
\r
1206 "image_type" => $media["type"]);
\r
1208 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
\r
1210 return array("media" => $returndata);
\r
1213 /// @TODO move to top of file or somwhere better
\r
1214 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
\r
1216 function api_status_show($type) {
\r
1220 $user_info = api_get_user($a);
\r
1222 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
\r
1224 if ($type == "raw") {
\r
1225 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
\r
1227 $privacy_sql = "";
\r
1230 // get last public wall message
\r
1231 $lastwall = q("SELECT `item`.*
\r
1233 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
\r
1234 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
\r
1235 AND `item`.`type` != 'activity' $privacy_sql
\r
1236 ORDER BY `item`.`id` DESC
\r
1238 intval($user_info['cid']),
\r
1239 intval(api_user()),
\r
1240 dbesc($user_info['url']),
\r
1241 dbesc(normalise_link($user_info['url'])),
\r
1242 dbesc($user_info['url']),
\r
1243 dbesc(normalise_link($user_info['url']))
\r
1246 if (dbm::is_result($lastwall)) {
\r
1247 $lastwall = $lastwall[0];
\r
1249 $in_reply_to = api_in_reply_to($lastwall);
\r
1251 $converted = api_convert_item($lastwall);
\r
1253 if ($type == "xml") {
\r
1254 $geo = "georss:point";
\r
1259 $status_info = array(
\r
1260 'created_at' => api_date($lastwall['created']),
\r
1261 'id' => intval($lastwall['id']),
\r
1262 'id_str' => (string) $lastwall['id'],
\r
1263 'text' => $converted["text"],
\r
1264 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
\r
1265 'truncated' => false,
\r
1266 'in_reply_to_status_id' => $in_reply_to['status_id'],
\r
1267 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
\r
1268 'in_reply_to_user_id' => $in_reply_to['user_id'],
\r
1269 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
\r
1270 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
\r
1271 'user' => $user_info,
\r
1273 'coordinates' => "",
\r
1275 'contributors' => "",
\r
1276 'is_quote_status' => false,
\r
1277 'retweet_count' => 0,
\r
1278 'favorite_count' => 0,
\r
1279 'favorited' => $lastwall['starred'] ? true : false,
\r
1280 'retweeted' => false,
\r
1281 'possibly_sensitive' => false,
\r
1283 'statusnet_html' => $converted["html"],
\r
1284 'statusnet_conversation_id' => $lastwall['parent'],
\r
1287 if (count($converted["attachments"]) > 0) {
\r
1288 $status_info["attachments"] = $converted["attachments"];
\r
1291 if (count($converted["entities"]) > 0) {
\r
1292 $status_info["entities"] = $converted["entities"];
\r
1295 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web')) {
\r
1296 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
\r
1297 } elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
\r
1298 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
\r
1301 // "uid" and "self" are only needed for some internal stuff, so remove it from here
\r
1302 unset($status_info["user"]["uid"]);
\r
1303 unset($status_info["user"]["self"]);
\r
1306 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
\r
1308 if ($type == "raw") {
\r
1309 return $status_info;
\r
1312 return api_format_data("statuses", $type, array('status' => $status_info));
\r
1317 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
\r
1318 * The author's most recent status will be returned inline.
\r
1319 * http://developer.twitter.com/doc/get/users/show
\r
1321 function api_users_show($type) {
\r
1325 $user_info = api_get_user($a);
\r
1326 $lastwall = q("SELECT `item`.*
\r
1328 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
\r
1329 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
\r
1330 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
\r
1331 AND `type`!='activity'
\r
1332 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
\r
1333 ORDER BY `id` DESC
\r
1335 intval(api_user()),
\r
1336 dbesc(ACTIVITY_POST),
\r
1337 intval($user_info['cid']),
\r
1338 dbesc($user_info['url']),
\r
1339 dbesc(normalise_link($user_info['url'])),
\r
1340 dbesc($user_info['url']),
\r
1341 dbesc(normalise_link($user_info['url']))
\r
1344 if (dbm::is_result($lastwall)) {
\r
1345 $lastwall = $lastwall[0];
\r
1347 $in_reply_to = api_in_reply_to($lastwall);
\r
1349 $converted = api_convert_item($lastwall);
\r
1351 if ($type == "xml") {
\r
1352 $geo = "georss:point";
\r
1357 $user_info['status'] = array(
\r
1358 'text' => $converted["text"],
\r
1359 'truncated' => false,
\r
1360 'created_at' => api_date($lastwall['created']),
\r
1361 'in_reply_to_status_id' => $in_reply_to['status_id'],
\r
1362 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
\r
1363 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
\r
1364 'id' => intval($lastwall['contact-id']),
\r
1365 'id_str' => (string) $lastwall['contact-id'],
\r
1366 'in_reply_to_user_id' => $in_reply_to['user_id'],
\r
1367 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
\r
1368 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
\r
1370 'favorited' => $lastwall['starred'] ? true : false,
\r
1371 'statusnet_html' => $converted["html"],
\r
1372 'statusnet_conversation_id' => $lastwall['parent'],
\r
1375 if (count($converted["attachments"]) > 0) {
\r
1376 $user_info["status"]["attachments"] = $converted["attachments"];
\r
1379 if (count($converted["entities"]) > 0) {
\r
1380 $user_info["status"]["entities"] = $converted["entities"];
\r
1383 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web')) {
\r
1384 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
\r
1387 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
\r
1388 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
\r
1393 // "uid" and "self" are only needed for some internal stuff, so remove it from here
\r
1394 unset($user_info["uid"]);
\r
1395 unset($user_info["self"]);
\r
1397 return api_format_data("user", $type, array('user' => $user_info));
\r
1401 /// @TODO move to top of file or somewhere better
\r
1402 api_register_func('api/users/show','api_users_show');
\r
1404 function api_users_search($type) {
\r
1408 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
\r
1410 $userlist = array();
\r
1412 if (x($_GET, 'q')) {
\r
1413 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
\r
1415 if (!dbm::is_result($r)) {
\r
1416 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
\r
1419 if (dbm::is_result($r)) {
\r
1421 foreach ($r AS $user) {
\r
1422 $user_info = api_get_user($a, $user["id"], "json");
\r
1424 if ($type == "xml") {
\r
1425 $userlist[$k++.":user"] = $user_info;
\r
1427 $userlist[] = $user_info;
\r
1430 $userlist = array("users" => $userlist);
\r
1432 throw new BadRequestException("User not found.");
\r
1435 throw new BadRequestException("User not found.");
\r
1437 return api_format_data("users", $type, $userlist);
\r
1440 /// @TODO move to top of file or somewhere better
\r
1441 api_register_func('api/users/search','api_users_search');
\r
1445 * http://developer.twitter.com/doc/get/statuses/home_timeline
\r
1447 * TODO: Optional parameters
\r
1448 * TODO: Add reply info
\r
1450 function api_statuses_home_timeline($type) {
\r
1454 if (api_user() === false) {
\r
1455 throw new ForbiddenException();
\r
1458 unset($_REQUEST["user_id"]);
\r
1459 unset($_GET["user_id"]);
\r
1461 unset($_REQUEST["screen_name"]);
\r
1462 unset($_GET["screen_name"]);
\r
1464 $user_info = api_get_user($a);
\r
1465 // get last newtork messages
\r
1468 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
\r
1469 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
\r
1473 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
\r
1474 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
\r
1475 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
\r
1476 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
\r
1477 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
\r
1479 $start = $page * $count;
\r
1482 if ($max_id > 0) {
\r
1483 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
\r
1485 if ($exclude_replies > 0) {
\r
1486 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
\r
1488 if ($conversation_id > 0) {
\r
1489 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
\r
1492 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
\r
1493 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
\r
1494 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
\r
1495 `contact`.`id` AS `cid`
\r
1497 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
\r
1498 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
\r
1499 WHERE `item`.`uid` = %d AND `verb` = '%s'
\r
1500 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
\r
1502 AND `item`.`id`>%d
\r
1503 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
\r
1504 intval(api_user()),
\r
1505 dbesc(ACTIVITY_POST),
\r
1506 intval($since_id),
\r
1507 intval($start), intval($count)
\r
1510 $ret = api_format_items($r, $user_info, false, $type);
\r
1512 // Set all posts from the query above to seen
\r
1513 $idarray = array();
\r
1514 foreach ($r AS $item) {
\r
1515 $idarray[] = intval($item["id"]);
\r
1518 $idlist = implode(",", $idarray);
\r
1520 if ($idlist != "") {
\r
1521 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
\r
1524 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
\r
1528 $data = array('status' => $ret);
\r
1532 $data = api_rss_extra($a, $data, $user_info);
\r
1536 return api_format_data("statuses", $type, $data);
\r
1539 /// @TODO move to top of file or somewhere better
\r
1540 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
\r
1541 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
\r
1543 function api_statuses_public_timeline($type) {
\r
1547 if (api_user() === false) {
\r
1548 throw new ForbiddenException();
\r
1551 $user_info = api_get_user($a);
\r
1552 // get last newtork messages
\r
1555 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
\r
1556 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
\r
1560 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
\r
1561 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
\r
1562 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
\r
1563 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
\r
1564 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
\r
1566 $start = $page * $count;
\r
1568 if ($max_id > 0) {
\r
1569 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
\r
1571 if ($exclude_replies > 0) {
\r
1572 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
\r
1574 if ($conversation_id > 0) {
\r
1575 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
\r
1578 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
\r
1579 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
\r
1580 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
\r
1581 `contact`.`id` AS `cid`,
\r
1582 `user`.`nickname`, `user`.`hidewall`
\r
1584 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
\r
1585 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
\r
1586 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
\r
1587 AND NOT `user`.`hidewall`
\r
1588 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
\r
1589 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
\r
1590 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
\r
1591 AND NOT `item`.`private` AND `item`.`wall`
\r
1593 AND `item`.`id`>%d
\r
1594 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
\r
1595 dbesc(ACTIVITY_POST),
\r
1596 intval($since_id),
\r
1600 $ret = api_format_items($r, $user_info, false, $type);
\r
1602 $data = array('status' => $ret);
\r
1606 $data = api_rss_extra($a, $data, $user_info);
\r
1610 return api_format_data("statuses", $type, $data);
\r
1613 /// @TODO move to top of file or somewhere better
\r
1614 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
\r
1617 * @TODO nothing to say?
\r
1619 function api_statuses_show($type) {
\r
1623 if (api_user() === false) {
\r
1624 throw new ForbiddenException();
\r
1627 $user_info = api_get_user($a);
\r
1630 $id = intval($a->argv[3]);
\r
1633 $id = intval($_REQUEST["id"]);
\r
1636 // Hotot workaround
\r
1638 $id = intval($a->argv[4]);
\r
1641 logger('API: api_statuses_show: ' . $id);
\r
1643 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
\r
1646 if ($conversation) {
\r
1647 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
\r
1649 $sql_extra .= " AND `item`.`id` = %d";
\r
1652 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
\r
1653 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
\r
1654 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
\r
1655 `contact`.`id` AS `cid`
\r
1657 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
\r
1658 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
\r
1659 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
\r
1660 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
\r
1662 intval(api_user()),
\r
1663 dbesc(ACTIVITY_POST),
\r
1667 /// @TODO How about copying this to above methods which don't check $r ?
\r
1668 if (!dbm::is_result($r)) {
\r
1669 throw new BadRequestException("There is no status with this id.");
\r
1672 $ret = api_format_items($r,$user_info, false, $type);
\r
1674 if ($conversation) {
\r
1675 $data = array('status' => $ret);
\r
1676 return api_format_data("statuses", $type, $data);
\r
1678 $data = array('status' => $ret[0]);
\r
1679 return api_format_data("status", $type, $data);
\r
1683 /// @TODO move to top of file or somewhere better
\r
1684 api_register_func('api/statuses/show','api_statuses_show', true);
\r
1687 * @TODO nothing to say?
\r
1689 function api_conversation_show($type) {
\r
1693 if (api_user() === false) {
\r
1694 throw new ForbiddenException();
\r
1697 $user_info = api_get_user($a);
\r
1700 $id = intval($a->argv[3]);
\r
1701 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
\r
1702 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
\r
1706 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
\r
1707 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
\r
1709 $start = $page*$count;
\r
1712 $id = intval($_REQUEST["id"]);
\r
1715 // Hotot workaround
\r
1717 $id = intval($a->argv[4]);
\r
1720 logger('API: api_conversation_show: '.$id);
\r
1722 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
\r
1723 if (dbm::is_result($r)) {
\r
1724 $id = $r[0]["parent"];
\r
1729 if ($max_id > 0) {
\r
1730 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
\r
1733 // Not sure why this query was so complicated. We should keep it here for a while,
\r
1734 // just to make sure that we really don't need it.
\r
1735 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
\r
1736 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
\r
1738 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
\r
1739 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
\r
1740 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
\r
1741 `contact`.`id` AS `cid`
\r
1743 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
\r
1744 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
\r
1745 WHERE `item`.`parent` = %d AND `item`.`visible`
\r
1746 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
\r
1747 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
\r
1748 AND `item`.`id`>%d $sql_extra
\r
1749 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
\r
1750 intval($id), intval(api_user()),
\r
1751 dbesc(ACTIVITY_POST),
\r
1752 intval($since_id),
\r
1753 intval($start), intval($count)
\r
1756 if (!dbm::is_result($r)) {
\r
1757 throw new BadRequestException("There is no status with this id.");
\r
1760 $ret = api_format_items($r, $user_info, false, $type);
\r
1762 $data = array('status' => $ret);
\r
1763 return api_format_data("statuses", $type, $data);
\r
1766 /// @TODO move to top of file or somewhere better
\r
1767 api_register_func('api/conversation/show','api_conversation_show', true);
\r
1768 api_register_func('api/statusnet/conversation','api_conversation_show', true);
\r
1771 * @TODO nothing to say?
\r
1773 function api_statuses_repeat($type) {
\r
1774 global $called_api;
\r
1778 if (api_user() === false) {
\r
1779 throw new ForbiddenException();
\r
1782 $user_info = api_get_user($a);
\r
1785 $id = intval($a->argv[3]);
\r
1788 $id = intval($_REQUEST["id"]);
\r
1791 // Hotot workaround
\r
1793 $id = intval($a->argv[4]);
\r
1796 logger('API: api_statuses_repeat: '.$id);
\r
1798 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
\r
1799 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
\r
1800 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
\r
1801 `contact`.`id` AS `cid`
\r
1803 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
\r
1804 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
\r
1805 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
\r
1806 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
\r
1807 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
\r
1809 AND `item`.`id`=%d",
\r
1813 /// @TODO other style than above functions!
\r
1814 if (dbm::is_result($r) && $r[0]['body'] != "") {
\r
1815 if (strpos($r[0]['body'], "[/share]") !== false) {
\r
1816 $pos = strpos($r[0]['body'], "[share");
\r
1817 $post = substr($r[0]['body'], $pos);
\r
1819 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
\r
1821 $post .= $r[0]['body'];
\r
1822 $post .= "[/share]";
\r
1824 $_REQUEST['body'] = $post;
\r
1825 $_REQUEST['profile_uid'] = api_user();
\r
1826 $_REQUEST['type'] = 'wall';
\r
1827 $_REQUEST['api_source'] = true;
\r
1829 if (!x($_REQUEST, "source")) {
\r
1830 $_REQUEST["source"] = api_source();
\r
1835 throw new ForbiddenException();
\r
1838 // this should output the last post (the one we just posted).
\r
1839 $called_api = null;
\r
1840 return api_status_show($type);
\r
1843 /// @TODO move to top of file or somewhere better
\r
1844 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
\r
1847 * @TODO nothing to say?
\r
1849 function api_statuses_destroy($type) {
\r
1853 if (api_user() === false) {
\r
1854 throw new ForbiddenException();
\r
1857 $user_info = api_get_user($a);
\r
1860 $id = intval($a->argv[3]);
\r
1863 $id = intval($_REQUEST["id"]);
\r
1866 // Hotot workaround
\r
1868 $id = intval($a->argv[4]);
\r
1871 logger('API: api_statuses_destroy: '.$id);
\r
1873 $ret = api_statuses_show($type);
\r
1875 drop_item($id, false);
\r
1880 /// @TODO move to top of file or somewhere better
\r
1881 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
\r
1884 * @TODO Nothing more than an URL to say?
\r
1885 * http://developer.twitter.com/doc/get/statuses/mentions
\r
1887 function api_statuses_mentions($type) {
\r
1891 if (api_user() === false) {
\r
1892 throw new ForbiddenException();
\r
1895 unset($_REQUEST["user_id"]);
\r
1896 unset($_GET["user_id"]);
\r
1898 unset($_REQUEST["screen_name"]);
\r
1899 unset($_GET["screen_name"]);
\r
1901 $user_info = api_get_user($a);
\r
1902 // get last newtork messages
\r
1906 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
\r
1907 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
\r
1911 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
\r
1912 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
\r
1913 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
\r
1915 $start = $page * $count;
\r
1917 // Ugly code - should be changed
\r
1918 $myurl = App::get_baseurl() . '/profile/'. $a->user['nickname'];
\r
1919 $myurl = substr($myurl,strpos($myurl, '://') + 3);
\r
1920 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
\r
1921 $myurl = str_replace('www.', '', $myurl);
\r
1922 $diasp_url = str_replace('/profile/', '/u/', $myurl);
\r
1924 if ($max_id > 0) {
\r
1925 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
\r
1928 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
\r
1929 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
\r
1930 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
\r
1931 `contact`.`id` AS `cid`
\r
1932 FROM `item` FORCE INDEX (`uid_id`)
\r
1933 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
\r
1934 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
\r
1935 WHERE `item`.`uid` = %d AND `verb` = '%s'
\r
1936 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
\r
1937 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
\r
1938 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
\r
1940 AND `item`.`id`>%d
\r
1941 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
\r
1942 intval(api_user()),
\r
1943 dbesc(ACTIVITY_POST),
\r
1944 dbesc(protect_sprintf($myurl)),
\r
1945 dbesc(protect_sprintf($myurl)),
\r
1946 intval(api_user()),
\r
1947 intval($since_id),
\r
1948 intval($start), intval($count)
\r
1951 $ret = api_format_items($r, $user_info, false, $type);
\r
1953 $data = array('status' => $ret);
\r
1957 $data = api_rss_extra($a, $data, $user_info);
\r
1961 return api_format_data("statuses", $type, $data);
\r
1964 /// @TODO move to top of file or somewhere better
\r
1965 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
\r
1966 api_register_func('api/statuses/replies','api_statuses_mentions', true);
\r
1968 function api_statuses_user_timeline($type) {
\r
1972 if (api_user() === false) {
\r
1973 throw new ForbiddenException();
\r
1976 $user_info = api_get_user($a);
\r
1977 // get last network messages
\r
1979 logger("api_statuses_user_timeline: api_user: ". api_user() .
\r
1980 "\nuser_info: ".print_r($user_info, true) .
\r
1981 "\n_REQUEST: ".print_r($_REQUEST, true),
\r
1985 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
\r
1986 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
\r
1990 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
\r
1991 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
\r
1992 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
\r
1993 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
\r
1995 $start = $page * $count;
\r
1998 if ($user_info['self'] == 1) {
\r
1999 $sql_extra .= " AND `item`.`wall` = 1 ";
\r
2002 if ($exclude_replies > 0) {
\r
2003 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
\r
2005 if ($conversation_id > 0) {
\r
2006 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
\r
2009 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
\r
2010 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
\r
2011 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
\r
2012 `contact`.`id` AS `cid`
\r
2013 FROM `item` FORCE INDEX (`uid_contactid_id`)
\r
2014 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
\r
2015 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
\r
2016 WHERE `item`.`uid` = %d AND `verb` = '%s'
\r
2017 AND `item`.`contact-id` = %d
\r
2018 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
\r
2020 AND `item`.`id`>%d
\r
2021 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
\r
2022 intval(api_user()),
\r
2023 dbesc(ACTIVITY_POST),
\r
2024 intval($user_info['cid']),
\r
2025 intval($since_id),
\r
2026 intval($start), intval($count)
\r
2029 $ret = api_format_items($r, $user_info, true, $type);
\r
2031 $data = array('status' => $ret);
\r
2035 $data = api_rss_extra($a, $data, $user_info);
\r
2039 return api_format_data("statuses", $type, $data);
\r
2042 /// @TODO move to top of file or somwhere better
\r
2043 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
\r
2046 * Star/unstar an item
\r
2047 * param: id : id of the item
\r
2049 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
\r
2051 function api_favorites_create_destroy($type) {
\r
2055 if (api_user() === false) {
\r
2056 throw new ForbiddenException();
\r
2059 // for versioned api.
\r
2060 /// @TODO We need a better global soluton
\r
2061 $action_argv_id = 2;
\r
2062 if ($a->argv[1] == "1.1") {
\r
2063 $action_argv_id = 3;
\r
2066 if ($a->argc <= $action_argv_id) {
\r
2067 throw new BadRequestException("Invalid request.");
\r
2069 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
\r
2070 if ($a->argc == $action_argv_id + 2) {
\r
2071 $itemid = intval($a->argv[$action_argv_id + 1]);
\r
2073 /// @TODO use x() to check if _REQUEST contains 'id'
\r
2074 $itemid = intval($_REQUEST['id']);
\r
2077 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1",
\r
2078 $itemid, api_user());
\r
2080 if (!dbm::is_result($item) || count($item) == 0) {
\r
2081 throw new BadRequestException("Invalid item.");
\r
2084 switch ($action) {
\r
2086 $item[0]['starred'] = 1;
\r
2089 $item[0]['starred'] = 0;
\r
2092 throw new BadRequestException("Invalid action ".$action);
\r
2095 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
\r
2096 $item[0]['starred'], $itemid, api_user());
\r
2098 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
\r
2099 $item[0]['starred'], $itemid, api_user());
\r
2101 if ($r === false) {
\r
2102 throw new InternalServerErrorException("DB error");
\r
2106 $user_info = api_get_user($a);
\r
2107 $rets = api_format_items($item, $user_info, false, $type);
\r
2110 $data = array('status' => $ret);
\r
2114 $data = api_rss_extra($a, $data, $user_info);
\r
2117 return api_format_data("status", $type, $data);
\r
2120 /// @TODO move to top of file or somwhere better
\r
2121 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
\r
2122 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
\r
2124 function api_favorites($type) {
\r
2125 global $called_api;
\r
2129 if (api_user() === false) {
\r
2130 throw new ForbiddenException();
\r
2133 $called_api = array();
\r
2135 $user_info = api_get_user($a);
\r
2137 // in friendica starred item are private
\r
2138 // return favorites only for self
\r
2139 logger('api_favorites: self:' . $user_info['self']);
\r
2141 if ($user_info['self'] == 0) {
\r
2147 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
\r
2148 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
\r
2149 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
\r
2150 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
\r
2155 $start = $page*$count;
\r
2157 if ($max_id > 0) {
\r
2158 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
\r
2161 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
\r
2162 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
\r
2163 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
\r
2164 `contact`.`id` AS `cid`
\r
2165 FROM `item`, `contact`
\r
2166 WHERE `item`.`uid` = %d
\r
2167 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
\r
2168 AND `item`.`starred` = 1
\r
2169 AND `contact`.`id` = `item`.`contact-id`
\r
2170 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
\r
2172 AND `item`.`id`>%d
\r
2173 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
\r
2174 intval(api_user()),
\r
2175 intval($since_id),
\r
2176 intval($start), intval($count)
\r
2179 $ret = api_format_items($r,$user_info, false, $type);
\r
2183 $data = array('status' => $ret);
\r
2187 $data = api_rss_extra($a, $data, $user_info);
\r
2190 return api_format_data("statuses", $type, $data);
\r
2193 /// @TODO move to top of file or somwhere better
\r
2194 api_register_func('api/favorites','api_favorites', true);
\r
2196 function api_format_messages($item, $recipient, $sender) {
\r
2197 // standard meta information
\r
2199 'id' => $item['id'],
\r
2200 'sender_id' => $sender['id'] ,
\r
2202 'recipient_id' => $recipient['id'],
\r
2203 'created_at' => api_date($item['created']),
\r
2204 'sender_screen_name' => $sender['screen_name'],
\r
2205 'recipient_screen_name' => $recipient['screen_name'],
\r
2206 'sender' => $sender,
\r
2207 'recipient' => $recipient,
\r
2209 'friendica_seen' => $item['seen'],
\r
2210 'friendica_parent_uri' => $item['parent-uri'],
\r
2213 // "uid" and "self" are only needed for some internal stuff, so remove it from here
\r
2214 unset($ret["sender"]["uid"]);
\r
2215 unset($ret["sender"]["self"]);
\r
2216 unset($ret["recipient"]["uid"]);
\r
2217 unset($ret["recipient"]["self"]);
\r
2219 //don't send title to regular StatusNET requests to avoid confusing these apps
\r
2220 if (x($_GET, 'getText')) {
\r
2221 $ret['title'] = $item['title'] ;
\r
2222 if ($_GET['getText'] == 'html') {
\r
2223 $ret['text'] = bbcode($item['body'], false, false);
\r
2224 } elseif ($_GET['getText'] == 'plain') {
\r
2225 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
\r
2226 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
\r
2229 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
\r
2231 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
\r
2232 unset($ret['sender']);
\r
2233 unset($ret['recipient']);
\r
2239 function api_convert_item($item) {
\r
2240 $body = $item['body'];
\r
2241 $attachments = api_get_attachments($body);
\r
2243 // Workaround for ostatus messages where the title is identically to the body
\r
2244 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
\r
2245 $statusbody = trim(html2plain($html, 0));
\r
2247 // handle data: images
\r
2248 $statusbody = api_format_items_embeded_images($item,$statusbody);
\r
2250 $statustitle = trim($item['title']);
\r
2252 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false)) {
\r
2253 $statustext = trim($statusbody);
\r
2255 $statustext = trim($statustitle."\n\n".$statusbody);
\r
2258 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000)) {
\r
2259 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
\r
2262 $statushtml = trim(bbcode($body, false, false));
\r
2264 $search = array("<br>", "<blockquote>", "</blockquote>",
\r
2265 "<h1>", "</h1>", "<h2>", "</h2>",
\r
2266 "<h3>", "</h3>", "<h4>", "</h4>",
\r
2267 "<h5>", "</h5>", "<h6>", "</h6>");
\r
2268 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
\r
2269 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
\r
2270 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
\r
2271 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
\r
2272 $statushtml = str_replace($search, $replace, $statushtml);
\r
2274 if ($item['title'] != "") {
\r
2275 $statushtml = "<h4>" . bbcode($item['title']) . "</h4>\n" . $statushtml;
\r
2278 $entities = api_get_entitities($statustext, $body);
\r
2281 "text" => $statustext,
\r
2282 "html" => $statushtml,
\r
2283 "attachments" => $attachments,
\r
2284 "entities" => $entities
\r
2288 function api_get_attachments(&$body) {
\r
2291 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
\r
2293 $URLSearchString = "^\[\]";
\r
2294 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
\r
2300 $attachments = array();
\r
2302 foreach ($images[1] AS $image) {
\r
2303 $imagedata = get_photo_info($image);
\r
2306 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
\r
2310 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
\r
2311 foreach ($images[0] AS $orig) {
\r
2312 $body = str_replace($orig, "", $body);
\r
2316 return $attachments;
\r
2319 function api_get_entitities(&$text, $bbcode) {
\r
2322 * Links at the first character of the post
\r
2327 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
\r
2329 if ($include_entities != "true") {
\r
2331 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
\r
2333 foreach ($images[1] AS $image) {
\r
2334 $replace = proxy_url($image);
\r
2335 $text = str_replace($image, $replace, $text);
\r
2340 $bbcode = bb_CleanPictureLinks($bbcode);
\r
2342 // Change pure links in text to bbcode uris
\r
2343 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
\r
2345 $entities = array();
\r
2346 $entities["hashtags"] = array();
\r
2347 $entities["symbols"] = array();
\r
2348 $entities["urls"] = array();
\r
2349 $entities["user_mentions"] = array();
\r
2351 $URLSearchString = "^\[\]";
\r
2353 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
\r
2355 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
\r
2356 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
\r
2357 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
\r
2359 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
\r
2360 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
\r
2361 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
\r
2363 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
\r
2364 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
\r
2365 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
\r
2367 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
\r
2369 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
\r
2370 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
\r
2372 $ordered_urls = array();
\r
2373 foreach ($urls[1] AS $id => $url) {
\r
2374 //$start = strpos($text, $url, $offset);
\r
2375 $start = iconv_strpos($text, $url, 0, "UTF-8");
\r
2376 if (!($start === false)) {
\r
2377 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
\r
2381 ksort($ordered_urls);
\r
2384 //foreach ($urls[1] AS $id=>$url) {
\r
2385 foreach ($ordered_urls AS $url) {
\r
2386 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
\r
2387 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
\r
2388 $display_url = $url["title"];
\r
2390 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
\r
2391 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
\r
2393 if (strlen($display_url) > 26)
\r
2394 $display_url = substr($display_url, 0, 25)."…";
\r
2397 //$start = strpos($text, $url, $offset);
\r
2398 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
\r
2399 if (!($start === false)) {
\r
2400 $entities["urls"][] = array("url" => $url["url"],
\r
2401 "expanded_url" => $url["url"],
\r
2402 "display_url" => $display_url,
\r
2403 "indices" => array($start, $start+strlen($url["url"])));
\r
2404 $offset = $start + 1;
\r
2408 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
\r
2409 $ordered_images = array();
\r
2410 foreach ($images[1] AS $image) {
\r
2411 //$start = strpos($text, $url, $offset);
\r
2412 $start = iconv_strpos($text, $image, 0, "UTF-8");
\r
2413 if (!($start === false))
\r
2414 $ordered_images[$start] = $image;
\r
2416 //$entities["media"] = array();
\r
2419 foreach ($ordered_images AS $url) {
\r
2420 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
\r
2421 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
\r
2423 if (strlen($display_url) > 26)
\r
2424 $display_url = substr($display_url, 0, 25)."…";
\r
2426 $start = iconv_strpos($text, $url, $offset, "UTF-8");
\r
2427 if (!($start === false)) {
\r
2428 $image = get_photo_info($url);
\r
2430 // If image cache is activated, then use the following sizes:
\r
2431 // thumb (150), small (340), medium (600) and large (1024)
\r
2432 if (!get_config("system", "proxy_disabled")) {
\r
2433 $media_url = proxy_url($url);
\r
2436 $scale = scale_image($image[0], $image[1], 150);
\r
2437 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
\r
2439 if (($image[0] > 150) OR ($image[1] > 150)) {
\r
2440 $scale = scale_image($image[0], $image[1], 340);
\r
2441 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
\r
2444 $scale = scale_image($image[0], $image[1], 600);
\r
2445 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
\r
2447 if (($image[0] > 600) OR ($image[1] > 600)) {
\r
2448 $scale = scale_image($image[0], $image[1], 1024);
\r
2449 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
\r
2452 $media_url = $url;
\r
2453 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
\r
2456 $entities["media"][] = array(
\r
2458 "id_str" => (string)$start+1,
\r
2459 "indices" => array($start, $start+strlen($url)),
\r
2460 "media_url" => normalise_link($media_url),
\r
2461 "media_url_https" => $media_url,
\r
2463 "display_url" => $display_url,
\r
2464 "expanded_url" => $url,
\r
2465 "type" => "photo",
\r
2466 "sizes" => $sizes);
\r
2468 $offset = $start + 1;
\r
2474 function api_format_items_embeded_images(&$item, $text) {
\r
2475 $text = preg_replace_callback(
\r
2476 "|data:image/([^;]+)[^=]+=*|m",
\r
2477 function($match) use ($item) {
\r
2478 return App::get_baseurl()."/display/".$item['guid'];
\r
2486 * @brief return <a href='url'>name</a> as array
\r
2488 * @param string $txt
\r
2493 function api_contactlink_to_array($txt) {
\r
2495 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
\r
2496 if ($r && count($match)==3) {
\r
2498 'name' => $match[2],
\r
2499 'url' => $match[1]
\r
2512 * @brief return likes, dislikes and attend status for item
\r
2514 * @param array $item
\r
2516 * likes => int count
\r
2517 * dislikes => int count
\r
2519 function api_format_items_activities(&$item, $type = "json") {
\r
2523 $activities = array(
\r
2524 'like' => array(),
\r
2525 'dislike' => array(),
\r
2526 'attendyes' => array(),
\r
2527 'attendno' => array(),
\r
2528 'attendmaybe' => array(),
\r
2531 $items = q('SELECT * FROM item
\r
2532 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
\r
2533 intval($item['uid']),
\r
2534 dbesc($item['uri']));
\r
2536 foreach ($items as $i) {
\r
2537 // not used as result should be structured like other user data
\r
2538 //builtin_activity_puller($i, $activities);
\r
2540 // get user data and add it to the array of the activity
\r
2541 $user = api_get_user($a, $i['author-link']);
\r
2542 switch ($i['verb']) {
\r
2543 case ACTIVITY_LIKE:
\r
2544 $activities['like'][] = $user;
\r
2546 case ACTIVITY_DISLIKE:
\r
2547 $activities['dislike'][] = $user;
\r
2549 case ACTIVITY_ATTEND:
\r
2550 $activities['attendyes'][] = $user;
\r
2552 case ACTIVITY_ATTENDNO:
\r
2553 $activities['attendno'][] = $user;
\r
2555 case ACTIVITY_ATTENDMAYBE:
\r
2556 $activities['attendmaybe'][] = $user;
\r
2563 if ($type == "xml") {
\r
2564 $xml_activities = array();
\r
2565 foreach ($activities as $k => $v) {
\r
2566 // change xml element from "like" to "friendica:like"
\r
2567 $xml_activities["friendica:".$k] = $v;
\r
2568 // add user data into xml output
\r
2570 foreach ($v as $user)
\r
2571 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
\r
2573 $activities = $xml_activities;
\r
2576 return $activities;
\r
2582 * @brief return data from profiles
\r
2584 * @param array $profile array containing data from db table 'profile'
\r
2585 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
2588 function api_format_items_profiles(&$profile = null, $type = "json") {
\r
2589 if ($profile != null) {
\r
2590 $profile = array('profile_id' => $profile['id'],
\r
2591 'profile_name' => $profile['profile-name'],
\r
2592 'is_default' => $profile['is-default'] ? true : false,
\r
2593 'hide_friends'=> $profile['hide-friends'] ? true : false,
\r
2594 'profile_photo' => $profile['photo'],
\r
2595 'profile_thumb' => $profile['thumb'],
\r
2596 'publish' => $profile['publish'] ? true : false,
\r
2597 'net_publish' => $profile['net-publish'] ? true : false,
\r
2598 'description' => $profile['pdesc'],
\r
2599 'date_of_birth' => $profile['dob'],
\r
2600 'address' => $profile['address'],
\r
2601 'city' => $profile['locality'],
\r
2602 'region' => $profile['region'],
\r
2603 'postal_code' => $profile['postal-code'],
\r
2604 'country' => $profile['country-name'],
\r
2605 'hometown' => $profile['hometown'],
\r
2606 'gender' => $profile['gender'],
\r
2607 'marital' => $profile['marital'],
\r
2608 'marital_with' => $profile['with'],
\r
2609 'marital_since' => $profile['howlong'],
\r
2610 'sexual' => $profile['sexual'],
\r
2611 'politic' => $profile['politic'],
\r
2612 'religion' => $profile['religion'],
\r
2613 'public_keywords' => $profile['pub_keywords'],
\r
2614 'private_keywords' => $profile['prv_keywords'],
\r
2615 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
\r
2616 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
\r
2617 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
\r
2618 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
\r
2619 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
\r
2620 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
\r
2621 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
\r
2622 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
\r
2623 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
\r
2624 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
\r
2625 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
\r
2626 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
\r
2627 'homepage' => $profile['homepage'],
\r
2634 * @brief format items to be returned by api
\r
2636 * @param array $r array of items
\r
2637 * @param array $user_info
\r
2638 * @param bool $filter_user filter items by $user_info
\r
2640 function api_format_items($r,$user_info, $filter_user = false, $type = "json") {
\r
2646 foreach ($r as $item) {
\r
2648 localize_item($item);
\r
2649 list($status_user, $owner_user) = api_item_get_user($a, $item);
\r
2651 // Look if the posts are matching if they should be filtered by user id
\r
2652 if ($filter_user AND ($status_user["id"] != $user_info["id"])) {
\r
2656 $in_reply_to = api_in_reply_to($item);
\r
2658 $converted = api_convert_item($item);
\r
2660 if ($type == "xml") {
\r
2661 $geo = "georss:point";
\r
2667 'text' => $converted["text"],
\r
2668 'truncated' => False,
\r
2669 'created_at'=> api_date($item['created']),
\r
2670 'in_reply_to_status_id' => $in_reply_to['status_id'],
\r
2671 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
\r
2672 'source' => (($item['app']) ? $item['app'] : 'web'),
\r
2673 'id' => intval($item['id']),
\r
2674 'id_str' => (string) intval($item['id']),
\r
2675 'in_reply_to_user_id' => $in_reply_to['user_id'],
\r
2676 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
\r
2677 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
\r
2679 'favorited' => $item['starred'] ? true : false,
\r
2680 'user' => $status_user ,
\r
2681 'friendica_owner' => $owner_user,
\r
2682 //'entities' => NULL,
\r
2683 'statusnet_html' => $converted["html"],
\r
2684 'statusnet_conversation_id' => $item['parent'],
\r
2685 'friendica_activities' => api_format_items_activities($item, $type),
\r
2688 if (count($converted["attachments"]) > 0) {
\r
2689 $status["attachments"] = $converted["attachments"];
\r
2692 if (count($converted["entities"]) > 0) {
\r
2693 $status["entities"] = $converted["entities"];
\r
2696 if (($item['item_network'] != "") AND ($status["source"] == 'web')) {
\r
2697 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
\r
2698 } elseif (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
\r
2699 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
\r
2703 // Retweets are only valid for top postings
\r
2704 // It doesn't work reliable with the link if its a feed
\r
2705 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
\r
2707 // $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
\r
2710 if ($item["id"] == $item["parent"]) {
\r
2711 $retweeted_item = api_share_as_retweet($item);
\r
2712 if ($retweeted_item !== false) {
\r
2713 $retweeted_status = $status;
\r
2715 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
\r
2716 } catch( BadRequestException $e ) {
\r
2717 // user not found. should be found?
\r
2718 /// @todo check if the user should be always found
\r
2719 $retweeted_status["user"] = array();
\r
2722 $rt_converted = api_convert_item($retweeted_item);
\r
2724 $retweeted_status['text'] = $rt_converted["text"];
\r
2725 $retweeted_status['statusnet_html'] = $rt_converted["html"];
\r
2726 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
\r
2727 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
\r
2728 $status['retweeted_status'] = $retweeted_status;
\r
2732 // "uid" and "self" are only needed for some internal stuff, so remove it from here
\r
2733 unset($status["user"]["uid"]);
\r
2734 unset($status["user"]["self"]);
\r
2736 if ($item["coord"] != "") {
\r
2737 $coords = explode(' ',$item["coord"]);
\r
2738 if (count($coords) == 2) {
\r
2739 if ($type == "json")
\r
2740 $status["geo"] = array('type' => 'Point',
\r
2741 'coordinates' => array((float) $coords[0],
\r
2742 (float) $coords[1]));
\r
2743 else // Not sure if this is the official format - if someone founds a documentation we can check
\r
2744 $status["georss:point"] = $item["coord"];
\r
2752 function api_account_rate_limit_status($type) {
\r
2754 if ($type == "xml") {
\r
2756 'remaining-hits' => '150',
\r
2757 '@attributes' => array("type" => "integer"),
\r
2758 'hourly-limit' => '150',
\r
2759 '@attributes2' => array("type" => "integer"),
\r
2760 'reset-time' => datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME),
\r
2761 '@attributes3' => array("type" => "datetime"),
\r
2762 'reset_time_in_seconds' => strtotime('now + 1 hour'),
\r
2763 '@attributes4' => array("type" => "integer"),
\r
2767 'reset_time_in_seconds' => strtotime('now + 1 hour'),
\r
2768 'remaining_hits' => '150',
\r
2769 'hourly_limit' => '150',
\r
2770 'reset_time' => api_date(datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME)),
\r
2774 return api_format_data('hash', $type, array('hash' => $hash));
\r
2777 /// @TODO move to top of file or somwhere better
\r
2778 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
\r
2780 function api_help_test($type) {
\r
2781 if ($type == 'xml') {
\r
2787 return api_format_data('ok', $type, array("ok" => $ok));
\r
2790 /// @TODO move to top of file or somwhere better
\r
2791 api_register_func('api/help/test','api_help_test', false);
\r
2793 function api_lists($type) {
\r
2795 /// @TODO $ret is not filled here?
\r
2796 return api_format_data('lists', $type, array("lists_list" => $ret));
\r
2799 /// @TODO move to top of file or somwhere better
\r
2800 api_register_func('api/lists','api_lists',true);
\r
2802 function api_lists_list($type) {
\r
2804 /// @TODO $ret is not filled here?
\r
2805 return api_format_data('lists', $type, array("lists_list" => $ret));
\r
2808 /// @TODO move to top of file or somwhere better
\r
2809 api_register_func('api/lists/list','api_lists_list',true);
\r
2812 * https://dev.twitter.com/docs/api/1/get/statuses/friends
\r
2813 * This function is deprecated by Twitter
\r
2814 * returns: json, xml
\r
2816 function api_statuses_f($type, $qtype) {
\r
2820 if (api_user() === false) {
\r
2821 throw new ForbiddenException();
\r
2824 $user_info = api_get_user($a);
\r
2826 if (x($_GET, 'cursor') && $_GET['cursor']=='undefined') {
\r
2827 /* this is to stop Hotot to load friends multiple times
\r
2828 * I'm not sure if I'm missing return something or
\r
2829 * is a bug in hotot. Workaround, meantime
\r
2833 return array('$users' => $ret);*/
\r
2837 if ($qtype == 'friends') {
\r
2838 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
\r
2840 if ($qtype == 'followers') {
\r
2841 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
\r
2844 // friends and followers only for self
\r
2845 if ($user_info['self'] == 0) {
\r
2846 $sql_extra = " AND false ";
\r
2849 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra",
\r
2850 intval(api_user())
\r
2854 foreach ($r as $cid) {
\r
2855 $user = api_get_user($a, $cid['nurl']);
\r
2856 // "uid" and "self" are only needed for some internal stuff, so remove it from here
\r
2857 unset($user["uid"]);
\r
2858 unset($user["self"]);
\r
2865 return array('user' => $ret);
\r
2869 function api_statuses_friends($type) {
\r
2870 $data = api_statuses_f($type, "friends");
\r
2871 if ($data === false) {
\r
2874 return api_format_data("users", $type, $data);
\r
2877 function api_statuses_followers($type) {
\r
2878 $data = api_statuses_f($type, "followers");
\r
2879 if ($data === false) {
\r
2882 return api_format_data("users", $type, $data);
\r
2885 /// @TODO move to top of file or somewhere better
\r
2886 api_register_func('api/statuses/friends','api_statuses_friends',true);
\r
2887 api_register_func('api/statuses/followers','api_statuses_followers',true);
\r
2889 function api_statusnet_config($type) {
\r
2893 $name = $a->config['sitename'];
\r
2894 $server = $a->get_hostname();
\r
2895 $logo = App::get_baseurl() . '/images/friendica-64.png';
\r
2896 $email = $a->config['admin_email'];
\r
2897 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
\r
2898 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
\r
2899 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
\r
2900 if ($a->config['api_import_size']) {
\r
2901 $texlimit = string($a->config['api_import_size']);
\r
2903 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
\r
2904 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',App::get_baseurl()) : '');
\r
2907 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
\r
2908 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
\r
2909 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
\r
2910 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
\r
2911 'shorturllength' => '30',
\r
2912 'friendica' => array(
\r
2913 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
\r
2914 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
\r
2915 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
\r
2916 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
\r
2921 return api_format_data('config', $type, array('config' => $config));
\r
2925 /// @TODO move to top of file or somewhere better
\r
2926 api_register_func('api/gnusocial/config','api_statusnet_config', false);
\r
2927 api_register_func('api/statusnet/config','api_statusnet_config', false);
\r
2929 function api_statusnet_version($type) {
\r
2931 $fake_statusnet_version = "0.9.7";
\r
2933 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
\r
2936 /// @TODO move to top of file or somewhere better
\r
2937 api_register_func('api/gnusocial/version','api_statusnet_version', false);
\r
2938 api_register_func('api/statusnet/version','api_statusnet_version', false);
\r
2941 * @todo use api_format_data() to return data
\r
2943 function api_ff_ids($type,$qtype) {
\r
2947 if (! api_user()) {
\r
2948 throw new ForbiddenException();
\r
2951 $user_info = api_get_user($a);
\r
2953 if ($qtype == 'friends') {
\r
2954 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
\r
2956 if ($qtype == 'followers') {
\r
2957 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
\r
2960 if (!$user_info["self"]) {
\r
2961 $sql_extra = " AND false ";
\r
2964 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
\r
2966 $r = q("SELECT `pcontact`.`id` FROM `contact`
\r
2967 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
\r
2968 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
\r
2969 intval(api_user())
\r
2972 if (!dbm::is_result($r)) {
\r
2977 foreach ($r as $rr) {
\r
2978 if ($stringify_ids) {
\r
2979 $ids[] = $rr['id'];
\r
2981 $ids[] = intval($rr['id']);
\r
2985 return api_format_data("ids", $type, array('id' => $ids));
\r
2988 function api_friends_ids($type) {
\r
2989 return api_ff_ids($type,'friends');
\r
2992 function api_followers_ids($type) {
\r
2993 return api_ff_ids($type,'followers');
\r
2996 /// @TODO move to top of file or somewhere better
\r
2997 api_register_func('api/friends/ids','api_friends_ids',true);
\r
2998 api_register_func('api/followers/ids','api_followers_ids',true);
\r
3000 function api_direct_messages_new($type) {
\r
3004 if (api_user() === false) throw new ForbiddenException();
\r
3006 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
\r
3008 $sender = api_get_user($a);
\r
3010 if ($_POST['screen_name']) {
\r
3011 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
\r
3012 intval(api_user()),
\r
3013 dbesc($_POST['screen_name']));
\r
3015 // Selecting the id by priority, friendica first
\r
3016 api_best_nickname($r);
\r
3018 $recipient = api_get_user($a, $r[0]['nurl']);
\r
3020 $recipient = api_get_user($a, $_POST['user_id']);
\r
3024 if (x($_REQUEST, 'replyto')) {
\r
3025 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
\r
3026 intval(api_user()),
\r
3027 intval($_REQUEST['replyto']));
\r
3028 $replyto = $r[0]['parent-uri'];
\r
3029 $sub = $r[0]['title'];
\r
3031 if (x($_REQUEST, 'title')) {
\r
3032 $sub = $_REQUEST['title'];
\r
3034 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'],0,10)."...":$_POST['text']);
\r
3038 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
\r
3041 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
\r
3042 $ret = api_format_messages($r[0], $recipient, $sender);
\r
3044 $ret = array("error"=>$id);
\r
3047 $data = array('direct_message'=>$ret);
\r
3052 $data = api_rss_extra($a, $data, $user_info);
\r
3055 return api_format_data("direct-messages", $type, $data);
\r
3059 /// @TODO move to top of file or somewhere better
\r
3060 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
\r
3063 * @brief delete a direct_message from mail table through api
\r
3065 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
3068 function api_direct_messages_destroy($type) {
\r
3071 if (api_user() === false) {
\r
3072 throw new ForbiddenException();
\r
3076 $user_info = api_get_user($a);
\r
3078 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
\r
3080 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
\r
3081 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
\r
3082 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
\r
3084 $uid = $user_info['uid'];
\r
3085 // error if no id or parenturi specified (for clients posting parent-uri as well)
\r
3086 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
\r
3087 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
\r
3088 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
\r
3091 // BadRequestException if no id specified (for clients using Twitter API)
\r
3093 throw new BadRequestException('Message id not specified');
\r
3096 // add parent-uri to sql command if specified by calling app
\r
3097 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
\r
3099 // get data of the specified message id
\r
3100 $r = q("SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
\r
3104 // error message if specified id is not in database
\r
3105 if (!dbm::is_result($r)) {
\r
3106 if ($verbose == "true") {
\r
3107 $answer = array('result' => 'error', 'message' => 'message id not in database');
\r
3108 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
\r
3110 /// @todo BadRequestException ok for Twitter API clients?
\r
3111 throw new BadRequestException('message id not in database');
\r
3115 $result = q("DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
\r
3119 if ($verbose == "true") {
\r
3122 $answer = array('result' => 'ok', 'message' => 'message deleted');
\r
3123 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
\r
3125 $answer = array('result' => 'error', 'message' => 'unknown error');
\r
3126 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
\r
3129 /// @todo return JSON data like Twitter API not yet implemented
\r
3133 /// @TODO move to top of file or somewhere better
\r
3134 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
\r
3136 function api_direct_messages_box($type, $box, $verbose) {
\r
3140 if (api_user() === false) {
\r
3141 throw new ForbiddenException();
\r
3145 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
\r
3146 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
\r
3151 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
\r
3152 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
\r
3154 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
\r
3155 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
\r
3157 // caller user info
\r
3158 unset($_REQUEST["user_id"]);
\r
3159 unset($_GET["user_id"]);
\r
3161 unset($_REQUEST["screen_name"]);
\r
3162 unset($_GET["screen_name"]);
\r
3164 $user_info = api_get_user($a);
\r
3165 $profile_url = $user_info["url"];
\r
3168 $start = $page * $count;
\r
3171 if ($box=="sentbox") {
\r
3172 $sql_extra = "`mail`.`from-url`='" . dbesc( $profile_url ) . "'";
\r
3173 } elseif ($box == "conversation") {
\r
3174 $sql_extra = "`mail`.`parent-uri`='" . dbesc( $_GET["uri"] ) . "'";
\r
3175 } elseif ($box == "all") {
\r
3176 $sql_extra = "true";
\r
3177 } elseif ($box == "inbox") {
\r
3178 $sql_extra = "`mail`.`from-url`!='" . dbesc( $profile_url ) . "'";
\r
3181 if ($max_id > 0) {
\r
3182 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
\r
3185 if ($user_id != "") {
\r
3186 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
\r
3187 } elseif ($screen_name !="") {
\r
3188 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
\r
3191 $r = q("SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND $sql_extra AND `mail`.`id` > %d ORDER BY `mail`.`id` DESC LIMIT %d,%d",
\r
3192 intval(api_user()),
\r
3193 intval($since_id),
\r
3194 intval($start), intval($count)
\r
3196 if ($verbose == "true" && !dbm::is_result($r)) {
\r
3197 $answer = array('result' => 'error', 'message' => 'no mails available');
\r
3198 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
\r
3202 foreach ($r as $item) {
\r
3203 if ($box == "inbox" || $item['from-url'] != $profile_url) {
\r
3204 $recipient = $user_info;
\r
3205 $sender = api_get_user($a,normalise_link($item['contact-url']));
\r
3206 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
\r
3207 $recipient = api_get_user($a,normalise_link($item['contact-url']));
\r
3208 $sender = $user_info;
\r
3211 $ret[] = api_format_messages($item, $recipient, $sender);
\r
3215 $data = array('direct_message' => $ret);
\r
3219 $data = api_rss_extra($a, $data, $user_info);
\r
3222 return api_format_data("direct-messages", $type, $data);
\r
3226 function api_direct_messages_sentbox($type) {
\r
3227 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
\r
3228 return api_direct_messages_box($type, "sentbox", $verbose);
\r
3231 function api_direct_messages_inbox($type) {
\r
3232 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
\r
3233 return api_direct_messages_box($type, "inbox", $verbose);
\r
3236 function api_direct_messages_all($type) {
\r
3237 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
\r
3238 return api_direct_messages_box($type, "all", $verbose);
\r
3241 function api_direct_messages_conversation($type) {
\r
3242 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
\r
3243 return api_direct_messages_box($type, "conversation", $verbose);
\r
3246 /// @TODO move to top of file or somewhere better
\r
3247 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
\r
3248 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
\r
3249 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
\r
3250 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
\r
3252 function api_oauth_request_token($type) {
\r
3254 $oauth = new FKOAuth1();
\r
3255 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
\r
3256 } catch (Exception $e) {
\r
3257 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
\r
3264 function api_oauth_access_token($type) {
\r
3266 $oauth = new FKOAuth1();
\r
3267 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
\r
3268 } catch (Exception $e) {
\r
3269 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
\r
3275 /// @TODO move to top of file or somewhere better
\r
3276 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
\r
3277 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
\r
3281 * @brief delete a complete photoalbum with all containing photos from database through api
\r
3283 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
3286 function api_fr_photoalbum_delete($type) {
\r
3287 if (api_user() === false) {
\r
3288 throw new ForbiddenException();
\r
3291 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : "");
\r
3293 // we do not allow calls without album string
\r
3294 if ($album == "") {
\r
3295 throw new BadRequestException("no albumname specified");
\r
3297 // check if album is existing
\r
3298 $r = q("SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
\r
3299 intval(api_user()),
\r
3301 if (!dbm::is_result($r))
\r
3302 throw new BadRequestException("album not available");
\r
3304 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
\r
3305 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
\r
3306 foreach ($r as $rr) {
\r
3307 $photo_item = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
\r
3308 intval(local_user()),
\r
3309 dbesc($rr['resource-id'])
\r
3312 if (!dbm::is_result($photo_item)) {
\r
3313 throw new InternalServerErrorException("problem with deleting items occured");
\r
3315 drop_item($photo_item[0]['id'],false);
\r
3318 // now let's delete all photos from the album
\r
3319 $result = q("DELETE FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
\r
3320 intval(api_user()),
\r
3323 // return success of deletion or error message
\r
3325 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
\r
3326 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
\r
3328 throw new BadRequestException("unknown error - deleting from database failed");
\r
3334 * @brief update the name of the album for all photos of an album
\r
3336 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
3339 function api_fr_photoalbum_update($type) {
\r
3340 if (api_user() === false) {
\r
3341 throw new ForbiddenException();
\r
3344 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : "");
\r
3345 $album_new = (x($_REQUEST,'album_new') ? $_REQUEST['album_new'] : "");
\r
3347 // we do not allow calls without album string
\r
3348 if ($album == "") {
\r
3349 throw new BadRequestException("no albumname specified");
\r
3351 if ($album_new == "") {
\r
3352 throw new BadRequestException("no new albumname specified");
\r
3354 // check if album is existing
\r
3355 $r = q("SELECT * FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
\r
3356 intval(api_user()),
\r
3358 if (!dbm::is_result($r)) {
\r
3359 throw new BadRequestException("album not available");
\r
3361 // now let's update all photos to the albumname
\r
3362 $result = q("UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
\r
3363 dbesc($album_new),
\r
3364 intval(api_user()),
\r
3367 // return success of updating or error message
\r
3369 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
\r
3370 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
\r
3372 throw new BadRequestException("unknown error - updating in database failed");
\r
3378 * @brief list all photos of the authenticated user
\r
3380 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
3383 function api_fr_photos_list($type) {
\r
3384 if (api_user() === false) {
\r
3385 throw new ForbiddenException();
\r
3387 $r = q("SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
\r
3388 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
\r
3389 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
\r
3390 intval(local_user())
\r
3392 $typetoext = array(
\r
3393 'image/jpeg' => 'jpg',
\r
3394 'image/png' => 'png',
\r
3395 'image/gif' => 'gif'
\r
3397 $data = array('photo'=>array());
\r
3398 if (dbm::is_result($r)) {
\r
3399 foreach ($r as $rr) {
\r
3401 $photo['id'] = $rr['resource-id'];
\r
3402 $photo['album'] = $rr['album'];
\r
3403 $photo['filename'] = $rr['filename'];
\r
3404 $photo['type'] = $rr['type'];
\r
3405 $thumb = App::get_baseurl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
\r
3406 $photo['created'] = $rr['created'];
\r
3407 $photo['edited'] = $rr['edited'];
\r
3408 $photo['desc'] = $rr['desc'];
\r
3410 if ($type == "xml") {
\r
3411 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
\r
3413 $photo['thumb'] = $thumb;
\r
3414 $data['photo'][] = $photo;
\r
3418 return api_format_data("photos", $type, $data);
\r
3422 * @brief upload a new photo or change an existing photo
\r
3424 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
3427 function api_fr_photo_create_update($type) {
\r
3428 if (api_user() === false) {
\r
3429 throw new ForbiddenException();
\r
3432 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
\r
3433 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
\r
3434 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : null);
\r
3435 $album_new = (x($_REQUEST,'album_new') ? $_REQUEST['album_new'] : null);
\r
3436 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
\r
3437 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
\r
3438 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
\r
3439 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
\r
3440 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
\r
3442 // do several checks on input parameters
\r
3443 // we do not allow calls without album string
\r
3444 if ($album == null) {
\r
3445 throw new BadRequestException("no albumname specified");
\r
3447 // if photo_id == null --> we are uploading a new photo
\r
3448 if ($photo_id == null) {
\r
3451 // error if no media posted in create-mode
\r
3452 if (!x($_FILES,'media')) {
\r
3454 throw new BadRequestException("no media data submitted");
\r
3457 // album_new will be ignored in create-mode
\r
3462 // check if photo is existing in database
\r
3463 $r = q("SELECT * FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
\r
3464 intval(api_user()),
\r
3467 if (!dbm::is_result($r)) {
\r
3468 throw new BadRequestException("photo not available");
\r
3472 // checks on acl strings provided by clients
\r
3473 $acl_input_error = false;
\r
3474 $acl_input_error |= check_acl_input($allow_cid);
\r
3475 $acl_input_error |= check_acl_input($deny_cid);
\r
3476 $acl_input_error |= check_acl_input($allow_gid);
\r
3477 $acl_input_error |= check_acl_input($deny_gid);
\r
3478 if ($acl_input_error) {
\r
3479 throw new BadRequestException("acl data invalid");
\r
3481 // now let's upload the new media in create-mode
\r
3482 if ($mode == "create") {
\r
3483 $media = $_FILES['media'];
\r
3484 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
\r
3486 // return success of updating or error message
\r
3487 if (!is_null($data)) {
\r
3488 return api_format_data("photo_create", $type, $data);
\r
3490 throw new BadRequestException("unknown error - uploading photo failed, see Friendica log for more information");
\r
3494 // now let's do the changes in update-mode
\r
3495 if ($mode == "update") {
\r
3498 if (!is_null($desc)) {
\r
3499 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
\r
3502 if (!is_null($album_new)) {
\r
3503 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
\r
3506 if (!is_null($allow_cid)) {
\r
3507 $allow_cid = trim($allow_cid);
\r
3508 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
\r
3511 if (!is_null($deny_cid)) {
\r
3512 $deny_cid = trim($deny_cid);
\r
3513 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
\r
3516 if (!is_null($allow_gid)) {
\r
3517 $allow_gid = trim($allow_gid);
\r
3518 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
\r
3521 if (!is_null($deny_gid)) {
\r
3522 $deny_gid = trim($deny_gid);
\r
3523 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
\r
3527 if ($sql_extra != "") {
\r
3528 $nothingtodo = false;
\r
3529 $result = q("UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
\r
3531 datetime_convert(), // update edited timestamp
\r
3532 intval(api_user()),
\r
3536 $nothingtodo = true;
\r
3539 if (x($_FILES,'media')) {
\r
3540 $nothingtodo = false;
\r
3541 $media = $_FILES['media'];
\r
3542 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
\r
3543 if (!is_null($data)) {
\r
3544 return api_format_data("photo_update", $type, $data);
\r
3548 // return success of updating or error message
\r
3550 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
\r
3551 return api_format_data("photo_update", $type, array('$result' => $answer));
\r
3553 if ($nothingtodo) {
\r
3554 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
\r
3555 return api_format_data("photo_update", $type, array('$result' => $answer));
\r
3557 throw new BadRequestException("unknown error - update photo entry in database failed");
\r
3560 throw new BadRequestException("unknown error - this error on uploading or updating a photo should never happen");
\r
3565 * @brief delete a single photo from the database through api
\r
3567 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
3570 function api_fr_photo_delete($type) {
\r
3571 if (api_user() === false) {
\r
3572 throw new ForbiddenException();
\r
3575 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
\r
3577 // do several checks on input parameters
\r
3578 // we do not allow calls without photo id
\r
3579 if ($photo_id == null) {
\r
3580 throw new BadRequestException("no photo_id specified");
\r
3582 // check if photo is existing in database
\r
3583 $r = q("SELECT * FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
\r
3584 intval(api_user()),
\r
3587 if (!dbm::is_result($r)) {
\r
3588 throw new BadRequestException("photo not available");
\r
3590 // now we can perform on the deletion of the photo
\r
3591 $result = q("DELETE FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
\r
3592 intval(api_user()),
\r
3593 dbesc($photo_id));
\r
3595 // return success of deletion or error message
\r
3597 // retrieve the id of the parent element (the photo element)
\r
3598 $photo_item = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
\r
3599 intval(local_user()),
\r
3603 if (!dbm::is_result($photo_item)) {
\r
3604 throw new InternalServerErrorException("problem with deleting items occured");
\r
3606 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
\r
3607 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
\r
3608 drop_item($photo_item[0]['id'], false);
\r
3610 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
\r
3611 return api_format_data("photo_delete", $type, array('$result' => $answer));
\r
3613 throw new InternalServerErrorException("unknown error on deleting photo from database table");
\r
3619 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
\r
3621 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
3624 function api_fr_photo_detail($type) {
\r
3625 if (api_user() === false) {
\r
3626 throw new ForbiddenException();
\r
3628 if (!x($_REQUEST, 'photo_id')) {
\r
3629 throw new BadRequestException("No photo id.");
\r
3632 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
\r
3633 $photo_id = $_REQUEST['photo_id'];
\r
3635 // prepare json/xml output with data from database for the requested photo
\r
3636 $data = prepare_photo_data($type, $scale, $photo_id);
\r
3638 return api_format_data("photo_detail", $type, $data);
\r
3643 * @brief updates the profile image for the user (either a specified profile or the default profile)
\r
3645 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
3648 function api_account_update_profile_image($type) {
\r
3649 if (api_user() === false) {
\r
3650 throw new ForbiddenException();
\r
3653 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
\r
3655 // error if image data is missing
\r
3656 if (!x($_FILES, 'image')) {
\r
3657 throw new BadRequestException("no media data submitted");
\r
3660 // check if specified profile id is valid
\r
3661 if ($profileid != 0) {
\r
3662 $r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
\r
3663 intval(api_user()),
\r
3664 intval($profileid));
\r
3665 // error message if specified profile id is not in database
\r
3666 if (!dbm::is_result($r)) {
\r
3667 throw new BadRequestException("profile_id not available");
\r
3669 $is_default_profile = $r['profile'];
\r
3671 $is_default_profile = 1;
\r
3674 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
\r
3676 if (x($_FILES, 'image')) {
\r
3677 $media = $_FILES['image'];
\r
3678 } elseif (x($_FILES, 'media')) {
\r
3679 $media = $_FILES['media'];
\r
3681 // save new profile image
\r
3682 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
\r
3685 if (is_array($media['type'])) {
\r
3686 $filetype = $media['type'][0];
\r
3688 $filetype = $media['type'];
\r
3690 if ($filetype == "image/jpeg") {
\r
3692 } elseif ($filetype == "image/png") {
\r
3695 // change specified profile or all profiles to the new resource-id
\r
3696 if ($is_default_profile) {
\r
3697 $r = q("UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
\r
3698 dbesc($data['photo']['id']),
\r
3699 intval(local_user())
\r
3702 $r = q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
\r
3703 dbesc(App::get_baseurl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
\r
3704 dbesc(App::get_baseurl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
\r
3705 dbesc(App::get_baseurl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
\r
3706 intval(local_user())
\r
3709 $r = q("update profile set photo = '%s', thumb = '%s' where id = %d and uid = %d",
\r
3710 dbesc(App::get_baseurl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
\r
3711 dbesc(App::get_baseurl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
\r
3712 intval($_REQUEST['profile']),
\r
3713 intval(local_user())
\r
3717 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
\r
3718 // so that browsers will do a cache update unconditionally
\r
3720 $r = q("UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
\r
3721 dbesc(datetime_convert()),
\r
3722 intval(local_user())
\r
3725 // Update global directory in background
\r
3726 //$user = api_get_user(get_app());
\r
3727 $url = App::get_baseurl() . '/profile/' . get_app()->user['nickname'];
\r
3728 if ($url && strlen(get_config('system', 'directory'))) {
\r
3729 proc_run(PRIORITY_LOW, "include/directory.php", $url);
\r
3732 require_once 'include/profile_update.php';
\r
3735 // output for client
\r
3737 return api_account_verify_credentials($type);
\r
3739 // SaveMediaToDatabase failed for some reason
\r
3740 throw new InternalServerErrorException("image upload failed");
\r
3744 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
\r
3745 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
\r
3746 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
\r
3747 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
\r
3748 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
\r
3749 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
\r
3750 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
\r
3751 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
\r
3752 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
\r
3755 function check_acl_input($acl_string) {
\r
3756 if ($acl_string == null || $acl_string == " ") {
\r
3759 $contact_not_found = false;
\r
3761 // split <x><y><z> into array of cid's
\r
3762 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
\r
3764 // check for each cid if it is available on server
\r
3765 $cid_array = $array[0];
\r
3766 foreach ($cid_array as $cid) {
\r
3767 $cid = str_replace("<", "", $cid);
\r
3768 $cid = str_replace(">", "", $cid);
\r
3769 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
\r
3771 intval(api_user()));
\r
3772 $contact_not_found |= !dbm::is_result($contact);
\r
3774 return $contact_not_found;
\r
3777 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) {
\r
3784 if (is_array($media)) {
\r
3785 if (is_array($media['tmp_name'])) {
\r
3786 $src = $media['tmp_name'][0];
\r
3788 $src = $media['tmp_name'];
\r
3790 if (is_array($media['name'])) {
\r
3791 $filename = basename($media['name'][0]);
\r
3793 $filename = basename($media['name']);
\r
3795 if (is_array($media['size'])) {
\r
3796 $filesize = intval($media['size'][0]);
\r
3798 $filesize = intval($media['size']);
\r
3800 if (is_array($media['type'])) {
\r
3801 $filetype = $media['type'][0];
\r
3803 $filetype = $media['type'];
\r
3807 if ($filetype == "") {
\r
3808 $filetype=guess_image_type($filename);
\r
3810 $imagedata = getimagesize($src);
\r
3812 $filetype = $imagedata['mime'];
\r
3814 logger("File upload src: " . $src . " - filename: " . $filename .
\r
3815 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG);
\r
3817 // check if there was a php upload error
\r
3818 if ($filesize == 0 && $media['error'] == 1) {
\r
3819 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
\r
3821 // check against max upload size within Friendica instance
\r
3822 $maximagesize = get_config('system', 'maximagesize');
\r
3823 if (($maximagesize) && ($filesize > $maximagesize)) {
\r
3824 $formattedBytes = formatBytes($maximagesize);
\r
3825 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
\r
3828 // create Photo instance with the data of the image
\r
3829 $imagedata = @file_get_contents($src);
\r
3830 $ph = new Photo($imagedata, $filetype);
\r
3831 if (! $ph->is_valid()) {
\r
3832 throw new InternalServerErrorException("unable to process image data");
\r
3835 // check orientation of image
\r
3836 $ph->orient($src);
\r
3839 // check max length of images on server
\r
3840 $max_length = get_config('system', 'max_image_length');
\r
3841 if (! $max_length) {
\r
3842 $max_length = MAX_IMAGE_LENGTH;
\r
3844 if ($max_length > 0) {
\r
3845 $ph->scaleImage($max_length);
\r
3846 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
\r
3848 $width = $ph->getWidth();
\r
3849 $height = $ph->getHeight();
\r
3851 // create a new resource-id if not already provided
\r
3852 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
\r
3854 if ($mediatype == "photo") {
\r
3855 // upload normal image (scales 0, 1, 2)
\r
3856 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
\r
3858 $r =$ph->store(local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
\r
3860 logger("photo upload: image upload with scale 0 (original size) failed");
\r
3862 if($width > 640 || $height > 640) {
\r
3863 $ph->scaleImage(640);
\r
3864 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
\r
3866 logger("photo upload: image upload with scale 1 (640x640) failed");
\r
3870 if ($width > 320 || $height > 320) {
\r
3871 $ph->scaleImage(320);
\r
3872 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
\r
3874 logger("photo upload: image upload with scale 2 (320x320) failed");
\r
3877 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
\r
3878 } elseif ($mediatype == "profileimage") {
\r
3879 // upload profile image (scales 4, 5, 6)
\r
3880 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
\r
3882 if ($width > 175 || $height > 175) {
\r
3883 $ph->scaleImage(175);
\r
3884 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
\r
3886 logger("photo upload: profile image upload with scale 4 (175x175) failed");
\r
3890 if ($width > 80 || $height > 80) {
\r
3891 $ph->scaleImage(80);
\r
3892 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
\r
3894 logger("photo upload: profile image upload with scale 5 (80x80) failed");
\r
3898 if ($width > 48 || $height > 48) {
\r
3899 $ph->scaleImage(48);
\r
3900 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
\r
3902 logger("photo upload: profile image upload with scale 6 (48x48) failed");
\r
3905 $ph->__destruct();
\r
3906 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
\r
3910 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
\r
3911 if ($photo_id == null && $mediatype == "photo") {
\r
3912 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
\r
3914 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
\r
3915 return prepare_photo_data($type, false, $hash);
\r
3917 throw new InternalServerErrorException("image upload failed");
\r
3921 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false) {
\r
3922 // get data about the api authenticated user
\r
3923 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
\r
3924 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
\r
3927 $arr['guid'] = get_guid(32);
\r
3928 $arr['uid'] = intval(api_user());
\r
3929 $arr['uri'] = $uri;
\r
3930 $arr['parent-uri'] = $uri;
\r
3931 $arr['type'] = 'photo';
\r
3933 $arr['resource-id'] = $hash;
\r
3934 $arr['contact-id'] = $owner_record[0]['id'];
\r
3935 $arr['owner-name'] = $owner_record[0]['name'];
\r
3936 $arr['owner-link'] = $owner_record[0]['url'];
\r
3937 $arr['owner-avatar'] = $owner_record[0]['thumb'];
\r
3938 $arr['author-name'] = $owner_record[0]['name'];
\r
3939 $arr['author-link'] = $owner_record[0]['url'];
\r
3940 $arr['author-avatar'] = $owner_record[0]['thumb'];
\r
3941 $arr['title'] = "";
\r
3942 $arr['allow_cid'] = $allow_cid;
\r
3943 $arr['allow_gid'] = $allow_gid;
\r
3944 $arr['deny_cid'] = $deny_cid;
\r
3945 $arr['deny_gid'] = $deny_gid;
\r
3946 $arr['last-child'] = 1;
\r
3947 $arr['visible'] = $visibility;
\r
3948 $arr['origin'] = 1;
\r
3950 $typetoext = array(
\r
3951 'image/jpeg' => 'jpg',
\r
3952 'image/png' => 'png',
\r
3953 'image/gif' => 'gif'
\r
3956 // adds link to the thumbnail scale photo
\r
3957 $arr['body'] = '[url=' . App::get_baseurl() . '/photos/' . $owner_record[0]['name'] . '/image/' . $hash . ']'
\r
3958 . '[img]' . App::get_baseurl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
\r
3961 // do the magic for storing the item in the database and trigger the federation to other contacts
\r
3965 function prepare_photo_data($type, $scale, $photo_id) {
\r
3966 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d", intval($scale)));
\r
3967 $data_sql = ($scale === false ? "" : "data, ");
\r
3969 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
\r
3970 // clients needs to convert this in their way for further processing
\r
3971 $r = q("SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
\r
3972 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
\r
3973 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
\r
3974 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
\r
3976 intval(local_user()),
\r
3981 $typetoext = array(
\r
3982 'image/jpeg' => 'jpg',
\r
3983 'image/png' => 'png',
\r
3984 'image/gif' => 'gif'
\r
3987 // prepare output data for photo
\r
3988 if (dbm::is_result($r)) {
\r
3989 $data = array('photo' => $r[0]);
\r
3990 $data['photo']['id'] = $data['photo']['resource-id'];
\r
3991 if ($scale !== false) {
\r
3992 $data['photo']['data'] = base64_encode($data['photo']['data']);
\r
3994 unset($data['photo']['datasize']); //needed only with scale param
\r
3996 if ($type == "xml") {
\r
3997 $data['photo']['links'] = array();
\r
3998 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
\r
3999 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
\r
4001 "href" => App::get_baseurl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
\r
4004 $data['photo']['link'] = array();
\r
4005 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
\r
4007 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
\r
4008 $data['photo']['link'][$i] = App::get_baseurl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
\r
4012 unset($data['photo']['resource-id']);
\r
4013 unset($data['photo']['minscale']);
\r
4014 unset($data['photo']['maxscale']);
\r
4017 throw new NotFoundException();
\r
4020 // retrieve item element for getting activities (like, dislike etc.) related to photo
\r
4021 $item = q("SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
\r
4022 intval(local_user()),
\r
4025 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
\r
4027 // retrieve comments on photo
\r
4028 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
\r
4029 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
\r
4030 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
\r
4031 `contact`.`id` AS `cid`
\r
4033 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
\r
4034 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
\r
4035 WHERE `item`.`parent` = %d AND `item`.`visible`
\r
4036 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
\r
4037 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
\r
4038 intval($item[0]['parent']),
\r
4039 intval(api_user()),
\r
4040 dbesc(ACTIVITY_POST)
\r
4043 // prepare output of comments
\r
4044 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
\r
4045 $comments = array();
\r
4046 if ($type == "xml") {
\r
4048 foreach ($commentData as $comment) {
\r
4049 $comments[$k++ . ":comment"] = $comment;
\r
4052 foreach ($commentData as $comment) {
\r
4053 $comments[] = $comment;
\r
4056 $data['photo']['friendica_comments'] = $comments;
\r
4058 // include info if rights on photo and rights on item are mismatching
\r
4059 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
\r
4060 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
\r
4061 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
\r
4062 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
\r
4063 $data['photo']['rights_mismatch'] = $rights_mismatch;
\r
4070 * similar as /mod/redir.php
\r
4071 * redirect to 'url' after dfrn auth
\r
4073 * why this when there is mod/redir.php already?
\r
4074 * This use api_user() and api_login()
\r
4077 * c_url: url of remote contact to auth to
\r
4078 * url: string, url to redirect after auth
\r
4080 function api_friendica_remoteauth() {
\r
4081 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
\r
4082 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
\r
4084 if ($url === '' || $c_url === '') {
\r
4085 throw new BadRequestException("Wrong parameters.");
\r
4088 $c_url = normalise_link($c_url);
\r
4090 // traditional DFRN
\r
4092 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
\r
4094 intval(api_user())
\r
4097 if ((! dbm::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
\r
4098 throw new BadRequestException("Unknown contact");
\r
4101 $cid = $r[0]['id'];
\r
4103 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
\r
4105 if ($r[0]['duplex'] && $r[0]['issued-id']) {
\r
4106 $orig_id = $r[0]['issued-id'];
\r
4107 $dfrn_id = '1:' . $orig_id;
\r
4109 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
\r
4110 $orig_id = $r[0]['dfrn-id'];
\r
4111 $dfrn_id = '0:' . $orig_id;
\r
4114 $sec = random_string();
\r
4116 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
\r
4117 VALUES( %d, %s, '%s', '%s', %d )",
\r
4118 intval(api_user()),
\r
4122 intval(time() + 45)
\r
4125 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
\r
4126 $dest = (($url) ? '&destination_url=' . $url : '');
\r
4127 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
\r
4128 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
\r
4129 . '&type=profile&sec=' . $sec . $dest . $quiet );
\r
4131 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
\r
4134 * @brief Return the item shared, if the item contains only the [share] tag
\r
4136 * @param array $item Sharer item
\r
4137 * @return array Shared item or false if not a reshare
\r
4139 function api_share_as_retweet(&$item) {
\r
4140 $body = trim($item["body"]);
\r
4142 if (Diaspora::is_reshare($body, false)===false) {
\r
4146 /// @TODO "$1" should maybe mean '$1' ?
\r
4147 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
\r
4149 * Skip if there is no shared message in there
\r
4150 * we already checked this in diaspora::is_reshare()
\r
4151 * but better one more than one less...
\r
4153 if ($body == $attributes) {
\r
4158 // build the fake reshared item
\r
4159 $reshared_item = $item;
\r
4162 preg_match("/author='(.*?)'/ism", $attributes, $matches);
\r
4163 if ($matches[1] != "") {
\r
4164 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
\r
4167 preg_match('/author="(.*?)"/ism', $attributes, $matches);
\r
4168 if ($matches[1] != "") {
\r
4169 $author = $matches[1];
\r
4173 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
\r
4174 if ($matches[1] != "") {
\r
4175 $profile = $matches[1];
\r
4178 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
\r
4179 if ($matches[1] != "") {
\r
4180 $profile = $matches[1];
\r
4184 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
\r
4185 if ($matches[1] != "") {
\r
4186 $avatar = $matches[1];
\r
4189 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
\r
4190 if ($matches[1] != "") {
\r
4191 $avatar = $matches[1];
\r
4195 preg_match("/link='(.*?)'/ism", $attributes, $matches);
\r
4196 if ($matches[1] != "") {
\r
4197 $link = $matches[1];
\r
4200 preg_match('/link="(.*?)"/ism', $attributes, $matches);
\r
4201 if ($matches[1] != "") {
\r
4202 $link = $matches[1];
\r
4206 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
\r
4207 if ($matches[1] != "")
\r
4208 $posted = $matches[1];
\r
4210 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
\r
4211 if ($matches[1] != "") {
\r
4212 $posted = $matches[1];
\r
4215 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
\r
4217 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
\r
4221 $reshared_item["body"] = $shared_body;
\r
4222 $reshared_item["author-name"] = $author;
\r
4223 $reshared_item["author-link"] = $profile;
\r
4224 $reshared_item["author-avatar"] = $avatar;
\r
4225 $reshared_item["plink"] = $link;
\r
4226 $reshared_item["created"] = $posted;
\r
4227 $reshared_item["edited"] = $posted;
\r
4229 return $reshared_item;
\r
4233 function api_get_nick($profile) {
\r
4235 - remove trailing junk from profile url
\r
4236 - pump.io check has to check the website
\r
4241 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
\r
4242 dbesc(normalise_link($profile)));
\r
4244 if (dbm::is_result($r)) {
\r
4245 $nick = $r[0]["nick"];
\r
4248 if (!$nick == "") {
\r
4249 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
\r
4250 dbesc(normalise_link($profile)));
\r
4252 if (dbm::is_result($r)) {
\r
4253 $nick = $r[0]["nick"];
\r
4257 if (!$nick == "") {
\r
4258 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
\r
4259 if ($friendica != $profile) {
\r
4260 $nick = $friendica;
\r
4264 if (!$nick == "") {
\r
4265 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
\r
4266 if ($diaspora != $profile) {
\r
4267 $nick = $diaspora;
\r
4271 if (!$nick == "") {
\r
4272 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
\r
4273 if ($twitter != $profile) {
\r
4279 if (!$nick == "") {
\r
4280 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
\r
4281 if ($StatusnetHost != $profile) {
\r
4282 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
\r
4283 if ($StatusnetUser != $profile) {
\r
4284 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
\r
4285 $user = json_decode($UserData);
\r
4287 $nick = $user->screen_name;
\r
4293 // To-Do: look at the page if its really a pumpio site
\r
4294 //if (!$nick == "") {
\r
4295 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
\r
4296 // if ($pumpio != $profile)
\r
4297 // $nick = $pumpio;
\r
4298 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
\r
4302 if ($nick != "") {
\r
4309 function api_in_reply_to($item) {
\r
4310 $in_reply_to = array();
\r
4312 $in_reply_to['status_id'] = NULL;
\r
4313 $in_reply_to['user_id'] = NULL;
\r
4314 $in_reply_to['status_id_str'] = NULL;
\r
4315 $in_reply_to['user_id_str'] = NULL;
\r
4316 $in_reply_to['screen_name'] = NULL;
\r
4318 if (($item['thr-parent'] != $item['uri']) AND (intval($item['parent']) != intval($item['id']))) {
\r
4319 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
\r
4320 intval($item['uid']),
\r
4321 dbesc($item['thr-parent']));
\r
4323 if (dbm::is_result($r)) {
\r
4324 $in_reply_to['status_id'] = intval($r[0]['id']);
\r
4326 $in_reply_to['status_id'] = intval($item['parent']);
\r
4329 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
\r
4331 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
\r
4332 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
\r
4333 WHERE `item`.`id` = %d LIMIT 1",
\r
4334 intval($in_reply_to['status_id'])
\r
4337 if (dbm::is_result($r)) {
\r
4338 if ($r[0]['nick'] == "") {
\r
4339 $r[0]['nick'] = api_get_nick($r[0]["url"]);
\r
4342 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
\r
4343 $in_reply_to['user_id'] = intval($r[0]['id']);
\r
4344 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
\r
4347 // There seems to be situation, where both fields are identical:
\r
4348 // https://github.com/friendica/friendica/issues/1010
\r
4349 // This is a bugfix for that.
\r
4350 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
\r
4351 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
\r
4352 $in_reply_to['status_id'] = NULL;
\r
4353 $in_reply_to['user_id'] = NULL;
\r
4354 $in_reply_to['status_id_str'] = NULL;
\r
4355 $in_reply_to['user_id_str'] = NULL;
\r
4356 $in_reply_to['screen_name'] = NULL;
\r
4360 return $in_reply_to;
\r
4363 function api_clean_plain_items($Text) {
\r
4364 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
\r
4366 $Text = bb_CleanPictureLinks($Text);
\r
4367 $URLSearchString = "^\[\]";
\r
4369 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
\r
4371 if ($include_entities == "true") {
\r
4372 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
\r
4375 // Simplify "attachment" element
\r
4376 $Text = api_clean_attachments($Text);
\r
4382 * @brief Removes most sharing information for API text export
\r
4384 * @param string $body The original body
\r
4386 * @return string Cleaned body
\r
4388 function api_clean_attachments($body) {
\r
4389 $data = get_attachment_data($body);
\r
4396 if (isset($data["text"]))
\r
4397 $body = $data["text"];
\r
4399 if (($body == "") AND (isset($data["title"])))
\r
4400 $body = $data["title"];
\r
4402 if (isset($data["url"]))
\r
4403 $body .= "\n".$data["url"];
\r
4405 $body .= $data["after"];
\r
4410 function api_best_nickname(&$contacts) {
\r
4411 $best_contact = array();
\r
4413 if (count($contact) == 0)
\r
4416 foreach ($contacts AS $contact)
\r
4417 if ($contact["network"] == "") {
\r
4418 $contact["network"] = "dfrn";
\r
4419 $best_contact = array($contact);
\r
4422 if (sizeof($best_contact) == 0)
\r
4423 foreach ($contacts AS $contact)
\r
4424 if ($contact["network"] == "dfrn")
\r
4425 $best_contact = array($contact);
\r
4427 if (sizeof($best_contact) == 0)
\r
4428 foreach ($contacts AS $contact)
\r
4429 if ($contact["network"] == "dspr")
\r
4430 $best_contact = array($contact);
\r
4432 if (sizeof($best_contact) == 0)
\r
4433 foreach ($contacts AS $contact)
\r
4434 if ($contact["network"] == "stat")
\r
4435 $best_contact = array($contact);
\r
4437 if (sizeof($best_contact) == 0)
\r
4438 foreach ($contacts AS $contact)
\r
4439 if ($contact["network"] == "pump")
\r
4440 $best_contact = array($contact);
\r
4442 if (sizeof($best_contact) == 0)
\r
4443 foreach ($contacts AS $contact)
\r
4444 if ($contact["network"] == "twit")
\r
4445 $best_contact = array($contact);
\r
4447 if (sizeof($best_contact) == 1)
\r
4448 $contacts = $best_contact;
\r
4450 $contacts = array($contacts[0]);
\r
4453 // return all or a specified group of the user with the containing contacts
\r
4454 function api_friendica_group_show($type) {
\r
4458 if (api_user() === false) throw new ForbiddenException();
\r
4461 $user_info = api_get_user($a);
\r
4462 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
\r
4463 $uid = $user_info['uid'];
\r
4465 // get data of the specified group id or all groups if not specified
\r
4467 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
\r
4470 // error message if specified gid is not in database
\r
4471 if (!dbm::is_result($r))
\r
4472 throw new BadRequestException("gid not available");
\r
4475 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
\r
4478 // loop through all groups and retrieve all members for adding data in the user array
\r
4479 foreach ($r as $rr) {
\r
4480 $members = group_get_members($rr['id']);
\r
4483 if ($type == "xml") {
\r
4484 $user_element = "users";
\r
4486 foreach ($members as $member) {
\r
4487 $user = api_get_user($a, $member['nurl']);
\r
4488 $users[$k++.":user"] = $user;
\r
4491 $user_element = "user";
\r
4492 foreach ($members as $member) {
\r
4493 $user = api_get_user($a, $member['nurl']);
\r
4497 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
\r
4499 return api_format_data("groups", $type, array('group' => $grps));
\r
4501 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
\r
4504 // delete the specified group of the user
\r
4505 function api_friendica_group_delete($type) {
\r
4509 if (api_user() === false) throw new ForbiddenException();
\r
4512 $user_info = api_get_user($a);
\r
4513 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
\r
4514 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
\r
4515 $uid = $user_info['uid'];
\r
4517 // error if no gid specified
\r
4518 if ($gid == 0 || $name == "")
\r
4519 throw new BadRequestException('gid or name not specified');
\r
4521 // get data of the specified group id
\r
4522 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
\r
4525 // error message if specified gid is not in database
\r
4526 if (!dbm::is_result($r))
\r
4527 throw new BadRequestException('gid not available');
\r
4529 // get data of the specified group id and group name
\r
4530 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
\r
4534 // error message if specified gid is not in database
\r
4535 if (!dbm::is_result($rname))
\r
4536 throw new BadRequestException('wrong group name');
\r
4539 $ret = group_rmv($uid, $name);
\r
4542 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
\r
4543 return api_format_data("group_delete", $type, array('result' => $success));
\r
4546 throw new BadRequestException('other API error');
\r
4548 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
\r
4551 // create the specified group with the posted array of contacts
\r
4552 function api_friendica_group_create($type) {
\r
4556 if (api_user() === false) throw new ForbiddenException();
\r
4559 $user_info = api_get_user($a);
\r
4560 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
\r
4561 $uid = $user_info['uid'];
\r
4562 $json = json_decode($_POST['json'], true);
\r
4563 $users = $json['user'];
\r
4565 // error if no name specified
\r
4567 throw new BadRequestException('group name not specified');
\r
4569 // get data of the specified group name
\r
4570 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
\r
4573 // error message if specified group name already exists
\r
4574 if (dbm::is_result($rname))
\r
4575 throw new BadRequestException('group name already exists');
\r
4577 // check if specified group name is a deleted group
\r
4578 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
\r
4581 // error message if specified group name already exists
\r
4582 if (dbm::is_result($rname))
\r
4583 $reactivate_group = true;
\r
4586 $ret = group_add($uid, $name);
\r
4588 $gid = group_byname($uid, $name);
\r
4590 throw new BadRequestException('other API error');
\r
4593 $erroraddinguser = false;
\r
4594 $errorusers = array();
\r
4595 foreach ($users as $user) {
\r
4596 $cid = $user['cid'];
\r
4597 // check if user really exists as contact
\r
4598 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
\r
4601 if (count($contact))
\r
4602 $result = group_add_member($uid, $name, $cid, $gid);
\r
4604 $erroraddinguser = true;
\r
4605 $errorusers[] = $cid;
\r
4609 // return success message incl. missing users in array
\r
4610 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
\r
4611 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
\r
4612 return api_format_data("group_create", $type, array('result' => $success));
\r
4614 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
\r
4617 // update the specified group with the posted array of contacts
\r
4618 function api_friendica_group_update($type) {
\r
4622 if (api_user() === false) throw new ForbiddenException();
\r
4625 $user_info = api_get_user($a);
\r
4626 $uid = $user_info['uid'];
\r
4627 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
\r
4628 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
\r
4629 $json = json_decode($_POST['json'], true);
\r
4630 $users = $json['user'];
\r
4632 // error if no name specified
\r
4634 throw new BadRequestException('group name not specified');
\r
4636 // error if no gid specified
\r
4638 throw new BadRequestException('gid not specified');
\r
4641 $members = group_get_members($gid);
\r
4642 foreach ($members as $member) {
\r
4643 $cid = $member['id'];
\r
4644 foreach ($users as $user) {
\r
4645 $found = ($user['cid'] == $cid ? true : false);
\r
4648 $ret = group_rmv_member($uid, $name, $cid);
\r
4653 $erroraddinguser = false;
\r
4654 $errorusers = array();
\r
4655 foreach ($users as $user) {
\r
4656 $cid = $user['cid'];
\r
4657 // check if user really exists as contact
\r
4658 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
\r
4661 if (count($contact))
\r
4662 $result = group_add_member($uid, $name, $cid, $gid);
\r
4664 $erroraddinguser = true;
\r
4665 $errorusers[] = $cid;
\r
4669 // return success message incl. missing users in array
\r
4670 $status = ($erroraddinguser ? "missing user" : "ok");
\r
4671 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
\r
4672 return api_format_data("group_update", $type, array('result' => $success));
\r
4675 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
\r
4677 function api_friendica_activity($type) {
\r
4681 if (api_user() === false) throw new ForbiddenException();
\r
4682 $verb = strtolower($a->argv[3]);
\r
4683 $verb = preg_replace("|\..*$|", "", $verb);
\r
4685 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
\r
4687 $res = do_like($id, $verb);
\r
4690 if ($type == "xml")
\r
4694 return api_format_data('ok', $type, array('ok' => $ok));
\r
4696 throw new BadRequestException('Error adding activity');
\r
4701 /// @TODO move to top of file or somwhere better
\r
4702 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
\r
4703 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
\r
4704 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
\r
4705 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
\r
4706 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
\r
4707 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
\r
4708 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
\r
4709 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
\r
4710 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
\r
4711 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
\r
4714 * @brief Returns notifications
\r
4716 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
4719 function api_friendica_notification($type) {
\r
4723 if (api_user() === false) throw new ForbiddenException();
\r
4724 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
\r
4725 $nm = new NotificationsManager();
\r
4727 $notes = $nm->getAll(array(), "+seen -date", 50);
\r
4729 if ($type == "xml") {
\r
4730 $xmlnotes = array();
\r
4731 foreach ($notes AS $note)
\r
4732 $xmlnotes[] = array("@attributes" => $note);
\r
4734 $notes = $xmlnotes;
\r
4737 return api_format_data("notes", $type, array('note' => $notes));
\r
4741 * @brief Set notification as seen and returns associated item (if possible)
\r
4743 * POST request with 'id' param as notification id
\r
4745 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
4748 function api_friendica_notification_seen($type) {
\r
4752 if (api_user() === false) throw new ForbiddenException();
\r
4753 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
\r
4755 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
\r
4757 $nm = new NotificationsManager();
\r
4758 $note = $nm->getByID($id);
\r
4759 if (is_null($note)) throw new BadRequestException("Invalid argument");
\r
4761 $nm->setSeen($note);
\r
4762 if ($note['otype']=='item') {
\r
4763 // would be really better with an ItemsManager and $im->getByID() :-P
\r
4764 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
\r
4765 intval($note['iid']),
\r
4766 intval(local_user())
\r
4769 // we found the item, return it to the user
\r
4770 $user_info = api_get_user($a);
\r
4771 $ret = api_format_items($r,$user_info, false, $type);
\r
4772 $data = array('status' => $ret);
\r
4773 return api_format_data("status", $type, $data);
\r
4775 // the item can't be found, but we set the note as seen, so we count this as a success
\r
4777 return api_format_data('result', $type, array('result' => "success"));
\r
4780 /// @TODO move to top of file or somwhere better
\r
4781 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
\r
4782 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
\r
4785 * @brief update a direct_message to seen state
\r
4787 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
4788 * @return string (success result=ok, error result=error with error message)
\r
4790 function api_friendica_direct_messages_setseen($type) {
\r
4792 if (api_user() === false) {
\r
4793 throw new ForbiddenException();
\r
4797 $user_info = api_get_user($a);
\r
4798 $uid = $user_info['uid'];
\r
4799 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
\r
4801 // return error if id is zero
\r
4803 $answer = array('result' => 'error', 'message' => 'message id not specified');
\r
4804 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
\r
4807 // get data of the specified message id
\r
4808 $r = q("SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
\r
4812 // error message if specified id is not in database
\r
4813 if (!dbm::is_result($r)) {
\r
4814 $answer = array('result' => 'error', 'message' => 'message id not in database');
\r
4815 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
\r
4818 // update seen indicator
\r
4819 $result = q("UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
\r
4825 $answer = array('result' => 'ok', 'message' => 'message set to seen');
\r
4826 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
\r
4828 $answer = array('result' => 'error', 'message' => 'unknown error');
\r
4829 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
\r
4833 /// @TODO move to top of file or somwhere better
\r
4834 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
\r
4837 * @brief search for direct_messages containing a searchstring through api
\r
4839 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
4840 * @return string (success: success=true if found and search_result contains found messages
\r
4841 * success=false if nothing was found, search_result='nothing found',
\r
4842 * error: result=error with error message)
\r
4844 function api_friendica_direct_messages_search($type) {
\r
4847 if (api_user() === false) {
\r
4848 throw new ForbiddenException();
\r
4852 $user_info = api_get_user($a);
\r
4853 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
\r
4854 $uid = $user_info['uid'];
\r
4856 // error if no searchstring specified
\r
4857 if ($searchstring == "") {
\r
4858 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
\r
4859 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
\r
4862 // get data for the specified searchstring
\r
4863 $r = q("SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND `body` LIKE '%s' ORDER BY `mail`.`id` DESC",
\r
4865 dbesc('%'.$searchstring.'%')
\r
4868 $profile_url = $user_info["url"];
\r
4870 // message if nothing was found
\r
4871 if (!dbm::is_result($r)) {
\r
4872 $success = array('success' => false, 'search_results' => 'problem with query');
\r
4873 } elseif (count($r) == 0) {
\r
4874 $success = array('success' => false, 'search_results' => 'nothing found');
\r
4877 foreach ($r as $item) {
\r
4878 if ($box == "inbox" || $item['from-url'] != $profile_url) {
\r
4879 $recipient = $user_info;
\r
4880 $sender = api_get_user($a,normalise_link($item['contact-url']));
\r
4881 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
\r
4882 $recipient = api_get_user($a,normalise_link($item['contact-url']));
\r
4883 $sender = $user_info;
\r
4886 $ret[] = api_format_messages($item, $recipient, $sender);
\r
4888 $success = array('success' => true, 'search_results' => $ret);
\r
4891 return api_format_data("direct_message_search", $type, array('$result' => $success));
\r
4894 /// @TODO move to top of file or somwhere better
\r
4895 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
\r
4898 * @brief return data of all the profiles a user has to the client
\r
4900 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
4903 function api_friendica_profile_show($type) {
\r
4906 if (api_user() === false) {
\r
4907 throw new ForbiddenException();
\r
4911 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
\r
4913 // retrieve general information about profiles for user
\r
4914 $multi_profiles = feature_enabled(api_user(),'multi_profiles');
\r
4915 $directory = get_config('system', 'directory');
\r
4917 // get data of the specified profile id or all profiles of the user if not specified
\r
4918 if ($profileid != 0) {
\r
4919 $r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
\r
4920 intval(api_user()),
\r
4921 intval($profileid));
\r
4923 // error message if specified gid is not in database
\r
4924 if (!dbm::is_result($r)) {
\r
4925 throw new BadRequestException("profile_id not available");
\r
4928 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
\r
4929 intval(api_user()));
\r
4931 // loop through all returned profiles and retrieve data and users
\r
4933 foreach ($r as $rr) {
\r
4934 $profile = api_format_items_profiles($rr, $type);
\r
4936 // select all users from contact table, loop and prepare standard return for user data
\r
4938 $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
\r
4939 intval(api_user()),
\r
4940 intval($rr['profile_id']));
\r
4942 foreach ($r as $rr) {
\r
4943 $user = api_get_user($a, $rr['nurl']);
\r
4944 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
\r
4946 $profile['users'] = $users;
\r
4948 // add prepared profile data to array for final return
\r
4949 if ($type == "xml") {
\r
4950 $profiles[$k++ . ":profile"] = $profile;
\r
4952 $profiles[] = $profile;
\r
4956 // return settings, authenticated user and profiles data
\r
4957 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
\r
4959 $result = array('multi_profiles' => $multi_profiles ? true : false,
\r
4960 'global_dir' => $directory,
\r
4961 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
\r
4962 'profiles' => $profiles);
\r
4963 return api_format_data("friendica_profiles", $type, array('$result' => $result));
\r
4965 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
\r
4968 @TODO Maybe open to implement?
\r
4970 [pagename] => api/1.1/statuses/lookup.json
\r
4971 [id] => 605138389168451584
\r
4972 [include_cards] => true
\r
4973 [cards_platform] => Android-12
\r
4974 [include_entities] => true
\r
4975 [include_my_retweet] => 1
\r
4976 [include_rts] => 1
\r
4977 [include_reply_count] => true
\r
4978 [include_descendent_reply_count] => true
\r
4982 Not implemented by now:
\r
4983 statuses/retweets_of_me
\r
4984 friendships/create
\r
4985 friendships/destroy
\r
4986 friendships/exists
\r
4988 account/update_location
\r
4989 account/update_profile_background_image
\r
4992 friendica/profile/update
\r
4993 friendica/profile/create
\r
4994 friendica/profile/delete
\r
4996 Not implemented in status.net:
\r
4997 statuses/retweeted_to_me
\r
4998 statuses/retweeted_by_me
\r
4999 direct_messages/destroy
\r
5000 account/end_session
\r
5001 account/update_delivery_device
\r
5002 notifications/follow
\r
5003 notifications/leave
\r