]> git.mxchange.org Git - friendica.git/blob - include/api.php
Merge pull request #4076 from AndyHee/20171216-README.md
[friendica.git] / include / api.php
1 <?php
2 /**
3  * @file include/api.php
4  * Friendica implementation of statusnet/twitter API
5  *
6  * @todo Automatically detect if incoming data is HTML or BBCode
7  */
8 use Friendica\App;
9 use Friendica\Content\Feature;
10 use Friendica\Core\System;
11 use Friendica\Core\Config;
12 use Friendica\Core\NotificationsManager;
13 use Friendica\Core\Worker;
14 use Friendica\Database\DBM;
15 use Friendica\Model\Contact;
16 use Friendica\Model\Group;
17 use Friendica\Model\Photo;
18 use Friendica\Model\User;
19 use Friendica\Network\FKOAuth1;
20 use Friendica\Network\HTTPException;
21 use Friendica\Network\HTTPException\BadRequestException;
22 use Friendica\Network\HTTPException\ForbiddenException;
23 use Friendica\Network\HTTPException\InternalServerErrorException;
24 use Friendica\Network\HTTPException\MethodNotAllowedException;
25 use Friendica\Network\HTTPException\NotFoundException;
26 use Friendica\Network\HTTPException\NotImplementedException;
27 use Friendica\Network\HTTPException\UnauthorizedException;
28 use Friendica\Network\HTTPException\TooManyRequestsException;
29 use Friendica\Object\Image;
30 use Friendica\Protocol\Diaspora;
31 use Friendica\Util\XML;
32
33 require_once 'include/bbcode.php';
34 require_once 'include/datetime.php';
35 require_once 'include/conversation.php';
36 require_once 'include/html2plain.php';
37 require_once 'mod/share.php';
38 require_once 'mod/item.php';
39 require_once 'include/security.php';
40 require_once 'include/contact_selectors.php';
41 require_once 'include/html2bbcode.php';
42 require_once 'mod/wall_upload.php';
43 require_once 'mod/proxy.php';
44 require_once 'include/message.php';
45 require_once 'include/like.php';
46 require_once 'include/plaintext.php';
47
48 define('API_METHOD_ANY', '*');
49 define('API_METHOD_GET', 'GET');
50 define('API_METHOD_POST', 'POST,PUT');
51 define('API_METHOD_DELETE', 'POST,DELETE');
52
53 $API = array();
54 $called_api = null;
55
56 /**
57  * @brief Auth API user
58  *
59  * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
60  * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
61  * into a page, and visitors will post something without noticing it).
62  */
63 function api_user()
64 {
65         if (x($_SESSION, 'allow_api')) {
66                 return local_user();
67         }
68
69         return false;
70 }
71
72 /**
73  * @brief Get source name from API client
74  *
75  * Clients can send 'source' parameter to be show in post metadata
76  * as "sent via <source>".
77  * Some clients doesn't send a source param, we support ones we know
78  * (only Twidere, atm)
79  *
80  * @return string
81  *              Client source name, default to "api" if unset/unknown
82  */
83 function api_source()
84 {
85         if (requestdata('source')) {
86                 return requestdata('source');
87         }
88
89         // Support for known clients that doesn't send a source name
90         if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
91                 return "Twidere";
92         }
93
94         logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
95
96         return "api";
97 }
98
99 /**
100  * @brief Format date for API
101  *
102  * @param string $str Source date, as UTC
103  * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
104  */
105 function api_date($str)
106 {
107         // Wed May 23 06:01:13 +0000 2007
108         return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y");
109 }
110
111 /**
112  * @brief Register API endpoint
113  *
114  * Register a function to be the endpont for defined API path.
115  *
116  * @param string $path   API URL path, relative to System::baseUrl()
117  * @param string $func   Function name to call on path request
118  * @param bool   $auth   API need logged user
119  * @param string $method HTTP method reqiured to call this endpoint.
120  *                       One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
121  *                       Default to API_METHOD_ANY
122  */
123 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
124 {
125         global $API;
126
127         $API[$path] = array(
128                 'func'   => $func,
129                 'auth'   => $auth,
130                 'method' => $method,
131         );
132
133         // Workaround for hotot
134         $path = str_replace("api/", "api/1.1/", $path);
135
136         $API[$path] = array(
137                 'func'   => $func,
138                 'auth'   => $auth,
139                 'method' => $method,
140         );
141 }
142
143 /**
144  * @brief Login API user
145  *
146  * Log in user via OAuth1 or Simple HTTP Auth.
147  * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
148  *
149  * @param object $a App
150  * @hook 'authenticate'
151  *              array $addon_auth
152  *                      'username' => username from login form
153  *                      'password' => password from login form
154  *                      'authenticated' => return status,
155  *                      'user_record' => return authenticated user record
156  * @hook 'logged_in'
157  *              array $user     logged user record
158  */
159 function api_login(App $a)
160 {
161         $oauth1 = new FKOAuth1();
162         // login with oauth
163         try {
164                 list($consumer, $token) = $oauth1->verify_request(OAuthRequest::from_request());
165                 if (!is_null($token)) {
166                         $oauth1->loginUser($token->uid);
167                         call_hooks('logged_in', $a->user);
168                         return;
169                 }
170                 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
171                 var_dump($consumer, $token);
172                 die();
173         } catch (Exception $e) {
174                 logger($e);
175         }
176
177         // workaround for HTTP-auth in CGI mode
178         if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
179                 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
180                 if (strlen($userpass)) {
181                         list($name, $password) = explode(':', $userpass);
182                         $_SERVER['PHP_AUTH_USER'] = $name;
183                         $_SERVER['PHP_AUTH_PW'] = $password;
184                 }
185         }
186
187         if (!x($_SERVER, 'PHP_AUTH_USER')) {
188                 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
189                 header('WWW-Authenticate: Basic realm="Friendica"');
190                 throw new UnauthorizedException("This API requires login");
191         }
192
193         $user = $_SERVER['PHP_AUTH_USER'];
194         $password = $_SERVER['PHP_AUTH_PW'];
195
196         // allow "user@server" login (but ignore 'server' part)
197         $at = strstr($user, "@", true);
198         if ($at) {
199                 $user = $at;
200         }
201
202         // next code from mod/auth.php. needs better solution
203         $record = null;
204
205         $addon_auth = array(
206                 'username' => trim($user),
207                 'password' => trim($password),
208                 'authenticated' => 0,
209                 'user_record' => null,
210         );
211
212         /*
213                 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
214                 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
215                 * and later plugins should not interfere with an earlier one that succeeded.
216                 */
217         call_hooks('authenticate', $addon_auth);
218
219         if (($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
220                 $record = $addon_auth['user_record'];
221         } else {
222                 $user_id = User::authenticate(trim($user), trim($password));
223                 if ($user_id) {
224                         $record = dba::select('user', [], ['uid' => $user_id], ['limit' => 1]);
225                 }
226         }
227
228         if ((! $record) || (! count($record))) {
229                 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
230                 header('WWW-Authenticate: Basic realm="Friendica"');
231                 //header('HTTP/1.0 401 Unauthorized');
232                 //die('This api requires login');
233                 throw new UnauthorizedException("This API requires login");
234         }
235
236         authenticate_success($record);
237
238         $_SESSION["allow_api"] = true;
239
240         call_hooks('logged_in', $a->user);
241 }
242
243 /**
244  * @brief Check HTTP method of called API
245  *
246  * API endpoints can define which HTTP method to accept when called.
247  * This function check the current HTTP method agains endpoint
248  * registered method.
249  *
250  * @param string $method Required methods, uppercase, separated by comma
251  * @return bool
252  */
253 function api_check_method($method)
254 {
255         if ($method == "*") {
256                 return true;
257         }
258         return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
259 }
260
261 /**
262  * @brief Main API entry point
263  *
264  * Authenticate user, call registered API function, set HTTP headers
265  *
266  * @param object $a App
267  * @return string API call result
268  */
269 function api_call(App $a)
270 {
271         global $API, $called_api;
272
273         $type = "json";
274         if (strpos($a->query_string, ".xml") > 0) {
275                 $type = "xml";
276         }
277         if (strpos($a->query_string, ".json") > 0) {
278                 $type = "json";
279         }
280         if (strpos($a->query_string, ".rss") > 0) {
281                 $type = "rss";
282         }
283         if (strpos($a->query_string, ".atom") > 0) {
284                 $type = "atom";
285         }
286
287         try {
288                 foreach ($API as $p => $info) {
289                         if (strpos($a->query_string, $p) === 0) {
290                                 if (!api_check_method($info['method'])) {
291                                         throw new MethodNotAllowedException();
292                                 }
293
294                                 $called_api = explode("/", $p);
295                                 //unset($_SERVER['PHP_AUTH_USER']);
296
297                                 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
298                                 if ($info['auth'] === true && api_user() === false) {
299                                         api_login($a);
300                                 }
301
302                                 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
303                                 logger('API parameters: ' . print_r($_REQUEST, true));
304
305                                 $stamp =  microtime(true);
306                                 $r = call_user_func($info['func'], $type);
307                                 $duration = (float) (microtime(true) - $stamp);
308                                 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
309
310                                 if (Config::get("system", "profiler")) {
311                                         $duration = microtime(true)-$a->performance["start"];
312
313                                         /// @TODO round() really everywhere?
314                                         logger(
315                                                 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
316                                                         "Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
317                                                         round($a->performance["database"] - $a->performance["database_write"], 3),
318                                                         round($a->performance["database_write"], 3),
319                                                         round($a->performance["network"], 2),
320                                                         round($a->performance["file"], 2),
321                                                         round($duration - ($a->performance["database"] + $a->performance["network"]     + $a->performance["file"]), 2),
322                                                         round($duration, 2)
323                                                 ),
324                                                 LOGGER_DEBUG
325                                         );
326
327                                         if (Config::get("rendertime", "callstack")) {
328                                                 $o = "Database Read:\n";
329                                                 foreach ($a->callstack["database"] as $func => $time) {
330                                                         $time = round($time, 3);
331                                                         if ($time > 0) {
332                                                                 $o .= $func . ": " . $time . "\n";
333                                                         }
334                                                 }
335                                                 $o .= "\nDatabase Write:\n";
336                                                 foreach ($a->callstack["database_write"] as $func => $time) {
337                                                         $time = round($time, 3);
338                                                         if ($time > 0) {
339                                                                 $o .= $func . ": " . $time . "\n";
340                                                         }
341                                                 }
342
343                                                 $o .= "\nNetwork:\n";
344                                                 foreach ($a->callstack["network"] as $func => $time) {
345                                                         $time = round($time, 3);
346                                                         if ($time > 0) {
347                                                                 $o .= $func . ": " . $time . "\n";
348                                                         }
349                                                 }
350                                                 logger($o, LOGGER_DEBUG);
351                                         }
352                                 }
353
354                                 if (false === $r) {
355                                         /*
356                                                 * api function returned false withour throw an
357                                                 * exception. This should not happend, throw a 500
358                                                 */
359                                         throw new InternalServerErrorException();
360                                 }
361
362                                 switch ($type) {
363                                         case "xml":
364                                                 header("Content-Type: text/xml");
365                                                 return $r;
366                                                 break;
367                                         case "json":
368                                                 header("Content-Type: application/json");
369                                                 foreach ($r as $rr)
370                                                         $json = json_encode($rr);
371                                                         if (x($_GET, 'callback')) {
372                                                                 $json = $_GET['callback'] . "(" . $json . ")";
373                                                         }
374                                                         return $json;
375                                                 break;
376                                         case "rss":
377                                                 header("Content-Type: application/rss+xml");
378                                                 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
379                                                 break;
380                                         case "atom":
381                                                 header("Content-Type: application/atom+xml");
382                                                 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
383                                                 break;
384                                 }
385                         }
386                 }
387
388                 logger('API call not implemented: ' . $a->query_string);
389                 throw new NotImplementedException();
390         } catch (HTTPException $e) {
391                 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
392                 return api_error($type, $e);
393         }
394 }
395
396 /**
397  * @brief Format API error string
398  *
399  * @param string $type Return type (xml, json, rss, as)
400  * @param object $e    HTTPException Error object
401  * @return strin error message formatted as $type
402  */
403 function api_error($type, $e)
404 {
405         $a = get_app();
406
407         $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
408         /// @TODO:  https://dev.twitter.com/overview/api/response-codes
409
410         $error = array("error" => $error,
411                         "code" => $e->httpcode . " " . $e->httpdesc,
412                         "request" => $a->query_string);
413
414         $ret = api_format_data('status', $type, array('status' => $error));
415
416         switch ($type) {
417                 case "xml":
418                         header("Content-Type: text/xml");
419                         return $ret;
420                         break;
421                 case "json":
422                         header("Content-Type: application/json");
423                         return json_encode($ret);
424                         break;
425                 case "rss":
426                         header("Content-Type: application/rss+xml");
427                         return $ret;
428                         break;
429                 case "atom":
430                         header("Content-Type: application/atom+xml");
431                         return $ret;
432                         break;
433         }
434 }
435
436 /**
437  * @brief Set values for RSS template
438  *
439  * @param App $a
440  * @param array $arr       Array to be passed to template
441  * @param array $user_info User info
442  * @return array
443  * @todo find proper type-hints
444  */
445 function api_rss_extra(App $a, $arr, $user_info)
446 {
447         if (is_null($user_info)) {
448                 $user_info = api_get_user($a);
449         }
450
451         $arr['$user'] = $user_info;
452         $arr['$rss'] = array(
453                 'alternate'    => $user_info['url'],
454                 'self'         => System::baseUrl() . "/" . $a->query_string,
455                 'base'         => System::baseUrl(),
456                 'updated'      => api_date(null),
457                 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
458                 'language'     => $user_info['language'],
459                 'logo'         => System::baseUrl() . "/images/friendica-32.png",
460         );
461
462         return $arr;
463 }
464
465
466 /**
467  * @brief Unique contact to contact url.
468  *
469  * @param int $id Contact id
470  * @return bool|string
471  *              Contact url or False if contact id is unknown
472  */
473 function api_unique_id_to_nurl($id)
474 {
475         $r = dba::select('contact', array('nurl'), array('uid' => 0, 'id' => $id), array('limit' => 1));
476
477         if (DBM::is_result($r)) {
478                 return $r["nurl"];
479         } else {
480                 return false;
481         }
482 }
483
484 /**
485  * @brief Get user info array.
486  *
487  * @param object     $a          App
488  * @param int|string $contact_id Contact ID or URL
489  */
490 function api_get_user(App $a, $contact_id = null)
491 {
492         global $called_api;
493
494         $user = null;
495         $extra_query = "";
496         $url = "";
497         $nick = "";
498
499         logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
500
501         // Searching for contact URL
502         if (!is_null($contact_id) && (intval($contact_id) == 0)) {
503                 $user = dbesc(normalise_link($contact_id));
504                 $url = $user;
505                 $extra_query = "AND `contact`.`nurl` = '%s' ";
506                 if (api_user() !== false) {
507                         $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
508                 }
509         }
510
511         // Searching for contact id with uid = 0
512         if (!is_null($contact_id) && (intval($contact_id) != 0)) {
513                 $user = dbesc(api_unique_id_to_nurl($contact_id));
514
515                 if ($user == "") {
516                         throw new BadRequestException("User not found.");
517                 }
518
519                 $url = $user;
520                 $extra_query = "AND `contact`.`nurl` = '%s' ";
521                 if (api_user() !== false) {
522                         $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
523                 }
524         }
525
526         if (is_null($user) && x($_GET, 'user_id')) {
527                 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
528
529                 if ($user == "") {
530                         throw new BadRequestException("User not found.");
531                 }
532
533                 $url = $user;
534                 $extra_query = "AND `contact`.`nurl` = '%s' ";
535                 if (api_user() !== false) {
536                         $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
537                 }
538         }
539         if (is_null($user) && x($_GET, 'screen_name')) {
540                 $user = dbesc($_GET['screen_name']);
541                 $nick = $user;
542                 $extra_query = "AND `contact`.`nick` = '%s' ";
543                 if (api_user() !== false) {
544                         $extra_query .= "AND `contact`.`uid`=".intval(api_user());
545                 }
546         }
547
548         if (is_null($user) && x($_GET, 'profileurl')) {
549                 $user = dbesc(normalise_link($_GET['profileurl']));
550                 $nick = $user;
551                 $extra_query = "AND `contact`.`nurl` = '%s' ";
552                 if (api_user() !== false) {
553                         $extra_query .= "AND `contact`.`uid`=".intval(api_user());
554                 }
555         }
556
557         if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
558                 $argid = count($called_api);
559                 list($user, $null) = explode(".", $a->argv[$argid]);
560                 if (is_numeric($user)) {
561                         $user = dbesc(api_unique_id_to_nurl($user));
562
563                         if ($user == "") {
564                                 return false;
565                         }
566
567                         $url = $user;
568                         $extra_query = "AND `contact`.`nurl` = '%s' ";
569                         if (api_user() !== false) {
570                                 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
571                         }
572                 } else {
573                         $user = dbesc($user);
574                         $nick = $user;
575                         $extra_query = "AND `contact`.`nick` = '%s' ";
576                         if (api_user() !== false) {
577                                 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
578                         }
579                 }
580         }
581
582         logger("api_get_user: user ".$user, LOGGER_DEBUG);
583
584         if (!$user) {
585                 if (api_user() === false) {
586                         api_login($a);
587                         return false;
588                 } else {
589                         $user = $_SESSION['uid'];
590                         $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
591                 }
592         }
593
594         logger('api_user: ' . $extra_query . ', user: ' . $user);
595
596         // user info
597         $uinfo = q(
598                 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
599                         WHERE 1
600                 $extra_query",
601                 $user
602         );
603
604         // Selecting the id by priority, friendica first
605         api_best_nickname($uinfo);
606
607         // if the contact wasn't found, fetch it from the contacts with uid = 0
608         if (!DBM::is_result($uinfo)) {
609                 $r = array();
610
611                 if ($url != "") {
612                         $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
613                 }
614
615                 if (DBM::is_result($r)) {
616                         $network_name = network_to_name($r[0]['network'], $r[0]['url']);
617
618                         // If no nick where given, extract it from the address
619                         if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
620                                 $r[0]['nick'] = api_get_nick($r[0]["url"]);
621                         }
622
623                         $ret = array(
624                                 'id' => $r[0]["id"],
625                                 'id_str' => (string) $r[0]["id"],
626                                 'name' => $r[0]["name"],
627                                 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
628                                 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
629                                 'description' => $r[0]["about"],
630                                 'profile_image_url' => $r[0]["micro"],
631                                 'profile_image_url_https' => $r[0]["micro"],
632                                 'url' => $r[0]["url"],
633                                 'protected' => false,
634                                 'followers_count' => 0,
635                                 'friends_count' => 0,
636                                 'listed_count' => 0,
637                                 'created_at' => api_date($r[0]["created"]),
638                                 'favourites_count' => 0,
639                                 'utc_offset' => 0,
640                                 'time_zone' => 'UTC',
641                                 'geo_enabled' => false,
642                                 'verified' => false,
643                                 'statuses_count' => 0,
644                                 'lang' => '',
645                                 'contributors_enabled' => false,
646                                 'is_translator' => false,
647                                 'is_translation_enabled' => false,
648                                 'following' => false,
649                                 'follow_request_sent' => false,
650                                 'statusnet_blocking' => false,
651                                 'notifications' => false,
652                                 'statusnet_profile_url' => $r[0]["url"],
653                                 'uid' => 0,
654                                 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
655                                 'self' => 0,
656                                 'network' => $r[0]["network"],
657                         );
658
659                         return $ret;
660                 } else {
661                         throw new BadRequestException("User not found.");
662                 }
663         }
664
665         if ($uinfo[0]['self']) {
666                 if ($uinfo[0]['network'] == "") {
667                         $uinfo[0]['network'] = NETWORK_DFRN;
668                 }
669
670                 $usr = q(
671                         "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
672                         intval(api_user())
673                 );
674                 $profile = q(
675                         "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
676                         intval(api_user())
677                 );
678
679                 /// @TODO old-lost code? (twice)
680                 // Counting is deactivated by now, due to performance issues
681                 // count public wall messages
682                 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
683                 //              intval($uinfo[0]['uid'])
684                 //);
685                 //$countitms = $r[0]['count'];
686                 $countitms = 0;
687         } else {
688                 // Counting is deactivated by now, due to performance issues
689                 //$r = q("SELECT count(*) as `count` FROM `item`
690                 //              WHERE  `contact-id` = %d",
691                 //              intval($uinfo[0]['id'])
692                 //);
693                 //$countitms = $r[0]['count'];
694                 $countitms = 0;
695         }
696
697                 /// @TODO old-lost code? (twice)
698                 /*
699                 // Counting is deactivated by now, due to performance issues
700                 // count friends
701                 $r = q("SELECT count(*) as `count` FROM `contact`
702                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
703                                 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
704                                 intval($uinfo[0]['uid']),
705                                 intval(CONTACT_IS_SHARING),
706                                 intval(CONTACT_IS_FRIEND)
707                 );
708                 $countfriends = $r[0]['count'];
709
710                 $r = q("SELECT count(*) as `count` FROM `contact`
711                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
712                                 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
713                                 intval($uinfo[0]['uid']),
714                                 intval(CONTACT_IS_FOLLOWER),
715                                 intval(CONTACT_IS_FRIEND)
716                 );
717                 $countfollowers = $r[0]['count'];
718
719                 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
720                         intval($uinfo[0]['uid'])
721                 );
722                 $starred = $r[0]['count'];
723
724
725                 if (! $uinfo[0]['self']) {
726                         $countfriends = 0;
727                         $countfollowers = 0;
728                         $starred = 0;
729                 }
730                 */
731         $countfriends = 0;
732         $countfollowers = 0;
733         $starred = 0;
734
735         // Add a nick if it isn't present there
736         if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
737                 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
738         }
739
740         $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
741
742         $pcontact_id  = Contact::getIdForURL($uinfo[0]['url'], 0, true);
743
744         $ret = array(
745                 'id' => intval($pcontact_id),
746                 'id_str' => (string) intval($pcontact_id),
747                 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
748                 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
749                 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
750                 'description' => (($profile) ? $profile[0]['pdesc'] : null),
751                 'profile_image_url' => $uinfo[0]['micro'],
752                 'profile_image_url_https' => $uinfo[0]['micro'],
753                 'url' => $uinfo[0]['url'],
754                 'protected' => false,
755                 'followers_count' => intval($countfollowers),
756                 'friends_count' => intval($countfriends),
757                 'listed_count' => 0,
758                 'created_at' => api_date($uinfo[0]['created']),
759                 'favourites_count' => intval($starred),
760                 'utc_offset' => "0",
761                 'time_zone' => 'UTC',
762                 'geo_enabled' => false,
763                 'verified' => true,
764                 'statuses_count' => intval($countitms),
765                 'lang' => '',
766                 'contributors_enabled' => false,
767                 'is_translator' => false,
768                 'is_translation_enabled' => false,
769                 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
770                 'follow_request_sent' => false,
771                 'statusnet_blocking' => false,
772                 'notifications' => false,
773                 /// @TODO old way?
774                 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
775                 'statusnet_profile_url' => $uinfo[0]['url'],
776                 'uid' => intval($uinfo[0]['uid']),
777                 'cid' => intval($uinfo[0]['cid']),
778                 'self' => $uinfo[0]['self'],
779                 'network' => $uinfo[0]['network'],
780         );
781
782         return $ret;
783 }
784
785 /**
786  * @brief return api-formatted array for item's author and owner
787  *
788  * @param object $a    App
789  * @param array  $item item from db
790  * @return array(array:author, array:owner)
791  */
792 function api_item_get_user(App $a, $item)
793 {
794         $status_user = api_get_user($a, $item["author-link"]);
795
796         $status_user["protected"] = (($item["allow_cid"] != "") ||
797                                         ($item["allow_gid"] != "") ||
798                                         ($item["deny_cid"] != "") ||
799                                         ($item["deny_gid"] != "") ||
800                                         $item["private"]);
801
802         if ($item['thr-parent'] == $item['uri']) {
803                 $owner_user = api_get_user($a, $item["owner-link"]);
804         } else {
805                 $owner_user = $status_user;
806         }
807
808         return (array($status_user, $owner_user));
809 }
810
811 /**
812  * @brief walks recursively through an array with the possibility to change value and key
813  *
814  * @param array  $array    The array to walk through
815  * @param string $callback The callback function
816  *
817  * @return array the transformed array
818  */
819 function api_walk_recursive(array &$array, callable $callback)
820 {
821         $new_array = array();
822
823         foreach ($array as $k => $v) {
824                 if (is_array($v)) {
825                         if ($callback($v, $k)) {
826                                 $new_array[$k] = api_walk_recursive($v, $callback);
827                         }
828                 } else {
829                         if ($callback($v, $k)) {
830                                 $new_array[$k] = $v;
831                         }
832                 }
833         }
834         $array = $new_array;
835
836         return $array;
837 }
838
839 /**
840  * @brief Callback function to transform the array in an array that can be transformed in a XML file
841  *
842  * @param mixed  $item Array item value
843  * @param string $key  Array key
844  *
845  * @return boolean Should the array item be deleted?
846  */
847 function api_reformat_xml(&$item, &$key)
848 {
849         if (is_bool($item)) {
850                 $item = ($item ? "true" : "false");
851         }
852
853         if (substr($key, 0, 10) == "statusnet_") {
854                 $key = "statusnet:".substr($key, 10);
855         } elseif (substr($key, 0, 10) == "friendica_") {
856                 $key = "friendica:".substr($key, 10);
857         }
858         /// @TODO old-lost code?
859         //else
860         //      $key = "default:".$key;
861
862         return true;
863 }
864
865 /**
866  * @brief Creates the XML from a JSON style array
867  *
868  * @param array  $data         JSON style array
869  * @param string $root_element Name of the root element
870  *
871  * @return string The XML data
872  */
873 function api_create_xml($data, $root_element)
874 {
875         $childname = key($data);
876         $data2 = array_pop($data);
877         $key = key($data2);
878
879         $namespaces = array("" => "http://api.twitter.com",
880                                 "statusnet" => "http://status.net/schema/api/1/",
881                                 "friendica" => "http://friendi.ca/schema/api/1/",
882                                 "georss" => "http://www.georss.org/georss");
883
884         /// @todo Auto detection of needed namespaces
885         if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
886                 $namespaces = array();
887         }
888
889         if (is_array($data2)) {
890                 api_walk_recursive($data2, "api_reformat_xml");
891         }
892
893         if ($key == "0") {
894                 $data4 = array();
895                 $i = 1;
896
897                 foreach ($data2 as $item) {
898                         $data4[$i++.":".$childname] = $item;
899                 }
900
901                 $data2 = $data4;
902         }
903
904         $data3 = array($root_element => $data2);
905
906         $ret = XML::fromArray($data3, $xml, false, $namespaces);
907         return $ret;
908 }
909
910 /**
911  * @brief Formats the data according to the data type
912  *
913  * @param string $root_element Name of the root element
914  * @param string $type         Return type (atom, rss, xml, json)
915  * @param array  $data         JSON style array
916  *
917  * @return (string|object) XML data or JSON data
918  */
919 function api_format_data($root_element, $type, $data)
920 {
921         $a = get_app();
922
923         switch ($type) {
924                 case "atom":
925                 case "rss":
926                 case "xml":
927                         $ret = api_create_xml($data, $root_element);
928                         break;
929                 case "json":
930                         $ret = $data;
931                         break;
932         }
933
934         return $ret;
935 }
936
937 /**
938  * TWITTER API
939  */
940
941 /**
942  * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
943  * returns a 401 status code and an error message if not.
944  * http://developer.twitter.com/doc/get/account/verify_credentials
945  */
946 function api_account_verify_credentials($type)
947 {
948
949         $a = get_app();
950
951         if (api_user() === false) {
952                 throw new ForbiddenException();
953         }
954
955         unset($_REQUEST["user_id"]);
956         unset($_GET["user_id"]);
957
958         unset($_REQUEST["screen_name"]);
959         unset($_GET["screen_name"]);
960
961         $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
962
963         $user_info = api_get_user($a);
964
965         // "verified" isn't used here in the standard
966         unset($user_info["verified"]);
967
968         // - Adding last status
969         if (!$skip_status) {
970                 $user_info["status"] = api_status_show("raw");
971                 if (!count($user_info["status"])) {
972                         unset($user_info["status"]);
973                 } else {
974                         unset($user_info["status"]["user"]);
975                 }
976         }
977
978         // "uid" and "self" are only needed for some internal stuff, so remove it from here
979         unset($user_info["uid"]);
980         unset($user_info["self"]);
981
982         return api_format_data("user", $type, array('user' => $user_info));
983 }
984
985 /// @TODO move to top of file or somwhere better
986 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
987
988 /**
989  * Get data from $_POST or $_GET
990  */
991 function requestdata($k)
992 {
993         if (x($_POST, $k)) {
994                 return $_POST[$k];
995         }
996         if (x($_GET, $k)) {
997                 return $_GET[$k];
998         }
999         return null;
1000 }
1001
1002 /*Waitman Gobble Mod*/
1003 function api_statuses_mediap($type)
1004 {
1005         $a = get_app();
1006
1007         if (api_user() === false) {
1008                 logger('api_statuses_update: no user');
1009                 throw new ForbiddenException();
1010         }
1011         $user_info = api_get_user($a);
1012
1013         $_REQUEST['type'] = 'wall';
1014         $_REQUEST['profile_uid'] = api_user();
1015         $_REQUEST['api_source'] = true;
1016         $txt = requestdata('status');
1017         /// @TODO old-lost code?
1018         //$txt = urldecode(requestdata('status'));
1019
1020         if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1021                 $txt = html2bb_video($txt);
1022                 $config = HTMLPurifier_Config::createDefault();
1023                 $config->set('Cache.DefinitionImpl', null);
1024                 $purifier = new HTMLPurifier($config);
1025                 $txt = $purifier->purify($txt);
1026         }
1027         $txt = html2bbcode($txt);
1028
1029         $a->argv[1]=$user_info['screen_name']; //should be set to username?
1030
1031         // tell wall_upload function to return img info instead of echo
1032         $_REQUEST['hush'] = 'yeah';
1033         $bebop = wall_upload_post($a);
1034
1035         // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1036         $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1037         item_post($a);
1038
1039         // this should output the last post (the one we just posted).
1040         return api_status_show($type);
1041 }
1042
1043 /// @TODO move this to top of file or somewhere better!
1044 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1045
1046 function api_statuses_update($type)
1047 {
1048
1049         $a = get_app();
1050
1051         if (api_user() === false) {
1052                 logger('api_statuses_update: no user');
1053                 throw new ForbiddenException();
1054         }
1055
1056         $user_info = api_get_user($a);
1057
1058         // convert $_POST array items to the form we use for web posts.
1059
1060         // logger('api_post: ' . print_r($_POST,true));
1061
1062         if (requestdata('htmlstatus')) {
1063                 $txt = requestdata('htmlstatus');
1064                 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1065                         $txt = html2bb_video($txt);
1066
1067                         $config = HTMLPurifier_Config::createDefault();
1068                         $config->set('Cache.DefinitionImpl', null);
1069
1070                         $purifier = new HTMLPurifier($config);
1071                         $txt = $purifier->purify($txt);
1072
1073                         $_REQUEST['body'] = html2bbcode($txt);
1074                 }
1075         } else {
1076                 $_REQUEST['body'] = requestdata('status');
1077         }
1078
1079         $_REQUEST['title'] = requestdata('title');
1080
1081         $parent = requestdata('in_reply_to_status_id');
1082
1083         // Twidere sends "-1" if it is no reply ...
1084         if ($parent == -1) {
1085                 $parent = "";
1086         }
1087
1088         if (ctype_digit($parent)) {
1089                 $_REQUEST['parent'] = $parent;
1090         } else {
1091                 $_REQUEST['parent_uri'] = $parent;
1092         }
1093
1094         if (requestdata('lat') && requestdata('long')) {
1095                 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1096         }
1097         $_REQUEST['profile_uid'] = api_user();
1098
1099         if ($parent) {
1100                 $_REQUEST['type'] = 'net-comment';
1101         } else {
1102                 // Check for throttling (maximum posts per day, week and month)
1103                 $throttle_day = Config::get('system', 'throttle_limit_day');
1104                 if ($throttle_day > 0) {
1105                         $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1106
1107                         $r = q(
1108                                 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1109                                 AND `created` > '%s' AND `id` = `parent`",
1110                                 intval(api_user()),
1111                                 dbesc($datefrom)
1112                         );
1113
1114                         if (DBM::is_result($r)) {
1115                                 $posts_day = $r[0]["posts_day"];
1116                         } else {
1117                                 $posts_day = 0;
1118                         }
1119
1120                         if ($posts_day > $throttle_day) {
1121                                 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1122                                 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1123                                 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1124                         }
1125                 }
1126
1127                 $throttle_week = Config::get('system', 'throttle_limit_week');
1128                 if ($throttle_week > 0) {
1129                         $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1130
1131                         $r = q(
1132                                 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1133                                 AND `created` > '%s' AND `id` = `parent`",
1134                                 intval(api_user()),
1135                                 dbesc($datefrom)
1136                         );
1137
1138                         if (DBM::is_result($r)) {
1139                                 $posts_week = $r[0]["posts_week"];
1140                         } else {
1141                                 $posts_week = 0;
1142                         }
1143
1144                         if ($posts_week > $throttle_week) {
1145                                 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1146                                 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1147                                 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1148                         }
1149                 }
1150
1151                 $throttle_month = Config::get('system', 'throttle_limit_month');
1152                 if ($throttle_month > 0) {
1153                         $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1154
1155                         $r = q(
1156                                 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1157                                 AND `created` > '%s' AND `id` = `parent`",
1158                                 intval(api_user()),
1159                                 dbesc($datefrom)
1160                         );
1161
1162                         if (DBM::is_result($r)) {
1163                                 $posts_month = $r[0]["posts_month"];
1164                         } else {
1165                                 $posts_month = 0;
1166                         }
1167
1168                         if ($posts_month > $throttle_month) {
1169                                 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1170                                 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1171                                 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1172                         }
1173                 }
1174
1175                 $_REQUEST['type'] = 'wall';
1176         }
1177
1178         if (x($_FILES, 'media')) {
1179                 // upload the image if we have one
1180                 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1181                 $media = wall_upload_post($a);
1182                 if (strlen($media) > 0) {
1183                         $_REQUEST['body'] .= "\n\n" . $media;
1184                 }
1185         }
1186
1187         // To-Do: Multiple IDs
1188         if (requestdata('media_ids')) {
1189                 $r = q(
1190                         "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",
1191                         intval(requestdata('media_ids')),
1192                         api_user()
1193                 );
1194                 if (DBM::is_result($r)) {
1195                         $phototypes = Image::supportedTypes();
1196                         $ext = $phototypes[$r[0]['type']];
1197                         $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1198                         $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1199                 }
1200         }
1201
1202         // set this so that the item_post() function is quiet and doesn't redirect or emit json
1203
1204         $_REQUEST['api_source'] = true;
1205
1206         if (!x($_REQUEST, "source")) {
1207                 $_REQUEST["source"] = api_source();
1208         }
1209
1210         // call out normal post function
1211         item_post($a);
1212
1213         // this should output the last post (the one we just posted).
1214         return api_status_show($type);
1215 }
1216
1217 /// @TODO move to top of file or somwhere better
1218 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1219 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1220
1221 function api_media_upload($type)
1222 {
1223         $a = get_app();
1224
1225         if (api_user() === false) {
1226                 logger('no user');
1227                 throw new ForbiddenException();
1228         }
1229
1230         $user_info = api_get_user($a);
1231
1232         if (!x($_FILES, 'media')) {
1233                 // Output error
1234                 throw new BadRequestException("No media.");
1235         }
1236
1237         $media = wall_upload_post($a, false);
1238         if (!$media) {
1239                 // Output error
1240                 throw new InternalServerErrorException();
1241         }
1242
1243         $returndata = array();
1244         $returndata["media_id"] = $media["id"];
1245         $returndata["media_id_string"] = (string)$media["id"];
1246         $returndata["size"] = $media["size"];
1247         $returndata["image"] = array("w" => $media["width"],
1248                                         "h" => $media["height"],
1249                                         "image_type" => $media["type"]);
1250
1251         logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1252
1253         return array("media" => $returndata);
1254 }
1255
1256 /// @TODO move to top of file or somwhere better
1257 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1258
1259 function api_status_show($type)
1260 {
1261         $a = get_app();
1262
1263         $user_info = api_get_user($a);
1264
1265         logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1266
1267         if ($type == "raw") {
1268                 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1269         } else {
1270                 $privacy_sql = "";
1271         }
1272
1273         // get last public wall message
1274         $lastwall = q(
1275                 "SELECT `item`.*
1276                         FROM `item`
1277                         WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1278                                 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1279                                 AND `item`.`type` != 'activity' $privacy_sql
1280                         ORDER BY `item`.`id` DESC
1281                         LIMIT 1",
1282                 intval($user_info['cid']),
1283                 intval(api_user()),
1284                 dbesc($user_info['url']),
1285                 dbesc(normalise_link($user_info['url'])),
1286                 dbesc($user_info['url']),
1287                 dbesc(normalise_link($user_info['url']))
1288         );
1289
1290         if (DBM::is_result($lastwall)) {
1291                 $lastwall = $lastwall[0];
1292
1293                 $in_reply_to = api_in_reply_to($lastwall);
1294
1295                 $converted = api_convert_item($lastwall);
1296
1297                 if ($type == "xml") {
1298                         $geo = "georss:point";
1299                 } else {
1300                         $geo = "geo";
1301                 }
1302
1303                 $status_info = array(
1304                         'created_at' => api_date($lastwall['created']),
1305                         'id' => intval($lastwall['id']),
1306                         'id_str' => (string) $lastwall['id'],
1307                         'text' => $converted["text"],
1308                         'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1309                         'truncated' => false,
1310                         'in_reply_to_status_id' => $in_reply_to['status_id'],
1311                         'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1312                         'in_reply_to_user_id' => $in_reply_to['user_id'],
1313                         'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1314                         'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1315                         'user' => $user_info,
1316                         $geo => null,
1317                         'coordinates' => "",
1318                         'place' => "",
1319                         'contributors' => "",
1320                         'is_quote_status' => false,
1321                         'retweet_count' => 0,
1322                         'favorite_count' => 0,
1323                         'favorited' => $lastwall['starred'] ? true : false,
1324                         'retweeted' => false,
1325                         'possibly_sensitive' => false,
1326                         'lang' => "",
1327                         'statusnet_html' => $converted["html"],
1328                         'statusnet_conversation_id' => $lastwall['parent'],
1329                         'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1330                 );
1331
1332                 if (count($converted["attachments"]) > 0) {
1333                         $status_info["attachments"] = $converted["attachments"];
1334                 }
1335
1336                 if (count($converted["entities"]) > 0) {
1337                         $status_info["entities"] = $converted["entities"];
1338                 }
1339
1340                 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1341                         $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1342                 } elseif (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1343                         $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1344                 }
1345
1346                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1347                 unset($status_info["user"]["uid"]);
1348                 unset($status_info["user"]["self"]);
1349         }
1350
1351         logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1352
1353         if ($type == "raw") {
1354                 return $status_info;
1355         }
1356
1357         return api_format_data("statuses", $type, array('status' => $status_info));
1358 }
1359
1360 /**
1361  * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1362  * The author's most recent status will be returned inline.
1363  * http://developer.twitter.com/doc/get/users/show
1364  */
1365 function api_users_show($type)
1366 {
1367         $a = get_app();
1368
1369         $user_info = api_get_user($a);
1370         $lastwall = q(
1371                 "SELECT `item`.*
1372                         FROM `item`
1373                         INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1374                         WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1375                                 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1376                                 AND `type`!='activity'
1377                                 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1378                         ORDER BY `id` DESC
1379                         LIMIT 1",
1380                 intval(api_user()),
1381                 dbesc(ACTIVITY_POST),
1382                 intval($user_info['cid']),
1383                 dbesc($user_info['url']),
1384                 dbesc(normalise_link($user_info['url'])),
1385                 dbesc($user_info['url']),
1386                 dbesc(normalise_link($user_info['url']))
1387         );
1388
1389         if (DBM::is_result($lastwall)) {
1390                 $lastwall = $lastwall[0];
1391
1392                 $in_reply_to = api_in_reply_to($lastwall);
1393
1394                 $converted = api_convert_item($lastwall);
1395
1396                 if ($type == "xml") {
1397                         $geo = "georss:point";
1398                 } else {
1399                         $geo = "geo";
1400                 }
1401
1402                 $user_info['status'] = array(
1403                         'text' => $converted["text"],
1404                         'truncated' => false,
1405                         'created_at' => api_date($lastwall['created']),
1406                         'in_reply_to_status_id' => $in_reply_to['status_id'],
1407                         'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1408                         'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1409                         'id' => intval($lastwall['contact-id']),
1410                         'id_str' => (string) $lastwall['contact-id'],
1411                         'in_reply_to_user_id' => $in_reply_to['user_id'],
1412                         'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1413                         'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1414                         $geo => null,
1415                         'favorited' => $lastwall['starred'] ? true : false,
1416                         'statusnet_html' => $converted["html"],
1417                         'statusnet_conversation_id' => $lastwall['parent'],
1418                         'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1419                 );
1420
1421                 if (count($converted["attachments"]) > 0) {
1422                         $user_info["status"]["attachments"] = $converted["attachments"];
1423                 }
1424
1425                 if (count($converted["entities"]) > 0) {
1426                         $user_info["status"]["entities"] = $converted["entities"];
1427                 }
1428
1429                 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1430                         $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1431                 }
1432
1433                 if (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1434                         $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
1435                 }
1436         }
1437
1438         // "uid" and "self" are only needed for some internal stuff, so remove it from here
1439         unset($user_info["uid"]);
1440         unset($user_info["self"]);
1441
1442         return api_format_data("user", $type, array('user' => $user_info));
1443 }
1444
1445 /// @TODO move to top of file or somewhere better
1446 api_register_func('api/users/show', 'api_users_show');
1447 api_register_func('api/externalprofile/show', 'api_users_show');
1448
1449 function api_users_search($type)
1450 {
1451         $a = get_app();
1452
1453         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1454
1455         $userlist = array();
1456
1457         if (x($_GET, 'q')) {
1458                 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1459
1460                 if (!DBM::is_result($r)) {
1461                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1462                 }
1463
1464                 if (DBM::is_result($r)) {
1465                         $k = 0;
1466                         foreach ($r as $user) {
1467                                 $user_info = api_get_user($a, $user["id"], "json");
1468
1469                                 if ($type == "xml") {
1470                                         $userlist[$k++.":user"] = $user_info;
1471                                 } else {
1472                                         $userlist[] = $user_info;
1473                                 }
1474                         }
1475                         $userlist = array("users" => $userlist);
1476                 } else {
1477                         throw new BadRequestException("User not found.");
1478                 }
1479         } else {
1480                 throw new BadRequestException("User not found.");
1481         }
1482         return api_format_data("users", $type, $userlist);
1483 }
1484
1485 /// @TODO move to top of file or somewhere better
1486 api_register_func('api/users/search', 'api_users_search');
1487
1488 /**
1489  *
1490  * http://developer.twitter.com/doc/get/statuses/home_timeline
1491  *
1492  * TODO: Optional parameters
1493  * TODO: Add reply info
1494  */
1495 function api_statuses_home_timeline($type)
1496 {
1497         $a = get_app();
1498
1499         if (api_user() === false) {
1500                 throw new ForbiddenException();
1501         }
1502
1503         unset($_REQUEST["user_id"]);
1504         unset($_GET["user_id"]);
1505
1506         unset($_REQUEST["screen_name"]);
1507         unset($_GET["screen_name"]);
1508
1509         $user_info = api_get_user($a);
1510         // get last newtork messages
1511
1512         // params
1513         $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1514         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1515         if ($page < 0) {
1516                 $page = 0;
1517         }
1518         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1519         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1520         //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1521         $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1522         $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1523
1524         $start = $page * $count;
1525
1526         $sql_extra = '';
1527         if ($max_id > 0) {
1528                 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1529         }
1530         if ($exclude_replies > 0) {
1531                 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1532         }
1533         if ($conversation_id > 0) {
1534                 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1535         }
1536
1537         $r = q(
1538                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1539                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1540                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1541                 `contact`.`id` AS `cid`
1542                 FROM `item`
1543                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1544                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1545                 WHERE `item`.`uid` = %d AND `verb` = '%s'
1546                 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1547                 $sql_extra
1548                 AND `item`.`id`>%d
1549                 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1550                 intval(api_user()),
1551                 dbesc(ACTIVITY_POST),
1552                 intval($since_id),
1553                 intval($start),
1554                 intval($count)
1555         );
1556
1557         $ret = api_format_items($r, $user_info, false, $type);
1558
1559         // Set all posts from the query above to seen
1560         $idarray = array();
1561         foreach ($r as $item) {
1562                 $idarray[] = intval($item["id"]);
1563         }
1564
1565         $idlist = implode(",", $idarray);
1566
1567         if ($idlist != "") {
1568                 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1569
1570                 if ($unseen) {
1571                         $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1572                 }
1573         }
1574
1575         $data = array('status' => $ret);
1576         switch ($type) {
1577                 case "atom":
1578                 case "rss":
1579                         $data = api_rss_extra($a, $data, $user_info);
1580                         break;
1581         }
1582
1583         return api_format_data("statuses", $type, $data);
1584 }
1585
1586 /// @TODO move to top of file or somewhere better
1587 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1588 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1589
1590 function api_statuses_public_timeline($type)
1591 {
1592         $a = get_app();
1593
1594         if (api_user() === false) {
1595                 throw new ForbiddenException();
1596         }
1597
1598         $user_info = api_get_user($a);
1599         // get last newtork messages
1600
1601         // params
1602         $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1603         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1604         if ($page < 0) {
1605                 $page = 0;
1606         }
1607         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1608         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1609         //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1610         $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1611         $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1612
1613         $start = $page * $count;
1614
1615         if ($max_id > 0) {
1616                 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1617         }
1618         if ($exclude_replies > 0) {
1619                 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1620         }
1621         if ($conversation_id > 0) {
1622                 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1623         }
1624
1625         $r = q(
1626                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1627                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1628                 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1629                 `contact`.`id` AS `cid`,
1630                 `user`.`nickname`, `user`.`hidewall`
1631                 FROM `item`
1632                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1633                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1634                 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1635                         AND NOT `user`.`hidewall`
1636                 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1637                 AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
1638                 AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
1639                 AND NOT `item`.`private` AND `item`.`wall`
1640                 $sql_extra
1641                 AND `item`.`id`>%d
1642                 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1643                 dbesc(ACTIVITY_POST),
1644                 intval($since_id),
1645                 intval($start),
1646                 intval($count)
1647         );
1648
1649         $ret = api_format_items($r, $user_info, false, $type);
1650
1651         $data = array('status' => $ret);
1652         switch ($type) {
1653                 case "atom":
1654                 case "rss":
1655                         $data = api_rss_extra($a, $data, $user_info);
1656                         break;
1657         }
1658
1659         return api_format_data("statuses", $type, $data);
1660 }
1661
1662 /// @TODO move to top of file or somewhere better
1663 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1664
1665 /**
1666  * @brief Returns the list of public federated posts this node knows about
1667  *
1668  * @param string $type Return format: json, xml, atom, rss
1669  * @return array|string
1670  * @throws ForbiddenException
1671  */
1672 function api_statuses_networkpublic_timeline($type)
1673 {
1674         $a = get_app();
1675
1676         if (api_user() === false) {
1677                 throw new ForbiddenException();
1678         }
1679
1680         $user_info = api_get_user($a);
1681
1682         $since_id        = x($_REQUEST, 'since_id')        ? $_REQUEST['since_id']        : 0;
1683         $max_id          = x($_REQUEST, 'max_id')          ? $_REQUEST['max_id']          : 0;
1684
1685         // pagination
1686         $count = x($_REQUEST, 'count') ? $_REQUEST['count']   : 20;
1687         $page  = x($_REQUEST, 'page')  ? $_REQUEST['page']    : 1;
1688         if ($page < 1) {
1689                 $page = 1;
1690         }
1691         $start = ($page - 1) * $count;
1692
1693         $sql_extra = '';
1694         if ($max_id > 0) {
1695                 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1696         }
1697
1698         $r = dba::p("SELECT " . item_fieldlists() . "
1699                 FROM `thread`
1700                 INNER JOIN `item` ON `item`.`id` = `thread`.`iid`
1701                 " . item_joins() . "
1702                 WHERE `thread`.`uid` = 0
1703                 AND `verb` = ?
1704                 AND `item`.`id` > ?
1705                 $sql_extra
1706                 ORDER BY `thread`.`iid` DESC
1707                 LIMIT " . intval($start) . ", " . intval($count),
1708                 ACTIVITY_POST,
1709                 $since_id
1710         );
1711
1712         $r = dba::inArray($r);
1713
1714         $ret = api_format_items($r, $user_info, false, $type);
1715
1716         $data = array('status' => $ret);
1717         switch ($type) {
1718                 case "atom":
1719                 case "rss":
1720                         $data = api_rss_extra($a, $data, $user_info);
1721                         break;
1722         }
1723
1724         return api_format_data("statuses", $type, $data);
1725 }
1726
1727 /// @TODO move to top of file or somewhere better
1728 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1729
1730 /**
1731  * @TODO nothing to say?
1732  */
1733 function api_statuses_show($type)
1734 {
1735         $a = get_app();
1736
1737         if (api_user() === false) {
1738                 throw new ForbiddenException();
1739         }
1740
1741         $user_info = api_get_user($a);
1742
1743         // params
1744         $id = intval($a->argv[3]);
1745
1746         if ($id == 0) {
1747                 $id = intval($_REQUEST["id"]);
1748         }
1749
1750         // Hotot workaround
1751         if ($id == 0) {
1752                 $id = intval($a->argv[4]);
1753         }
1754
1755         logger('API: api_statuses_show: ' . $id);
1756
1757         $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1758
1759         $sql_extra = '';
1760         if ($conversation) {
1761                 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1762         } else {
1763                 $sql_extra .= " AND `item`.`id` = %d";
1764         }
1765
1766         $r = q(
1767                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1768                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1769                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1770                 `contact`.`id` AS `cid`
1771                 FROM `item`
1772                 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1773                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1774                 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1775                 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1776                 $sql_extra",
1777                 intval(api_user()),
1778                 dbesc(ACTIVITY_POST),
1779                 intval($id)
1780         );
1781
1782         /// @TODO How about copying this to above methods which don't check $r ?
1783         if (!DBM::is_result($r)) {
1784                 throw new BadRequestException("There is no status with this id.");
1785         }
1786
1787         $ret = api_format_items($r, $user_info, false, $type);
1788
1789         if ($conversation) {
1790                 $data = array('status' => $ret);
1791                 return api_format_data("statuses", $type, $data);
1792         } else {
1793                 $data = array('status' => $ret[0]);
1794                 return api_format_data("status", $type, $data);
1795         }
1796 }
1797
1798 /// @TODO move to top of file or somewhere better
1799 api_register_func('api/statuses/show', 'api_statuses_show', true);
1800
1801 /**
1802  * @TODO nothing to say?
1803  */
1804 function api_conversation_show($type)
1805 {
1806         $a = get_app();
1807
1808         if (api_user() === false) {
1809                 throw new ForbiddenException();
1810         }
1811
1812         $user_info = api_get_user($a);
1813
1814         // params
1815         $id = intval($a->argv[3]);
1816         $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1817         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1818         if ($page < 0) {
1819                 $page = 0;
1820         }
1821         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1822         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1823
1824         $start = $page*$count;
1825
1826         if ($id == 0) {
1827                 $id = intval($_REQUEST["id"]);
1828         }
1829
1830         // Hotot workaround
1831         if ($id == 0) {
1832                 $id = intval($a->argv[4]);
1833         }
1834
1835         logger('API: api_conversation_show: '.$id);
1836
1837         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1838         if (DBM::is_result($r)) {
1839                 $id = $r[0]["parent"];
1840         }
1841
1842         $sql_extra = '';
1843
1844         if ($max_id > 0) {
1845                 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1846         }
1847
1848         // Not sure why this query was so complicated. We should keep it here for a while,
1849         // just to make sure that we really don't need it.
1850         //      FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1851         //      ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1852
1853         $r = q(
1854                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1855                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1856                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1857                 `contact`.`id` AS `cid`
1858                 FROM `item`
1859                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1860                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1861                 WHERE `item`.`parent` = %d AND `item`.`visible`
1862                 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1863                 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1864                 AND `item`.`id`>%d $sql_extra
1865                 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1866                 intval($id), intval(api_user()),
1867                 dbesc(ACTIVITY_POST),
1868                 intval($since_id),
1869                 intval($start), intval($count)
1870         );
1871
1872         if (!DBM::is_result($r)) {
1873                 throw new BadRequestException("There is no status with this id.");
1874         }
1875
1876         $ret = api_format_items($r, $user_info, false, $type);
1877
1878         $data = array('status' => $ret);
1879         return api_format_data("statuses", $type, $data);
1880 }
1881
1882 /// @TODO move to top of file or somewhere better
1883 api_register_func('api/conversation/show', 'api_conversation_show', true);
1884 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1885
1886 /**
1887  * @TODO nothing to say?
1888  */
1889 function api_statuses_repeat($type)
1890 {
1891         global $called_api;
1892
1893         $a = get_app();
1894
1895         if (api_user() === false) {
1896                 throw new ForbiddenException();
1897         }
1898
1899         $user_info = api_get_user($a);
1900
1901         // params
1902         $id = intval($a->argv[3]);
1903
1904         if ($id == 0) {
1905                 $id = intval($_REQUEST["id"]);
1906         }
1907
1908         // Hotot workaround
1909         if ($id == 0) {
1910                 $id = intval($a->argv[4]);
1911         }
1912
1913         logger('API: api_statuses_repeat: '.$id);
1914
1915         $r = q(
1916                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1917                 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1918                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1919                 `contact`.`id` AS `cid`
1920                 FROM `item`
1921                 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1922                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1923                 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1924                 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1925                 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1926                 $sql_extra
1927                 AND `item`.`id`=%d",
1928                 intval($id)
1929         );
1930
1931         /// @TODO other style than above functions!
1932         if (DBM::is_result($r) && $r[0]['body'] != "") {
1933                 if (strpos($r[0]['body'], "[/share]") !== false) {
1934                         $pos = strpos($r[0]['body'], "[share");
1935                         $post = substr($r[0]['body'], $pos);
1936                 } else {
1937                         $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1938
1939                         $post .= $r[0]['body'];
1940                         $post .= "[/share]";
1941                 }
1942                 $_REQUEST['body'] = $post;
1943                 $_REQUEST['profile_uid'] = api_user();
1944                 $_REQUEST['type'] = 'wall';
1945                 $_REQUEST['api_source'] = true;
1946
1947                 if (!x($_REQUEST, "source")) {
1948                         $_REQUEST["source"] = api_source();
1949                 }
1950
1951                 item_post($a);
1952         } else {
1953                 throw new ForbiddenException();
1954         }
1955
1956         // this should output the last post (the one we just posted).
1957         $called_api = null;
1958         return api_status_show($type);
1959 }
1960
1961 /// @TODO move to top of file or somewhere better
1962 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1963
1964 /**
1965  * @TODO nothing to say?
1966  */
1967 function api_statuses_destroy($type)
1968 {
1969         $a = get_app();
1970
1971         if (api_user() === false) {
1972                 throw new ForbiddenException();
1973         }
1974
1975         $user_info = api_get_user($a);
1976
1977         // params
1978         $id = intval($a->argv[3]);
1979
1980         if ($id == 0) {
1981                 $id = intval($_REQUEST["id"]);
1982         }
1983
1984         // Hotot workaround
1985         if ($id == 0) {
1986                 $id = intval($a->argv[4]);
1987         }
1988
1989         logger('API: api_statuses_destroy: '.$id);
1990
1991         $ret = api_statuses_show($type);
1992
1993         drop_item($id, false);
1994
1995         return $ret;
1996 }
1997
1998 /// @TODO move to top of file or somewhere better
1999 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2000
2001 /**
2002  * @TODO Nothing more than an URL to say?
2003  * http://developer.twitter.com/doc/get/statuses/mentions
2004  */
2005 function api_statuses_mentions($type)
2006 {
2007         $a = get_app();
2008
2009         if (api_user() === false) {
2010                 throw new ForbiddenException();
2011         }
2012
2013         unset($_REQUEST["user_id"]);
2014         unset($_GET["user_id"]);
2015
2016         unset($_REQUEST["screen_name"]);
2017         unset($_GET["screen_name"]);
2018
2019         $user_info = api_get_user($a);
2020         // get last newtork messages
2021
2022
2023         // params
2024         $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2025         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2026         if ($page < 0) {
2027                 $page = 0;
2028         }
2029         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2030         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2031         //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2032
2033         $start = $page * $count;
2034
2035         // Ugly code - should be changed
2036         $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2037         $myurl = substr($myurl, strpos($myurl, '://') + 3);
2038         //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
2039         $myurl = str_replace('www.', '', $myurl);
2040         $diasp_url = str_replace('/profile/', '/u/', $myurl);
2041
2042         if ($max_id > 0) {
2043                 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2044         }
2045
2046         $r = q(
2047                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2048                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2049                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2050                 `contact`.`id` AS `cid`
2051                 FROM `item` FORCE INDEX (`uid_id`)
2052                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2053                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2054                 WHERE `item`.`uid` = %d AND `verb` = '%s'
2055                 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2056                 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2057                 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2058                 $sql_extra
2059                 AND `item`.`id`>%d
2060                 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2061                 intval(api_user()),
2062                 dbesc(ACTIVITY_POST),
2063                 dbesc(protect_sprintf($myurl)),
2064                 dbesc(protect_sprintf($myurl)),
2065                 intval(api_user()),
2066                 intval($since_id),
2067                 intval($start),
2068                 intval($count)
2069         );
2070
2071         $ret = api_format_items($r, $user_info, false, $type);
2072
2073         $data = array('status' => $ret);
2074         switch ($type) {
2075                 case "atom":
2076                 case "rss":
2077                         $data = api_rss_extra($a, $data, $user_info);
2078                         break;
2079         }
2080
2081         return api_format_data("statuses", $type, $data);
2082 }
2083
2084 /// @TODO move to top of file or somewhere better
2085 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2086 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2087
2088 /**
2089  * @brief Returns a user's public timeline
2090  *
2091  * @param string $type Either "json" or "xml"
2092  * @return string|array
2093  * @throws ForbiddenException
2094  */
2095 function api_statuses_user_timeline($type)
2096 {
2097         $a = get_app();
2098
2099         if (api_user() === false) {
2100                 throw new ForbiddenException();
2101         }
2102
2103         $user_info = api_get_user($a);
2104
2105         logger(
2106                 "api_statuses_user_timeline: api_user: ". api_user() .
2107                         "\nuser_info: ".print_r($user_info, true) .
2108                         "\n_REQUEST:  ".print_r($_REQUEST, true),
2109                 LOGGER_DEBUG
2110         );
2111
2112         $since_id        = x($_REQUEST, 'since_id')        ? $_REQUEST['since_id']        : 0;
2113         $max_id          = x($_REQUEST, 'max_id')          ? $_REQUEST['max_id']          : 0;
2114         $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1                            : 0;
2115         $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2116
2117         // pagination
2118         $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2119         $page  = x($_REQUEST, 'page')  ? $_REQUEST['page']  : 1;
2120         if ($page < 1) {
2121                 $page = 1;
2122         }
2123         $start = ($page - 1) * $count;
2124
2125         $sql_extra = '';
2126         if ($user_info['self'] == 1) {
2127                 $sql_extra .= " AND `item`.`wall` = 1 ";
2128         }
2129
2130         if ($exclude_replies > 0) {
2131                 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2132         }
2133
2134         if ($conversation_id > 0) {
2135                 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2136         }
2137
2138         if ($max_id > 0) {
2139                 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2140         }
2141
2142         $r = q(
2143                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2144                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2145                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2146                 `contact`.`id` AS `cid`
2147                 FROM `item` FORCE INDEX (`uid_contactid_id`)
2148                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2149                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2150                 WHERE `item`.`uid` = %d AND `verb` = '%s'
2151                 AND `item`.`contact-id` = %d
2152                 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2153                 $sql_extra
2154                 AND `item`.`id` > %d
2155                 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2156                 intval(api_user()),
2157                 dbesc(ACTIVITY_POST),
2158                 intval($user_info['cid']),
2159                 intval($since_id),
2160                 intval($start),
2161                 intval($count)
2162         );
2163
2164         $ret = api_format_items($r, $user_info, true, $type);
2165
2166         $data = array('status' => $ret);
2167         switch ($type) {
2168                 case "atom":
2169                 case "rss":
2170                         $data = api_rss_extra($a, $data, $user_info);
2171                         break;
2172         }
2173
2174         return api_format_data("statuses", $type, $data);
2175 }
2176
2177 /// @TODO move to top of file or somwhere better
2178 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2179
2180 /**
2181  * Star/unstar an item
2182  * param: id : id of the item
2183  *
2184  * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2185  */
2186 function api_favorites_create_destroy($type)
2187 {
2188         $a = get_app();
2189
2190         if (api_user() === false) {
2191                 throw new ForbiddenException();
2192         }
2193
2194         // for versioned api.
2195         /// @TODO We need a better global soluton
2196         $action_argv_id = 2;
2197         if ($a->argv[1] == "1.1") {
2198                 $action_argv_id = 3;
2199         }
2200
2201         if ($a->argc <= $action_argv_id) {
2202                 throw new BadRequestException("Invalid request.");
2203         }
2204         $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2205         if ($a->argc == $action_argv_id + 2) {
2206                 $itemid = intval($a->argv[$action_argv_id + 1]);
2207         } else {
2208                 ///  @TODO use x() to check if _REQUEST contains 'id'
2209                 $itemid = intval($_REQUEST['id']);
2210         }
2211
2212         $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2213
2214         if (!DBM::is_result($item) || count($item) == 0) {
2215                 throw new BadRequestException("Invalid item.");
2216         }
2217
2218         switch ($action) {
2219                 case "create":
2220                         $item[0]['starred'] = 1;
2221                         break;
2222                 case "destroy":
2223                         $item[0]['starred'] = 0;
2224                         break;
2225                 default:
2226                         throw new BadRequestException("Invalid action ".$action);
2227         }
2228
2229         $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",     $item[0]['starred'], $itemid, api_user());
2230
2231         q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2232
2233         if ($r === false) {
2234                 throw new InternalServerErrorException("DB error");
2235         }
2236
2237
2238         $user_info = api_get_user($a);
2239         $rets = api_format_items($item, $user_info, false, $type);
2240         $ret = $rets[0];
2241
2242         $data = array('status' => $ret);
2243         switch ($type) {
2244                 case "atom":
2245                 case "rss":
2246                         $data = api_rss_extra($a, $data, $user_info);
2247         }
2248
2249         return api_format_data("status", $type, $data);
2250 }
2251
2252 /// @TODO move to top of file or somwhere better
2253 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2254 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2255
2256 function api_favorites($type)
2257 {
2258         global $called_api;
2259
2260         $a = get_app();
2261
2262         if (api_user() === false) {
2263                 throw new ForbiddenException();
2264         }
2265
2266         $called_api = array();
2267
2268         $user_info = api_get_user($a);
2269
2270         // in friendica starred item are private
2271         // return favorites only for self
2272         logger('api_favorites: self:' . $user_info['self']);
2273
2274         if ($user_info['self'] == 0) {
2275                 $ret = array();
2276         } else {
2277                 $sql_extra = "";
2278
2279                 // params
2280                 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2281                 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2282                 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2283                 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2284                 if ($page < 0) {
2285                         $page = 0;
2286                 }
2287
2288                 $start = $page*$count;
2289
2290                 if ($max_id > 0) {
2291                         $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2292                 }
2293
2294                 $r = q(
2295                         "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2296                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2297                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2298                         `contact`.`id` AS `cid`
2299                         FROM `item`, `contact`
2300                         WHERE `item`.`uid` = %d
2301                         AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2302                         AND `item`.`starred` = 1
2303                         AND `contact`.`id` = `item`.`contact-id`
2304                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2305                         $sql_extra
2306                         AND `item`.`id`>%d
2307                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2308                         intval(api_user()),
2309                         intval($since_id),
2310                         intval($start),
2311                         intval($count)
2312                 );
2313
2314                 $ret = api_format_items($r, $user_info, false, $type);
2315         }
2316
2317         $data = array('status' => $ret);
2318         switch ($type) {
2319                 case "atom":
2320                 case "rss":
2321                         $data = api_rss_extra($a, $data, $user_info);
2322         }
2323
2324         return api_format_data("statuses", $type, $data);
2325 }
2326
2327 /// @TODO move to top of file or somwhere better
2328 api_register_func('api/favorites', 'api_favorites', true);
2329
2330 function api_format_messages($item, $recipient, $sender)
2331 {
2332         // standard meta information
2333         $ret = array(
2334                         'id'                    => $item['id'],
2335                         'sender_id'             => $sender['id'] ,
2336                         'text'                  => "",
2337                         'recipient_id'          => $recipient['id'],
2338                         'created_at'            => api_date($item['created']),
2339                         'sender_screen_name'    => $sender['screen_name'],
2340                         'recipient_screen_name' => $recipient['screen_name'],
2341                         'sender'                => $sender,
2342                         'recipient'             => $recipient,
2343                         'title'                 => "",
2344                         'friendica_seen'        => $item['seen'],
2345                         'friendica_parent_uri'  => $item['parent-uri'],
2346         );
2347
2348         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2349         unset($ret["sender"]["uid"]);
2350         unset($ret["sender"]["self"]);
2351         unset($ret["recipient"]["uid"]);
2352         unset($ret["recipient"]["self"]);
2353
2354         //don't send title to regular StatusNET requests to avoid confusing these apps
2355         if (x($_GET, 'getText')) {
2356                 $ret['title'] = $item['title'];
2357                 if ($_GET['getText'] == 'html') {
2358                         $ret['text'] = bbcode($item['body'], false, false);
2359                 } elseif ($_GET['getText'] == 'plain') {
2360                         //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2361                         $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2362                 }
2363         } else {
2364                 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2365         }
2366         if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2367                 unset($ret['sender']);
2368                 unset($ret['recipient']);
2369         }
2370
2371         return $ret;
2372 }
2373
2374 function api_convert_item($item)
2375 {
2376         $body = $item['body'];
2377         $attachments = api_get_attachments($body);
2378
2379         // Workaround for ostatus messages where the title is identically to the body
2380         $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2381         $statusbody = trim(html2plain($html, 0));
2382
2383         // handle data: images
2384         $statusbody = api_format_items_embeded_images($item, $statusbody);
2385
2386         $statustitle = trim($item['title']);
2387
2388         if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2389                 $statustext = trim($statusbody);
2390         } else {
2391                 $statustext = trim($statustitle."\n\n".$statusbody);
2392         }
2393
2394         if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2395                 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2396         }
2397
2398         $statushtml = trim(bbcode($body, false, false));
2399
2400         // Workaround for clients with limited HTML parser functionality
2401         $search = array("<br>", "<blockquote>", "</blockquote>",
2402                         "<h1>", "</h1>", "<h2>", "</h2>",
2403                         "<h3>", "</h3>", "<h4>", "</h4>",
2404                         "<h5>", "</h5>", "<h6>", "</h6>");
2405         $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2406                         "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2407                         "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2408                         "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2409         $statushtml = str_replace($search, $replace, $statushtml);
2410
2411         if ($item['title'] != "") {
2412                 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2413         }
2414
2415         do {
2416                 $oldtext = $statushtml;
2417                 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2418         } while ($oldtext != $statushtml);
2419
2420         if (substr($statushtml, 0, 4) == '<br>') {
2421                 $statushtml = substr($statushtml, 4);
2422         }
2423
2424         if (substr($statushtml, 0, -4) == '<br>') {
2425                 $statushtml = substr($statushtml, -4);
2426         }
2427
2428         // feeds without body should contain the link
2429         if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2430                 $statushtml .= bbcode($item['plink']);
2431         }
2432
2433         $entities = api_get_entitities($statustext, $body);
2434
2435         return array(
2436                 "text" => $statustext,
2437                 "html" => $statushtml,
2438                 "attachments" => $attachments,
2439                 "entities" => $entities
2440         );
2441 }
2442
2443 function api_get_attachments(&$body)
2444 {
2445         $text = $body;
2446         $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2447
2448         $URLSearchString = "^\[\]";
2449         $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2450
2451         if (!$ret) {
2452                 return false;
2453         }
2454
2455         $attachments = array();
2456
2457         foreach ($images[1] as $image) {
2458                 $imagedata = Image::getInfoFromURL($image);
2459
2460                 if ($imagedata) {
2461                         $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2462                 }
2463         }
2464
2465         if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2466                 foreach ($images[0] as $orig) {
2467                         $body = str_replace($orig, "", $body);
2468                 }
2469         }
2470
2471         return $attachments;
2472 }
2473
2474 function api_get_entitities(&$text, $bbcode)
2475 {
2476         /*
2477         To-Do:
2478         * Links at the first character of the post
2479         */
2480
2481         $a = get_app();
2482
2483         $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2484
2485         if ($include_entities != "true") {
2486                 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2487
2488                 foreach ($images[1] as $image) {
2489                         $replace = proxy_url($image);
2490                         $text = str_replace($image, $replace, $text);
2491                 }
2492                 return array();
2493         }
2494
2495         $bbcode = bb_CleanPictureLinks($bbcode);
2496
2497         // Change pure links in text to bbcode uris
2498         $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2499
2500         $entities = array();
2501         $entities["hashtags"] = array();
2502         $entities["symbols"] = array();
2503         $entities["urls"] = array();
2504         $entities["user_mentions"] = array();
2505
2506         $URLSearchString = "^\[\]";
2507
2508         $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2509
2510         $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2511         //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2512         $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2513
2514         $bbcode = preg_replace(
2515                 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2516                 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2517                 $bbcode
2518         );
2519         $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2520
2521         $bbcode = preg_replace(
2522                 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2523                 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2524                 $bbcode
2525         );
2526         $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2527
2528         $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2529
2530         //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2531         preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2532
2533         $ordered_urls = array();
2534         foreach ($urls[1] as $id => $url) {
2535                 //$start = strpos($text, $url, $offset);
2536                 $start = iconv_strpos($text, $url, 0, "UTF-8");
2537                 if (!($start === false)) {
2538                         $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2539                 }
2540         }
2541
2542         ksort($ordered_urls);
2543
2544         $offset = 0;
2545         //foreach ($urls[1] AS $id=>$url) {
2546         foreach ($ordered_urls as $url) {
2547                 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2548                         && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2549                 )
2550                         $display_url = $url["title"];
2551                 else {
2552                         $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2553                         $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2554
2555                         if (strlen($display_url) > 26)
2556                                 $display_url = substr($display_url, 0, 25)."…";
2557                 }
2558
2559                 //$start = strpos($text, $url, $offset);
2560                 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2561                 if (!($start === false)) {
2562                         $entities["urls"][] = array("url" => $url["url"],
2563                                                         "expanded_url" => $url["url"],
2564                                                         "display_url" => $display_url,
2565                                                         "indices" => array($start, $start+strlen($url["url"])));
2566                         $offset = $start + 1;
2567                 }
2568         }
2569
2570         preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2571         $ordered_images = array();
2572         foreach ($images[1] as $image) {
2573                 //$start = strpos($text, $url, $offset);
2574                 $start = iconv_strpos($text, $image, 0, "UTF-8");
2575                 if (!($start === false))
2576                         $ordered_images[$start] = $image;
2577         }
2578         //$entities["media"] = array();
2579         $offset = 0;
2580
2581         foreach ($ordered_images as $url) {
2582                 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2583                 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2584
2585                 if (strlen($display_url) > 26)
2586                         $display_url = substr($display_url, 0, 25)."…";
2587
2588                 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2589                 if (!($start === false)) {
2590                         $image = Image::getInfoFromURL($url);
2591                         if ($image) {
2592                                 // If image cache is activated, then use the following sizes:
2593                                 // thumb  (150), small (340), medium (600) and large (1024)
2594                                 if (!Config::get("system", "proxy_disabled")) {
2595                                         $media_url = proxy_url($url);
2596
2597                                         $sizes = array();
2598                                         $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2599                                         $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2600
2601                                         if (($image[0] > 150) || ($image[1] > 150)) {
2602                                                 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2603                                                 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2604                                         }
2605
2606                                         $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2607                                         $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2608
2609                                         if (($image[0] > 600) || ($image[1] > 600)) {
2610                                                 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2611                                                 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2612                                         }
2613                                 } else {
2614                                         $media_url = $url;
2615                                         $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2616                                 }
2617
2618                                 $entities["media"][] = array(
2619                                                         "id" => $start+1,
2620                                                         "id_str" => (string)$start+1,
2621                                                         "indices" => array($start, $start+strlen($url)),
2622                                                         "media_url" => normalise_link($media_url),
2623                                                         "media_url_https" => $media_url,
2624                                                         "url" => $url,
2625                                                         "display_url" => $display_url,
2626                                                         "expanded_url" => $url,
2627                                                         "type" => "photo",
2628                                                         "sizes" => $sizes);
2629                         }
2630                         $offset = $start + 1;
2631                 }
2632         }
2633
2634         return $entities;
2635 }
2636 function api_format_items_embeded_images(&$item, $text)
2637 {
2638         $text = preg_replace_callback(
2639                 "|data:image/([^;]+)[^=]+=*|m",
2640                 function ($match) use ($item) {
2641                         return System::baseUrl()."/display/".$item['guid'];
2642                 },
2643                 $text
2644         );
2645         return $text;
2646 }
2647
2648
2649 /**
2650  * @brief return <a href='url'>name</a> as array
2651  *
2652  * @param string $txt text
2653  * @return array
2654  *                      name => 'name'
2655  *                      'url => 'url'
2656  */
2657 function api_contactlink_to_array($txt)
2658 {
2659         $match = array();
2660         $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2661         if ($r && count($match)==3) {
2662                 $res = array(
2663                         'name' => $match[2],
2664                         'url' => $match[1]
2665                 );
2666         } else {
2667                 $res = array(
2668                         'name' => $text,
2669                         'url' => ""
2670                 );
2671         }
2672         return $res;
2673 }
2674
2675
2676 /**
2677  * @brief return likes, dislikes and attend status for item
2678  *
2679  * @param array $item array
2680  * @return array
2681  *                      likes => int count
2682  *                      dislikes => int count
2683  */
2684 function api_format_items_activities(&$item, $type = "json")
2685 {
2686         $a = get_app();
2687
2688         $activities = array(
2689                 'like' => array(),
2690                 'dislike' => array(),
2691                 'attendyes' => array(),
2692                 'attendno' => array(),
2693                 'attendmaybe' => array(),
2694         );
2695
2696         $items = q(
2697                 'SELECT * FROM item
2698                         WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2699                 intval($item['uid']),
2700                 dbesc($item['uri'])
2701         );
2702
2703         foreach ($items as $i) {
2704                 // not used as result should be structured like other user data
2705                 //builtin_activity_puller($i, $activities);
2706
2707                 // get user data and add it to the array of the activity
2708                 $user = api_get_user($a, $i['author-link']);
2709                 switch ($i['verb']) {
2710                         case ACTIVITY_LIKE:
2711                                 $activities['like'][] = $user;
2712                                 break;
2713                         case ACTIVITY_DISLIKE:
2714                                 $activities['dislike'][] = $user;
2715                                 break;
2716                         case ACTIVITY_ATTEND:
2717                                 $activities['attendyes'][] = $user;
2718                                 break;
2719                         case ACTIVITY_ATTENDNO:
2720                                 $activities['attendno'][] = $user;
2721                                 break;
2722                         case ACTIVITY_ATTENDMAYBE:
2723                                 $activities['attendmaybe'][] = $user;
2724                                 break;
2725                         default:
2726                                 break;
2727                 }
2728         }
2729
2730         if ($type == "xml") {
2731                 $xml_activities = array();
2732                 foreach ($activities as $k => $v) {
2733                         // change xml element from "like" to "friendica:like"
2734                         $xml_activities["friendica:".$k] = $v;
2735                         // add user data into xml output
2736                         $k_user = 0;
2737                         foreach ($v as $user)
2738                                 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2739                 }
2740                 $activities = $xml_activities;
2741         }
2742
2743         return $activities;
2744 }
2745
2746
2747 /**
2748  * @brief return data from profiles
2749  *
2750  * @param array  $profile array containing data from db table 'profile'
2751  * @param string $type    Known types are 'atom', 'rss', 'xml' and 'json'
2752  * @return array
2753  */
2754 function api_format_items_profiles(&$profile = null, $type = "json")
2755 {
2756         if ($profile != null) {
2757                 $profile = array('profile_id' => $profile['id'],
2758                                                 'profile_name' => $profile['profile-name'],
2759                                                 'is_default' => $profile['is-default'] ? true : false,
2760                                                 'hide_friends'=> $profile['hide-friends'] ? true : false,
2761                                                 'profile_photo' => $profile['photo'],
2762                                                 'profile_thumb' => $profile['thumb'],
2763                                                 'publish' => $profile['publish'] ? true : false,
2764                                                 'net_publish' => $profile['net-publish'] ? true : false,
2765                                                 'description' => $profile['pdesc'],
2766                                                 'date_of_birth' => $profile['dob'],
2767                                                 'address' => $profile['address'],
2768                                                 'city' => $profile['locality'],
2769                                                 'region' => $profile['region'],
2770                                                 'postal_code' => $profile['postal-code'],
2771                                                 'country' => $profile['country-name'],
2772                                                 'hometown' => $profile['hometown'],
2773                                                 'gender' => $profile['gender'],
2774                                                 'marital' => $profile['marital'],
2775                                                 'marital_with' => $profile['with'],
2776                                                 'marital_since' => $profile['howlong'],
2777                                                 'sexual' => $profile['sexual'],
2778                                                 'politic' => $profile['politic'],
2779                                                 'religion' => $profile['religion'],
2780                                                 'public_keywords' => $profile['pub_keywords'],
2781                                                 'private_keywords' => $profile['prv_keywords'],
2782                                                 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2783                                                 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2784                                                 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2785                                                 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2786                                                 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2787                                                 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2788                                                 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2789                                                 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2790                                                 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2791                                                 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2792                                                 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2793                                                 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2794                                                 'homepage' => $profile['homepage'],
2795                                                 'users' => null);
2796                 return $profile;
2797         }
2798 }
2799
2800 /**
2801  * @brief format items to be returned by api
2802  *
2803  * @param array $r array of items
2804  * @param array $user_info
2805  * @param bool $filter_user filter items by $user_info
2806  */
2807 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2808 {
2809         $a = get_app();
2810
2811         $ret = array();
2812
2813         foreach ($r as $item) {
2814                 localize_item($item);
2815                 list($status_user, $owner_user) = api_item_get_user($a, $item);
2816
2817                 // Look if the posts are matching if they should be filtered by user id
2818                 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2819                         continue;
2820                 }
2821
2822                 $in_reply_to = api_in_reply_to($item);
2823
2824                 $converted = api_convert_item($item);
2825
2826                 if ($type == "xml") {
2827                         $geo = "georss:point";
2828                 } else {
2829                         $geo = "geo";
2830                 }
2831
2832                 $status = array(
2833                         'text'          => $converted["text"],
2834                         'truncated' => false,
2835                         'created_at'=> api_date($item['created']),
2836                         'in_reply_to_status_id' => $in_reply_to['status_id'],
2837                         'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2838                         'source'    => (($item['app']) ? $item['app'] : 'web'),
2839                         'id'            => intval($item['id']),
2840                         'id_str'        => (string) intval($item['id']),
2841                         'in_reply_to_user_id' => $in_reply_to['user_id'],
2842                         'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2843                         'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2844                         $geo => null,
2845                         'favorited' => $item['starred'] ? true : false,
2846                         'user' =>  $status_user ,
2847                         'friendica_owner' => $owner_user,
2848                         //'entities' => NULL,
2849                         'statusnet_html' => $converted["html"],
2850                         'statusnet_conversation_id' => $item['parent'],
2851                         'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2852                         'friendica_activities' => api_format_items_activities($item, $type),
2853                 );
2854
2855                 if (count($converted["attachments"]) > 0) {
2856                         $status["attachments"] = $converted["attachments"];
2857                 }
2858
2859                 if (count($converted["entities"]) > 0) {
2860                         $status["entities"] = $converted["entities"];
2861                 }
2862
2863                 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
2864                         $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2865                 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2866                         $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2867                 }
2868
2869
2870                 // Retweets are only valid for top postings
2871                 // It doesn't work reliable with the link if its a feed
2872                 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2873                 //if ($IsRetweet)
2874                 //      $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
2875
2876
2877                 if ($item["id"] == $item["parent"]) {
2878                         $retweeted_item = api_share_as_retweet($item);
2879                         if ($retweeted_item !== false) {
2880                                 $retweeted_status = $status;
2881                                 try {
2882                                         $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
2883                                 } catch (BadRequestException $e) {
2884                                         // user not found. should be found?
2885                                         /// @todo check if the user should be always found
2886                                         $retweeted_status["user"] = array();
2887                                 }
2888
2889                                 $rt_converted = api_convert_item($retweeted_item);
2890
2891                                 $retweeted_status['text'] = $rt_converted["text"];
2892                                 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2893                                 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2894                                 $retweeted_status['created_at'] =  api_date($retweeted_item['created']);
2895                                 $status['retweeted_status'] = $retweeted_status;
2896                         }
2897                 }
2898
2899                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2900                 unset($status["user"]["uid"]);
2901                 unset($status["user"]["self"]);
2902
2903                 if ($item["coord"] != "") {
2904                         $coords = explode(' ', $item["coord"]);
2905                         if (count($coords) == 2) {
2906                                 if ($type == "json")
2907                                         $status["geo"] = array('type' => 'Point',
2908                                                         'coordinates' => array((float) $coords[0],
2909                                                                                 (float) $coords[1]));
2910                                 else // Not sure if this is the official format - if someone founds a documentation we can check
2911                                         $status["georss:point"] = $item["coord"];
2912                         }
2913                 }
2914                 $ret[] = $status;
2915         };
2916         return $ret;
2917 }
2918
2919 function api_account_rate_limit_status($type)
2920 {
2921         if ($type == "xml") {
2922                 $hash = array(
2923                                 'remaining-hits' => '150',
2924                                 '@attributes' => array("type" => "integer"),
2925                                 'hourly-limit' => '150',
2926                                 '@attributes2' => array("type" => "integer"),
2927                                 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
2928                                 '@attributes3' => array("type" => "datetime"),
2929                                 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2930                                 '@attributes4' => array("type" => "integer"),
2931                         );
2932         } else {
2933                 $hash = array(
2934                                 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2935                                 'remaining_hits' => '150',
2936                                 'hourly_limit' => '150',
2937                                 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
2938                         );
2939         }
2940
2941         return api_format_data('hash', $type, array('hash' => $hash));
2942 }
2943
2944 /// @TODO move to top of file or somwhere better
2945 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
2946
2947 function api_help_test($type)
2948 {
2949         if ($type == 'xml') {
2950                 $ok = "true";
2951         } else {
2952                 $ok = "ok";
2953         }
2954
2955         return api_format_data('ok', $type, array("ok" => $ok));
2956 }
2957
2958 /// @TODO move to top of file or somwhere better
2959 api_register_func('api/help/test', 'api_help_test', false);
2960
2961 function api_lists($type)
2962 {
2963         $ret = array();
2964         /// @TODO $ret is not filled here?
2965         return api_format_data('lists', $type, array("lists_list" => $ret));
2966 }
2967
2968 /// @TODO move to top of file or somwhere better
2969 api_register_func('api/lists', 'api_lists', true);
2970
2971 function api_lists_list($type)
2972 {
2973         $ret = array();
2974         /// @TODO $ret is not filled here?
2975         return api_format_data('lists', $type, array("lists_list" => $ret));
2976 }
2977
2978 /// @TODO move to top of file or somwhere better
2979 api_register_func('api/lists/list', 'api_lists_list', true);
2980
2981 /**
2982  * @brief Returns either the friends of the follower list
2983  *
2984  * Note: Considers friends and followers lists to be private and won't return
2985  * anything if any user_id parameter is passed.
2986  *
2987  * @param string $qtype Either "friends" or "followers"
2988  * @return boolean|array
2989  * @throws ForbiddenException
2990  */
2991 function api_statuses_f($qtype)
2992 {
2993         $a = get_app();
2994
2995         if (api_user() === false) {
2996                 throw new ForbiddenException();
2997         }
2998
2999         // pagination
3000         $count = x($_GET, 'count') ? $_GET['count'] : 20;
3001         $page = x($_GET, 'page') ? $_GET['page'] : 1;
3002         if ($page < 1) {
3003                 $page = 1;
3004         }
3005         $start = ($page - 1) * $count;
3006
3007         $user_info = api_get_user($a);
3008
3009         if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3010                 /* this is to stop Hotot to load friends multiple times
3011                 *  I'm not sure if I'm missing return something or
3012                 *  is a bug in hotot. Workaround, meantime
3013                 */
3014
3015                 /*$ret=Array();
3016                 return array('$users' => $ret);*/
3017                 return false;
3018         }
3019
3020         if ($qtype == 'friends') {
3021                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3022         }
3023         if ($qtype == 'followers') {
3024                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3025         }
3026
3027         // friends and followers only for self
3028         if ($user_info['self'] == 0) {
3029                 $sql_extra = " AND false ";
3030         }
3031
3032         $r = q(
3033                 "SELECT `nurl`
3034                 FROM `contact`
3035                 WHERE `uid` = %d
3036                 AND NOT `self`
3037                 AND (NOT `blocked` OR `pending`)
3038                 $sql_extra
3039                 ORDER BY `nick`
3040                 LIMIT %d, %d",
3041                 intval(api_user()),
3042                 intval($start),
3043                 intval($count)
3044         );
3045
3046         $ret = array();
3047         foreach ($r as $cid) {
3048                 $user = api_get_user($a, $cid['nurl']);
3049                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3050                 unset($user["uid"]);
3051                 unset($user["self"]);
3052
3053                 if ($user) {
3054                         $ret[] = $user;
3055                 }
3056         }
3057
3058         return array('user' => $ret);
3059 }
3060
3061
3062 /**
3063  * @brief Returns the list of friends of the provided user
3064  *
3065  * @deprecated By Twitter API in favor of friends/list
3066  *
3067  * @param string $type Either "json" or "xml"
3068  * @return boolean|string|array
3069  */
3070 function api_statuses_friends($type)
3071 {
3072         $data =  api_statuses_f("friends");
3073         if ($data === false) {
3074                 return false;
3075         }
3076         return api_format_data("users", $type, $data);
3077 }
3078
3079 /**
3080  * @brief Returns the list of friends of the provided user
3081  *
3082  * @deprecated By Twitter API in favor of friends/list
3083  *
3084  * @param string $type Either "json" or "xml"
3085  * @return boolean|string|array
3086  */
3087 function api_statuses_followers($type)
3088 {
3089         $data = api_statuses_f("followers");
3090         if ($data === false) {
3091                 return false;
3092         }
3093         return api_format_data("users", $type, $data);
3094 }
3095
3096 /// @TODO move to top of file or somewhere better
3097 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3098 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3099
3100 function api_statusnet_config($type)
3101 {
3102         $a = get_app();
3103
3104         $name = $a->config['sitename'];
3105         $server = $a->get_hostname();
3106         $logo = System::baseUrl() . '/images/friendica-64.png';
3107         $email = $a->config['admin_email'];
3108         $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3109         $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3110         $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3111         if ($a->config['api_import_size']) {
3112                 $texlimit = string($a->config['api_import_size']);
3113         }
3114         $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3115         $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3116
3117         $config = array(
3118                 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3119                         'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3120                         'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3121                         'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3122                         'shorturllength' => '30',
3123                         'friendica' => array(
3124                                         'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3125                                         'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3126                                         'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3127                                         'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3128                                         )
3129                 ),
3130         );
3131
3132         return api_format_data('config', $type, array('config' => $config));
3133 }
3134
3135 /// @TODO move to top of file or somewhere better
3136 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3137 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3138
3139 function api_statusnet_version($type)
3140 {
3141         // liar
3142         $fake_statusnet_version = "0.9.7";
3143
3144         return api_format_data('version', $type, array('version' => $fake_statusnet_version));
3145 }
3146
3147 /// @TODO move to top of file or somewhere better
3148 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3149 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3150
3151 /**
3152  * @todo use api_format_data() to return data
3153  */
3154 function api_ff_ids($type,$qtype)
3155 {
3156         $a = get_app();
3157
3158         if (! api_user()) {
3159                 throw new ForbiddenException();
3160         }
3161
3162         $user_info = api_get_user($a);
3163
3164         if ($qtype == 'friends') {
3165                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3166         }
3167         if ($qtype == 'followers') {
3168                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3169         }
3170
3171         if (!$user_info["self"]) {
3172                 $sql_extra = " AND false ";
3173         }
3174
3175         $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3176
3177         $r = q(
3178                 "SELECT `pcontact`.`id` FROM `contact`
3179                         INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3180                         WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3181                 intval(api_user())
3182         );
3183
3184         if (!DBM::is_result($r)) {
3185                 return;
3186         }
3187
3188         $ids = array();
3189         foreach ($r as $rr) {
3190                 if ($stringify_ids) {
3191                         $ids[] = $rr['id'];
3192                 } else {
3193                         $ids[] = intval($rr['id']);
3194                 }
3195         }
3196
3197         return api_format_data("ids", $type, array('id' => $ids));
3198 }
3199
3200 function api_friends_ids($type)
3201 {
3202         return api_ff_ids($type, 'friends');
3203 }
3204
3205 function api_followers_ids($type)
3206 {
3207         return api_ff_ids($type, 'followers');
3208 }
3209
3210 /// @TODO move to top of file or somewhere better
3211 api_register_func('api/friends/ids', 'api_friends_ids', true);
3212 api_register_func('api/followers/ids', 'api_followers_ids', true);
3213
3214 function api_direct_messages_new($type)
3215 {
3216
3217         $a = get_app();
3218
3219         if (api_user() === false) throw new ForbiddenException();
3220
3221         if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) return;
3222
3223         $sender = api_get_user($a);
3224
3225         if ($_POST['screen_name']) {
3226                 $r = q(
3227                         "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3228                         intval(api_user()),
3229                         dbesc($_POST['screen_name'])
3230                 );
3231
3232                 // Selecting the id by priority, friendica first
3233                 api_best_nickname($r);
3234
3235                 $recipient = api_get_user($a, $r[0]['nurl']);
3236         } else {
3237                 $recipient = api_get_user($a, $_POST['user_id']);
3238         }
3239
3240         $replyto = '';
3241         $sub     = '';
3242         if (x($_REQUEST, 'replyto')) {
3243                 $r = q(
3244                         'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3245                         intval(api_user()),
3246                         intval($_REQUEST['replyto'])
3247                 );
3248                 $replyto = $r[0]['parent-uri'];
3249                 $sub     = $r[0]['title'];
3250         } else {
3251                 if (x($_REQUEST, 'title')) {
3252                         $sub = $_REQUEST['title'];
3253                 } else {
3254                         $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3255                 }
3256         }
3257
3258         $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3259
3260         if ($id > -1) {
3261                 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3262                 $ret = api_format_messages($r[0], $recipient, $sender);
3263         } else {
3264                 $ret = array("error"=>$id);
3265         }
3266
3267         $data = array('direct_message'=>$ret);
3268
3269         switch ($type) {
3270                 case "atom":
3271                 case "rss":
3272                         $data = api_rss_extra($a, $data, $user_info);
3273         }
3274
3275         return api_format_data("direct-messages", $type, $data);
3276
3277 }
3278
3279 /// @TODO move to top of file or somewhere better
3280 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3281
3282 /**
3283  * @brief delete a direct_message from mail table through api
3284  *
3285  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3286  * @return string
3287  */
3288 function api_direct_messages_destroy($type)
3289 {
3290         $a = get_app();
3291
3292         if (api_user() === false) {
3293                 throw new ForbiddenException();
3294         }
3295
3296         // params
3297         $user_info = api_get_user($a);
3298         //required
3299         $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3300         // optional
3301         $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3302         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3303         /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3304
3305         $uid = $user_info['uid'];
3306         // error if no id or parenturi specified (for clients posting parent-uri as well)
3307         if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3308                 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3309                 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3310         }
3311
3312         // BadRequestException if no id specified (for clients using Twitter API)
3313         if ($id == 0) {
3314                 throw new BadRequestException('Message id not specified');
3315         }
3316
3317         // add parent-uri to sql command if specified by calling app
3318         $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3319
3320         // get data of the specified message id
3321         $r = q(
3322                 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3323                 intval($uid),
3324                 intval($id)
3325         );
3326
3327         // error message if specified id is not in database
3328         if (!DBM::is_result($r)) {
3329                 if ($verbose == "true") {
3330                         $answer = array('result' => 'error', 'message' => 'message id not in database');
3331                         return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3332                 }
3333                 /// @todo BadRequestException ok for Twitter API clients?
3334                 throw new BadRequestException('message id not in database');
3335         }
3336
3337         // delete message
3338         $result = q(
3339                 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3340                 intval($uid),
3341                 intval($id)
3342         );
3343
3344         if ($verbose == "true") {
3345                 if ($result) {
3346                         // return success
3347                         $answer = array('result' => 'ok', 'message' => 'message deleted');
3348                         return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3349                 } else {
3350                         $answer = array('result' => 'error', 'message' => 'unknown error');
3351                         return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3352                 }
3353         }
3354         /// @todo return JSON data like Twitter API not yet implemented
3355
3356 }
3357
3358 /// @TODO move to top of file or somewhere better
3359 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3360
3361 function api_direct_messages_box($type, $box, $verbose)
3362 {
3363         $a = get_app();
3364
3365         if (api_user() === false) {
3366                 throw new ForbiddenException();
3367         }
3368
3369         // params
3370         $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3371         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3372         if ($page < 0) {
3373                 $page = 0;
3374         }
3375
3376         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3377         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3378
3379         $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3380         $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3381
3382         //  caller user info
3383         unset($_REQUEST["user_id"]);
3384         unset($_GET["user_id"]);
3385
3386         unset($_REQUEST["screen_name"]);
3387         unset($_GET["screen_name"]);
3388
3389         $user_info = api_get_user($a);
3390         $profile_url = $user_info["url"];
3391
3392         // pagination
3393         $start = $page * $count;
3394
3395         // filters
3396         if ($box=="sentbox") {
3397                 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3398         } elseif ($box == "conversation") {
3399                 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"])  . "'";
3400         } elseif ($box == "all") {
3401                 $sql_extra = "true";
3402         } elseif ($box == "inbox") {
3403                 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3404         }
3405
3406         if ($max_id > 0) {
3407                 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3408         }
3409
3410         if ($user_id != "") {
3411                 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3412         } elseif ($screen_name !="") {
3413                 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3414         }
3415
3416         $r = q(
3417                 "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",
3418                 intval(api_user()),
3419                 intval($since_id),
3420                 intval($start),
3421                 intval($count)
3422         );
3423         if ($verbose == "true" && !DBM::is_result($r)) {
3424                 $answer = array('result' => 'error', 'message' => 'no mails available');
3425                 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3426         }
3427
3428         $ret = array();
3429         foreach ($r as $item) {
3430                 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3431                         $recipient = $user_info;
3432                         $sender = api_get_user($a, normalise_link($item['contact-url']));
3433                 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3434                         $recipient = api_get_user($a, normalise_link($item['contact-url']));
3435                         $sender = $user_info;
3436                 }
3437
3438                 $ret[] = api_format_messages($item, $recipient, $sender);
3439         }
3440
3441
3442         $data = array('direct_message' => $ret);
3443         switch ($type) {
3444                 case "atom":
3445                 case "rss":
3446                         $data = api_rss_extra($a, $data, $user_info);
3447         }
3448
3449         return api_format_data("direct-messages", $type, $data);
3450 }
3451
3452 function api_direct_messages_sentbox($type)
3453 {
3454         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3455         return api_direct_messages_box($type, "sentbox", $verbose);
3456 }
3457
3458 function api_direct_messages_inbox($type)
3459 {
3460         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3461         return api_direct_messages_box($type, "inbox", $verbose);
3462 }
3463
3464 function api_direct_messages_all($type)
3465 {
3466         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3467         return api_direct_messages_box($type, "all", $verbose);
3468 }
3469
3470 function api_direct_messages_conversation($type)
3471 {
3472         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3473         return api_direct_messages_box($type, "conversation", $verbose);
3474 }
3475
3476 /// @TODO move to top of file or somewhere better
3477 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3478 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3479 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3480 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3481
3482 function api_oauth_request_token($type)
3483 {
3484         $oauth1 = new FKOAuth1();
3485         try {
3486                 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3487         } catch (Exception $e) {
3488                 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3489                 killme();
3490         }
3491         echo $r;
3492         killme();
3493 }
3494
3495 function api_oauth_access_token($type)
3496 {
3497         $oauth1 = new FKOAuth1();
3498         try {
3499                 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3500         } catch (Exception $e) {
3501                 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3502                 killme();
3503         }
3504         echo $r;
3505         killme();
3506 }
3507
3508 /// @TODO move to top of file or somewhere better
3509 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3510 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3511
3512
3513 /**
3514  * @brief delete a complete photoalbum with all containing photos from database through api
3515  *
3516  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3517  * @return string
3518  */
3519 function api_fr_photoalbum_delete($type)
3520 {
3521         if (api_user() === false) {
3522                 throw new ForbiddenException();
3523         }
3524         // input params
3525         $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3526
3527         // we do not allow calls without album string
3528         if ($album == "") {
3529                 throw new BadRequestException("no albumname specified");
3530         }
3531         // check if album is existing
3532         $r = q(
3533                 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3534                 intval(api_user()),
3535                 dbesc($album)
3536         );
3537         if (!DBM::is_result($r))
3538                 throw new BadRequestException("album not available");
3539
3540         // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3541         // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3542         foreach ($r as $rr) {
3543                 $photo_item = q(
3544                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3545                         intval(local_user()),
3546                         dbesc($rr['resource-id'])
3547                 );
3548
3549                 if (!DBM::is_result($photo_item)) {
3550                         throw new InternalServerErrorException("problem with deleting items occured");
3551                 }
3552                 drop_item($photo_item[0]['id'], false);
3553         }
3554
3555         // now let's delete all photos from the album
3556         $result = dba::delete('photo', array('uid' => api_user(), 'album' => $album));
3557
3558         // return success of deletion or error message
3559         if ($result) {
3560                 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3561                 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3562         } else {
3563                 throw new InternalServerErrorException("unknown error - deleting from database failed");
3564         }
3565 }
3566
3567 /**
3568  * @brief update the name of the album for all photos of an album
3569  *
3570  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3571  * @return string
3572  */
3573 function api_fr_photoalbum_update($type)
3574 {
3575         if (api_user() === false) {
3576                 throw new ForbiddenException();
3577         }
3578         // input params
3579         $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3580         $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3581
3582         // we do not allow calls without album string
3583         if ($album == "") {
3584                 throw new BadRequestException("no albumname specified");
3585         }
3586         if ($album_new == "") {
3587                 throw new BadRequestException("no new albumname specified");
3588         }
3589         // check if album is existing
3590         $r = q(
3591                 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3592                 intval(api_user()),
3593                 dbesc($album)
3594         );
3595         if (!DBM::is_result($r)) {
3596                 throw new BadRequestException("album not available");
3597         }
3598         // now let's update all photos to the albumname
3599         $result = q(
3600                 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3601                 dbesc($album_new),
3602                 intval(api_user()),
3603                 dbesc($album)
3604         );
3605
3606         // return success of updating or error message
3607         if ($result) {
3608                 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3609                 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3610         } else {
3611                 throw new InternalServerErrorException("unknown error - updating in database failed");
3612         }
3613 }
3614
3615
3616 /**
3617  * @brief list all photos of the authenticated user
3618  *
3619  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3620  * @return string
3621  */
3622 function api_fr_photos_list($type)
3623 {
3624         if (api_user() === false) {
3625                 throw new ForbiddenException();
3626         }
3627         $r = q(
3628                 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3629                 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3630                 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3631                 intval(local_user())
3632         );
3633         $typetoext = array(
3634                 'image/jpeg' => 'jpg',
3635                 'image/png' => 'png',
3636                 'image/gif' => 'gif'
3637         );
3638         $data = array('photo'=>array());
3639         if (DBM::is_result($r)) {
3640                 foreach ($r as $rr) {
3641                         $photo = array();
3642                         $photo['id'] = $rr['resource-id'];
3643                         $photo['album'] = $rr['album'];
3644                         $photo['filename'] = $rr['filename'];
3645                         $photo['type'] = $rr['type'];
3646                         $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3647                         $photo['created'] = $rr['created'];
3648                         $photo['edited'] = $rr['edited'];
3649                         $photo['desc'] = $rr['desc'];
3650
3651                         if ($type == "xml") {
3652                                 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3653                         } else {
3654                                 $photo['thumb'] = $thumb;
3655                                 $data['photo'][] = $photo;
3656                         }
3657                 }
3658         }
3659         return api_format_data("photos", $type, $data);
3660 }
3661
3662 /**
3663  * @brief upload a new photo or change an existing photo
3664  *
3665  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3666  * @return string
3667  */
3668 function api_fr_photo_create_update($type)
3669 {
3670         if (api_user() === false) {
3671                 throw new ForbiddenException();
3672         }
3673         // input params
3674         $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3675         $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3676         $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3677         $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3678         $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3679         $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3680         $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3681         $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3682         $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3683
3684         // do several checks on input parameters
3685         // we do not allow calls without album string
3686         if ($album == null) {
3687                 throw new BadRequestException("no albumname specified");
3688         }
3689         // if photo_id == null --> we are uploading a new photo
3690         if ($photo_id == null) {
3691                 $mode = "create";
3692
3693                 // error if no media posted in create-mode
3694                 if (!x($_FILES, 'media')) {
3695                         // Output error
3696                         throw new BadRequestException("no media data submitted");
3697                 }
3698
3699                 // album_new will be ignored in create-mode
3700                 $album_new = "";
3701         } else {
3702                 $mode = "update";
3703
3704                 // check if photo is existing in database
3705                 $r = q(
3706                         "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3707                         intval(api_user()),
3708                         dbesc($photo_id),
3709                         dbesc($album)
3710                 );
3711                 if (!DBM::is_result($r)) {
3712                         throw new BadRequestException("photo not available");
3713                 }
3714         }
3715
3716         // checks on acl strings provided by clients
3717         $acl_input_error = false;
3718         $acl_input_error |= check_acl_input($allow_cid);
3719         $acl_input_error |= check_acl_input($deny_cid);
3720         $acl_input_error |= check_acl_input($allow_gid);
3721         $acl_input_error |= check_acl_input($deny_gid);
3722         if ($acl_input_error) {
3723                 throw new BadRequestException("acl data invalid");
3724         }
3725         // now let's upload the new media in create-mode
3726         if ($mode == "create") {
3727                 $media = $_FILES['media'];
3728                 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3729
3730                 // return success of updating or error message
3731                 if (!is_null($data)) {
3732                         return api_format_data("photo_create", $type, $data);
3733                 } else {
3734                         throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3735                 }
3736         }
3737
3738         // now let's do the changes in update-mode
3739         if ($mode == "update") {
3740                 $sql_extra = "";
3741
3742                 if (!is_null($desc)) {
3743                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3744                 }
3745
3746                 if (!is_null($album_new)) {
3747                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3748                 }
3749
3750                 if (!is_null($allow_cid)) {
3751                         $allow_cid = trim($allow_cid);
3752                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3753                 }
3754
3755                 if (!is_null($deny_cid)) {
3756                         $deny_cid = trim($deny_cid);
3757                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3758                 }
3759
3760                 if (!is_null($allow_gid)) {
3761                         $allow_gid = trim($allow_gid);
3762                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3763                 }
3764
3765                 if (!is_null($deny_gid)) {
3766                         $deny_gid = trim($deny_gid);
3767                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3768                 }
3769
3770                 $result = false;
3771                 if ($sql_extra != "") {
3772                         $nothingtodo = false;
3773                         $result = q(
3774                                 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3775                                 $sql_extra,
3776                                 datetime_convert(),   // update edited timestamp
3777                                 intval(api_user()),
3778                                 dbesc($photo_id),
3779                                 dbesc($album)
3780                         );
3781                 } else {
3782                         $nothingtodo = true;
3783                 }
3784
3785                 if (x($_FILES, 'media')) {
3786                         $nothingtodo = false;
3787                         $media = $_FILES['media'];
3788                         $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3789                         if (!is_null($data)) {
3790                                 return api_format_data("photo_update", $type, $data);
3791                         }
3792                 }
3793
3794                 // return success of updating or error message
3795                 if ($result) {
3796                         $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
3797                         return api_format_data("photo_update", $type, array('$result' => $answer));
3798                 } else {
3799                         if ($nothingtodo) {
3800                                 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
3801                                 return api_format_data("photo_update", $type, array('$result' => $answer));
3802                         }
3803                         throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3804                 }
3805         }
3806         throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3807 }
3808
3809
3810 /**
3811  * @brief delete a single photo from the database through api
3812  *
3813  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3814  * @return string
3815  */
3816 function api_fr_photo_delete($type)
3817 {
3818         if (api_user() === false) {
3819                 throw new ForbiddenException();
3820         }
3821         // input params
3822         $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3823
3824         // do several checks on input parameters
3825         // we do not allow calls without photo id
3826         if ($photo_id == null) {
3827                 throw new BadRequestException("no photo_id specified");
3828         }
3829         // check if photo is existing in database
3830         $r = q(
3831                 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3832                 intval(api_user()),
3833                 dbesc($photo_id)
3834         );
3835         if (!DBM::is_result($r)) {
3836                 throw new BadRequestException("photo not available");
3837         }
3838         // now we can perform on the deletion of the photo
3839         $result = dba::delete('photo', array('uid' => api_user(), 'resource-id' => $photo_id));
3840
3841         // return success of deletion or error message
3842         if ($result) {
3843                 // retrieve the id of the parent element (the photo element)
3844                 $photo_item = q(
3845                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3846                         intval(local_user()),
3847                         dbesc($photo_id)
3848                 );
3849
3850                 if (!DBM::is_result($photo_item)) {
3851                         throw new InternalServerErrorException("problem with deleting items occured");
3852                 }
3853                 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3854                 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
3855                 drop_item($photo_item[0]['id'], false);
3856
3857                 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
3858                 return api_format_data("photo_delete", $type, array('$result' => $answer));
3859         } else {
3860                 throw new InternalServerErrorException("unknown error on deleting photo from database table");
3861         }
3862 }
3863
3864
3865 /**
3866  * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3867  *
3868  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3869  * @return string
3870  */
3871 function api_fr_photo_detail($type)
3872 {
3873         if (api_user() === false) {
3874                 throw new ForbiddenException();
3875         }
3876         if (!x($_REQUEST, 'photo_id')) {
3877                 throw new BadRequestException("No photo id.");
3878         }
3879
3880         $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3881         $photo_id = $_REQUEST['photo_id'];
3882
3883         // prepare json/xml output with data from database for the requested photo
3884         $data = prepare_photo_data($type, $scale, $photo_id);
3885
3886         return api_format_data("photo_detail", $type, $data);
3887 }
3888
3889
3890 /**
3891  * @brief updates the profile image for the user (either a specified profile or the default profile)
3892  *
3893  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3894  * @return string
3895  */
3896 function api_account_update_profile_image($type)
3897 {
3898         if (api_user() === false) {
3899                 throw new ForbiddenException();
3900         }
3901         // input params
3902         $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
3903
3904         // error if image data is missing
3905         if (!x($_FILES, 'image')) {
3906                 throw new BadRequestException("no media data submitted");
3907         }
3908
3909         // check if specified profile id is valid
3910         if ($profileid != 0) {
3911                 $r = q(
3912                         "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
3913                         intval(api_user()),
3914                         intval($profileid)
3915                 );
3916                 // error message if specified profile id is not in database
3917                 if (!DBM::is_result($r)) {
3918                         throw new BadRequestException("profile_id not available");
3919                 }
3920                 $is_default_profile = $r['profile'];
3921         } else {
3922                 $is_default_profile = 1;
3923         }
3924
3925         // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3926         $media = null;
3927         if (x($_FILES, 'image')) {
3928                 $media = $_FILES['image'];
3929         } elseif (x($_FILES, 'media')) {
3930                 $media = $_FILES['media'];
3931         }
3932         // save new profile image
3933         $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
3934
3935         // get filetype
3936         if (is_array($media['type'])) {
3937                 $filetype = $media['type'][0];
3938         } else {
3939                 $filetype = $media['type'];
3940         }
3941         if ($filetype == "image/jpeg") {
3942                 $fileext = "jpg";
3943         } elseif ($filetype == "image/png") {
3944                 $fileext = "png";
3945         }
3946         // change specified profile or all profiles to the new resource-id
3947         if ($is_default_profile) {
3948                 $r = q(
3949                         "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
3950                         dbesc($data['photo']['id']),
3951                         intval(local_user())
3952                 );
3953
3954                 $r = q(
3955                         "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s'  WHERE `self` AND `uid` = %d",
3956                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
3957                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
3958                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
3959                         intval(local_user())
3960                 );
3961         } else {
3962                 $r = q(
3963                         "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
3964                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
3965                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
3966                         intval($_REQUEST['profile']),
3967                         intval(local_user())
3968                 );
3969         }
3970
3971         // we'll set the updated profile-photo timestamp even if it isn't the default profile,
3972         // so that browsers will do a cache update unconditionally
3973
3974         $r = q(
3975                 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
3976                 dbesc(datetime_convert()),
3977                 intval(local_user())
3978         );
3979
3980         // Update global directory in background
3981         //$user = api_get_user(get_app());
3982         $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
3983         if ($url && strlen(Config::get('system', 'directory'))) {
3984                 Worker::add(PRIORITY_LOW, "Directory", $url);
3985         }
3986
3987         Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
3988
3989         // output for client
3990         if ($data) {
3991                 return api_account_verify_credentials($type);
3992         } else {
3993                 // SaveMediaToDatabase failed for some reason
3994                 throw new InternalServerErrorException("image upload failed");
3995         }
3996 }
3997
3998 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3999 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4000 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4001 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4002 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4003 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4004 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4005 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4006 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4007
4008
4009 function check_acl_input($acl_string)
4010 {
4011         if ($acl_string == null || $acl_string == " ") {
4012                 return false;
4013         }
4014         $contact_not_found = false;
4015
4016         // split <x><y><z> into array of cid's
4017         preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4018
4019         // check for each cid if it is available on server
4020         $cid_array = $array[0];
4021         foreach ($cid_array as $cid) {
4022                 $cid = str_replace("<", "", $cid);
4023                 $cid = str_replace(">", "", $cid);
4024                 $contact = q(
4025                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4026                         intval($cid),
4027                         intval(api_user())
4028                 );
4029                 $contact_not_found |= !DBM::is_result($contact);
4030         }
4031         return $contact_not_found;
4032 }
4033
4034 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)
4035 {
4036         $visitor   = 0;
4037         $src = "";
4038         $filetype = "";
4039         $filename = "";
4040         $filesize = 0;
4041
4042         if (is_array($media)) {
4043                 if (is_array($media['tmp_name'])) {
4044                         $src = $media['tmp_name'][0];
4045                 } else {
4046                         $src = $media['tmp_name'];
4047                 }
4048                 if (is_array($media['name'])) {
4049                         $filename = basename($media['name'][0]);
4050                 } else {
4051                         $filename = basename($media['name']);
4052                 }
4053                 if (is_array($media['size'])) {
4054                         $filesize = intval($media['size'][0]);
4055                 } else {
4056                         $filesize = intval($media['size']);
4057                 }
4058                 if (is_array($media['type'])) {
4059                         $filetype = $media['type'][0];
4060                 } else {
4061                         $filetype = $media['type'];
4062                 }
4063         }
4064
4065         if ($filetype == "") {
4066                 $filetype=Image::guessType($filename);
4067         }
4068         $imagedata = getimagesize($src);
4069         if ($imagedata) {
4070                 $filetype = $imagedata['mime'];
4071         }
4072         logger(
4073                 "File upload src: " . $src . " - filename: " . $filename .
4074                 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG
4075         );
4076
4077         // check if there was a php upload error
4078         if ($filesize == 0 && $media['error'] == 1) {
4079                 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4080         }
4081         // check against max upload size within Friendica instance
4082         $maximagesize = Config::get('system', 'maximagesize');
4083         if (($maximagesize) && ($filesize > $maximagesize)) {
4084                 $formattedBytes = formatBytes($maximagesize);
4085                 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4086         }
4087
4088         // create Photo instance with the data of the image
4089         $imagedata = @file_get_contents($src);
4090         $Image = new Image($imagedata, $filetype);
4091         if (! $Image->isValid()) {
4092                 throw new InternalServerErrorException("unable to process image data");
4093         }
4094
4095         // check orientation of image
4096         $Image->orient($src);
4097         @unlink($src);
4098
4099         // check max length of images on server
4100         $max_length = Config::get('system', 'max_image_length');
4101         if (! $max_length) {
4102                 $max_length = MAX_IMAGE_LENGTH;
4103         }
4104         if ($max_length > 0) {
4105                 $Image->scaleDown($max_length);
4106                 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4107         }
4108         $width = $Image->getWidth();
4109         $height = $Image->getHeight();
4110
4111         // create a new resource-id if not already provided
4112         $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
4113
4114         if ($mediatype == "photo") {
4115                 // upload normal image (scales 0, 1, 2)
4116                 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4117
4118                 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4119                 if (! $r) {
4120                         logger("photo upload: image upload with scale 0 (original size) failed");
4121                 }
4122                 if ($width > 640 || $height > 640) {
4123                         $Image->scaleDown(640);
4124                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4125                         if (! $r) {
4126                                 logger("photo upload: image upload with scale 1 (640x640) failed");
4127                         }
4128                 }
4129
4130                 if ($width > 320 || $height > 320) {
4131                         $Image->scaleDown(320);
4132                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4133                         if (! $r) {
4134                                 logger("photo upload: image upload with scale 2 (320x320) failed");
4135                         }
4136                 }
4137                 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4138         } elseif ($mediatype == "profileimage") {
4139                 // upload profile image (scales 4, 5, 6)
4140                 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4141
4142                 if ($width > 175 || $height > 175) {
4143                         $Image->scaleDown(175);
4144                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4145                         if (! $r) {
4146                                 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4147                         }
4148                 }
4149
4150                 if ($width > 80 || $height > 80) {
4151                         $Image->scaleDown(80);
4152                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4153                         if (! $r) {
4154                                 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4155                         }
4156                 }
4157
4158                 if ($width > 48 || $height > 48) {
4159                         $Image->scaleDown(48);
4160                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4161                         if (! $r) {
4162                                 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4163                         }
4164                 }
4165                 $Image->__destruct();
4166                 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4167         }
4168
4169         if ($r) {
4170                 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4171                 if ($photo_id == null && $mediatype == "photo") {
4172                         post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4173                 }
4174                 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4175                 return prepare_photo_data($type, false, $hash);
4176         } else {
4177                 throw new InternalServerErrorException("image upload failed");
4178         }
4179 }
4180
4181 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4182 {
4183         // get data about the api authenticated user
4184         $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4185         $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4186
4187         $arr = array();
4188         $arr['guid']          = get_guid(32);
4189         $arr['uid']           = intval(api_user());
4190         $arr['uri']           = $uri;
4191         $arr['parent-uri']    = $uri;
4192         $arr['type']          = 'photo';
4193         $arr['wall']          = 1;
4194         $arr['resource-id']   = $hash;
4195         $arr['contact-id']    = $owner_record[0]['id'];
4196         $arr['owner-name']    = $owner_record[0]['name'];
4197         $arr['owner-link']    = $owner_record[0]['url'];
4198         $arr['owner-avatar']  = $owner_record[0]['thumb'];
4199         $arr['author-name']   = $owner_record[0]['name'];
4200         $arr['author-link']   = $owner_record[0]['url'];
4201         $arr['author-avatar'] = $owner_record[0]['thumb'];
4202         $arr['title']         = "";
4203         $arr['allow_cid']     = $allow_cid;
4204         $arr['allow_gid']     = $allow_gid;
4205         $arr['deny_cid']      = $deny_cid;
4206         $arr['deny_gid']      = $deny_gid;
4207         $arr['last-child']    = 1;
4208         $arr['visible']       = $visibility;
4209         $arr['origin']        = 1;
4210
4211         $typetoext = array(
4212                         'image/jpeg' => 'jpg',
4213                         'image/png' => 'png',
4214                         'image/gif' => 'gif'
4215                         );
4216
4217         // adds link to the thumbnail scale photo
4218         $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4219                                 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4220                                 . '[/url]';
4221
4222         // do the magic for storing the item in the database and trigger the federation to other contacts
4223         item_store($arr);
4224 }
4225
4226 function prepare_photo_data($type, $scale, $photo_id)
4227 {
4228         $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4229         $data_sql = ($scale === false ? "" : "data, ");
4230
4231         // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4232         // clients needs to convert this in their way for further processing
4233         $r = q(
4234                 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4235                                         `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4236                                         MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4237                         FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4238                 $data_sql,
4239                 intval(local_user()),
4240                 dbesc($photo_id),
4241                 $scale_sql
4242         );
4243
4244         $typetoext = array(
4245                 'image/jpeg' => 'jpg',
4246                 'image/png' => 'png',
4247                 'image/gif' => 'gif'
4248         );
4249
4250         // prepare output data for photo
4251         if (DBM::is_result($r)) {
4252                 $data = array('photo' => $r[0]);
4253                 $data['photo']['id'] = $data['photo']['resource-id'];
4254                 if ($scale !== false) {
4255                         $data['photo']['data'] = base64_encode($data['photo']['data']);
4256                 } else {
4257                         unset($data['photo']['datasize']); //needed only with scale param
4258                 }
4259                 if ($type == "xml") {
4260                         $data['photo']['links'] = array();
4261                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4262                                 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4263                                                                                 "scale" => $k,
4264                                                                                 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4265                         }
4266                 } else {
4267                         $data['photo']['link'] = array();
4268                         // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4269                         $i = 0;
4270                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4271                                 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4272                                 $i++;
4273                         }
4274                 }
4275                 unset($data['photo']['resource-id']);
4276                 unset($data['photo']['minscale']);
4277                 unset($data['photo']['maxscale']);
4278         } else {
4279                 throw new NotFoundException();
4280         }
4281
4282         // retrieve item element for getting activities (like, dislike etc.) related to photo
4283         $item = q(
4284                 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4285                 intval(local_user()),
4286                 dbesc($photo_id)
4287         );
4288         $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4289
4290         // retrieve comments on photo
4291         $r = q(
4292                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4293                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4294                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4295                 `contact`.`id` AS `cid`
4296                 FROM `item`
4297                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4298                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4299                 WHERE `item`.`parent` = %d AND `item`.`visible`
4300                 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4301                 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4302                 intval($item[0]['parent']),
4303                 intval(api_user()),
4304                 dbesc(ACTIVITY_POST)
4305         );
4306
4307         // prepare output of comments
4308         $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4309         $comments = array();
4310         if ($type == "xml") {
4311                 $k = 0;
4312                 foreach ($commentData as $comment) {
4313                         $comments[$k++ . ":comment"] = $comment;
4314                 }
4315         } else {
4316                 foreach ($commentData as $comment) {
4317                         $comments[] = $comment;
4318                 }
4319         }
4320         $data['photo']['friendica_comments'] = $comments;
4321
4322         // include info if rights on photo and rights on item are mismatching
4323         $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4324                 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4325                 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4326                 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4327         $data['photo']['rights_mismatch'] = $rights_mismatch;
4328
4329         return $data;
4330 }
4331
4332
4333 /**
4334  * Similar as /mod/redir.php
4335  * redirect to 'url' after dfrn auth
4336  *
4337  * Why this when there is mod/redir.php already?
4338  * This use api_user() and api_login()
4339  *
4340  * params
4341  *              c_url: url of remote contact to auth to
4342  *              url: string, url to redirect after auth
4343  */
4344 function api_friendica_remoteauth()
4345 {
4346         $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4347         $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4348
4349         if ($url === '' || $c_url === '') {
4350                 throw new BadRequestException("Wrong parameters.");
4351         }
4352
4353         $c_url = normalise_link($c_url);
4354
4355         // traditional DFRN
4356
4357         $r = q(
4358                 "SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4359                 dbesc($c_url),
4360                 intval(api_user())
4361         );
4362
4363         if ((! DBM::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4364                 throw new BadRequestException("Unknown contact");
4365         }
4366
4367         $cid = $r[0]['id'];
4368
4369         $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4370
4371         if ($r[0]['duplex'] && $r[0]['issued-id']) {
4372                 $orig_id = $r[0]['issued-id'];
4373                 $dfrn_id = '1:' . $orig_id;
4374         }
4375         if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4376                 $orig_id = $r[0]['dfrn-id'];
4377                 $dfrn_id = '0:' . $orig_id;
4378         }
4379
4380         $sec = random_string();
4381
4382         q(
4383                 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4384                 VALUES( %d, %s, '%s', '%s', %d )",
4385                 intval(api_user()),
4386                 intval($cid),
4387                 dbesc($dfrn_id),
4388                 dbesc($sec),
4389                 intval(time() + 45)
4390         );
4391
4392         logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4393         $dest = (($url) ? '&destination_url=' . $url : '');
4394         goaway(
4395                 $r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4396                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4397                 . '&type=profile&sec=' . $sec . $dest . $quiet
4398         );
4399 }
4400 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4401
4402 /**
4403  * @brief Return the item shared, if the item contains only the [share] tag
4404  *
4405  * @param array $item Sharer item
4406  * @return array Shared item or false if not a reshare
4407  */
4408 function api_share_as_retweet(&$item)
4409 {
4410         $body = trim($item["body"]);
4411
4412         if (Diaspora::isReshare($body, false)===false) {
4413                 return false;
4414         }
4415
4416         /// @TODO "$1" should maybe mean '$1' ?
4417         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4418         /*
4419                 * Skip if there is no shared message in there
4420                 * we already checked this in diaspora::isReshare()
4421                 * but better one more than one less...
4422                 */
4423         if ($body == $attributes) {
4424                 return false;
4425         }
4426
4427
4428         // build the fake reshared item
4429         $reshared_item = $item;
4430
4431         $author = "";
4432         preg_match("/author='(.*?)'/ism", $attributes, $matches);
4433         if ($matches[1] != "") {
4434                 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4435         }
4436
4437         preg_match('/author="(.*?)"/ism', $attributes, $matches);
4438         if ($matches[1] != "") {
4439                 $author = $matches[1];
4440         }
4441
4442         $profile = "";
4443         preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4444         if ($matches[1] != "") {
4445                 $profile = $matches[1];
4446         }
4447
4448         preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4449         if ($matches[1] != "") {
4450                 $profile = $matches[1];
4451         }
4452
4453         $avatar = "";
4454         preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4455         if ($matches[1] != "") {
4456                 $avatar = $matches[1];
4457         }
4458
4459         preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4460         if ($matches[1] != "") {
4461                 $avatar = $matches[1];
4462         }
4463
4464         $link = "";
4465         preg_match("/link='(.*?)'/ism", $attributes, $matches);
4466         if ($matches[1] != "") {
4467                 $link = $matches[1];
4468         }
4469
4470         preg_match('/link="(.*?)"/ism', $attributes, $matches);
4471         if ($matches[1] != "") {
4472                 $link = $matches[1];
4473         }
4474
4475         $posted = "";
4476         preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4477         if ($matches[1] != "")
4478                 $posted = $matches[1];
4479
4480         preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4481         if ($matches[1] != "") {
4482                 $posted = $matches[1];
4483         }
4484
4485         $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4486
4487         if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4488                 return false;
4489         }
4490
4491         $reshared_item["body"] = $shared_body;
4492         $reshared_item["author-name"] = $author;
4493         $reshared_item["author-link"] = $profile;
4494         $reshared_item["author-avatar"] = $avatar;
4495         $reshared_item["plink"] = $link;
4496         $reshared_item["created"] = $posted;
4497         $reshared_item["edited"] = $posted;
4498
4499         return $reshared_item;
4500
4501 }
4502
4503 function api_get_nick($profile)
4504 {
4505         /* To-Do:
4506                 - remove trailing junk from profile url
4507                 - pump.io check has to check the website
4508         */
4509
4510         $nick = "";
4511
4512         $r = q(
4513                 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4514                 dbesc(normalise_link($profile))
4515         );
4516
4517         if (DBM::is_result($r)) {
4518                 $nick = $r[0]["nick"];
4519         }
4520
4521         if (!$nick == "") {
4522                 $r = q(
4523                         "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4524                         dbesc(normalise_link($profile))
4525                 );
4526
4527                 if (DBM::is_result($r)) {
4528                         $nick = $r[0]["nick"];
4529                 }
4530         }
4531
4532         if (!$nick == "") {
4533                 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4534                 if ($friendica != $profile) {
4535                         $nick = $friendica;
4536                 }
4537         }
4538
4539         if (!$nick == "") {
4540                 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4541                 if ($diaspora != $profile) {
4542                         $nick = $diaspora;
4543                 }
4544         }
4545
4546         if (!$nick == "") {
4547                 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4548                 if ($twitter != $profile) {
4549                         $nick = $twitter;
4550                 }
4551         }
4552
4553
4554         if (!$nick == "") {
4555                 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4556                 if ($StatusnetHost != $profile) {
4557                         $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4558                         if ($StatusnetUser != $profile) {
4559                                 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4560                                 $user = json_decode($UserData);
4561                                 if ($user) {
4562                                         $nick = $user->screen_name;
4563                                 }
4564                         }
4565                 }
4566         }
4567
4568         // To-Do: look at the page if its really a pumpio site
4569         //if (!$nick == "") {
4570         //      $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4571         //      if ($pumpio != $profile)
4572         //              $nick = $pumpio;
4573                 //      <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4574
4575         //}
4576
4577         if ($nick != "") {
4578                 return $nick;
4579         }
4580
4581         return false;
4582 }
4583
4584 function api_in_reply_to($item)
4585 {
4586         $in_reply_to = array();
4587
4588         $in_reply_to['status_id'] = null;
4589         $in_reply_to['user_id'] = null;
4590         $in_reply_to['status_id_str'] = null;
4591         $in_reply_to['user_id_str'] = null;
4592         $in_reply_to['screen_name'] = null;
4593
4594         if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4595                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4596                         intval($item['uid']),
4597                         dbesc($item['thr-parent']));
4598
4599                 if (DBM::is_result($r)) {
4600                         $in_reply_to['status_id'] = intval($r[0]['id']);
4601                 } else {
4602                         $in_reply_to['status_id'] = intval($item['parent']);
4603                 }
4604
4605                 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4606
4607                 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4608                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4609                         WHERE `item`.`id` = %d LIMIT 1",
4610                         intval($in_reply_to['status_id'])
4611                 );
4612
4613                 if (DBM::is_result($r)) {
4614                         if ($r[0]['nick'] == "") {
4615                                 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4616                         }
4617
4618                         $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4619                         $in_reply_to['user_id'] = intval($r[0]['id']);
4620                         $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4621                 }
4622
4623                 // There seems to be situation, where both fields are identical:
4624                 // https://github.com/friendica/friendica/issues/1010
4625                 // This is a bugfix for that.
4626                 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4627                         logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4628                         $in_reply_to['status_id'] = null;
4629                         $in_reply_to['user_id'] = null;
4630                         $in_reply_to['status_id_str'] = null;
4631                         $in_reply_to['user_id_str'] = null;
4632                         $in_reply_to['screen_name'] = null;
4633                 }
4634         }
4635
4636         return $in_reply_to;
4637 }
4638
4639 function api_clean_plain_items($Text)
4640 {
4641         $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4642
4643         $Text = bb_CleanPictureLinks($Text);
4644         $URLSearchString = "^\[\]";
4645
4646         $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
4647
4648         if ($include_entities == "true") {
4649                 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
4650         }
4651
4652         // Simplify "attachment" element
4653         $Text = api_clean_attachments($Text);
4654
4655         return($Text);
4656 }
4657
4658 /**
4659  * @brief Removes most sharing information for API text export
4660  *
4661  * @param string $body The original body
4662  *
4663  * @return string Cleaned body
4664  */
4665 function api_clean_attachments($body)
4666 {
4667         $data = get_attachment_data($body);
4668
4669         if (!$data)
4670                 return $body;
4671
4672         $body = "";
4673
4674         if (isset($data["text"]))
4675                 $body = $data["text"];
4676
4677         if (($body == "") && (isset($data["title"])))
4678                 $body = $data["title"];
4679
4680         if (isset($data["url"]))
4681                 $body .= "\n".$data["url"];
4682
4683         $body .= $data["after"];
4684
4685         return $body;
4686 }
4687
4688 function api_best_nickname(&$contacts)
4689 {
4690         $best_contact = array();
4691
4692         if (count($contact) == 0)
4693                 return;
4694
4695         foreach ($contacts as $contact)
4696                 if ($contact["network"] == "") {
4697                         $contact["network"] = "dfrn";
4698                         $best_contact = array($contact);
4699                 }
4700
4701         if (sizeof($best_contact) == 0)
4702                 foreach ($contacts as $contact)
4703                         if ($contact["network"] == "dfrn")
4704                                 $best_contact = array($contact);
4705
4706         if (sizeof($best_contact) == 0)
4707                 foreach ($contacts as $contact)
4708                         if ($contact["network"] == "dspr")
4709                                 $best_contact = array($contact);
4710
4711         if (sizeof($best_contact) == 0)
4712                 foreach ($contacts as $contact)
4713                         if ($contact["network"] == "stat")
4714                                 $best_contact = array($contact);
4715
4716         if (sizeof($best_contact) == 0)
4717                 foreach ($contacts as $contact)
4718                         if ($contact["network"] == "pump")
4719                                 $best_contact = array($contact);
4720
4721         if (sizeof($best_contact) == 0)
4722                 foreach ($contacts as $contact)
4723                         if ($contact["network"] == "twit")
4724                                 $best_contact = array($contact);
4725
4726         if (sizeof($best_contact) == 1) {
4727                 $contacts = $best_contact;
4728         } else {
4729                 $contacts = array($contacts[0]);
4730         }
4731 }
4732
4733 // return all or a specified group of the user with the containing contacts
4734 function api_friendica_group_show($type)
4735 {
4736         $a = get_app();
4737
4738         if (api_user() === false) throw new ForbiddenException();
4739
4740         // params
4741         $user_info = api_get_user($a);
4742         $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4743         $uid = $user_info['uid'];
4744
4745         // get data of the specified group id or all groups if not specified
4746         if ($gid != 0) {
4747                 $r = q(
4748                         "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4749                         intval($uid),
4750                         intval($gid)
4751                 );
4752                 // error message if specified gid is not in database
4753                 if (!DBM::is_result($r))
4754                         throw new BadRequestException("gid not available");
4755         } else {
4756                 $r = q(
4757                         "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4758                         intval($uid)
4759                 );
4760         }
4761
4762         // loop through all groups and retrieve all members for adding data in the user array
4763         foreach ($r as $rr) {
4764                 $members = Contact::getByGroupId($rr['id']);
4765                 $users = array();
4766
4767                 if ($type == "xml") {
4768                         $user_element = "users";
4769                         $k = 0;
4770                         foreach ($members as $member) {
4771                                 $user = api_get_user($a, $member['nurl']);
4772                                 $users[$k++.":user"] = $user;
4773                         }
4774                 } else {
4775                         $user_element = "user";
4776                         foreach ($members as $member) {
4777                                 $user = api_get_user($a, $member['nurl']);
4778                                 $users[] = $user;
4779                         }
4780                 }
4781                 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4782         }
4783         return api_format_data("groups", $type, array('group' => $grps));
4784 }
4785 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4786
4787
4788 // delete the specified group of the user
4789 function api_friendica_group_delete($type)
4790 {
4791         $a = get_app();
4792
4793         if (api_user() === false) {
4794                 throw new ForbiddenException();
4795         }
4796
4797         // params
4798         $user_info = api_get_user($a);
4799         $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4800         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4801         $uid = $user_info['uid'];
4802
4803         // error if no gid specified
4804         if ($gid == 0 || $name == "") {
4805                 throw new BadRequestException('gid or name not specified');
4806         }
4807
4808         // get data of the specified group id
4809         $r = q(
4810                 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
4811                 intval($uid),
4812                 intval($gid)
4813         );
4814         // error message if specified gid is not in database
4815         if (!DBM::is_result($r)) {
4816                 throw new BadRequestException('gid not available');
4817         }
4818
4819         // get data of the specified group id and group name
4820         $rname = q(
4821                 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
4822                 intval($uid),
4823                 intval($gid),
4824                 dbesc($name)
4825         );
4826         // error message if specified gid is not in database
4827         if (!DBM::is_result($rname)) {
4828                 throw new BadRequestException('wrong group name');
4829         }
4830
4831         // delete group
4832         $ret = Group::removeByName($uid, $name);
4833         if ($ret) {
4834                 // return success
4835                 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
4836                 return api_format_data("group_delete", $type, array('result' => $success));
4837         } else {
4838                 throw new BadRequestException('other API error');
4839         }
4840 }
4841 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4842
4843
4844 // create the specified group with the posted array of contacts
4845 function api_friendica_group_create($type)
4846 {
4847         $a = get_app();
4848
4849         if (api_user() === false) throw new ForbiddenException();
4850
4851         // params
4852         $user_info = api_get_user($a);
4853         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4854         $uid = $user_info['uid'];
4855         $json = json_decode($_POST['json'], true);
4856         $users = $json['user'];
4857
4858         // error if no name specified
4859         if ($name == "")
4860                 throw new BadRequestException('group name not specified');
4861
4862         // get data of the specified group name
4863         $rname = q(
4864                 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
4865                 intval($uid),
4866                 dbesc($name)
4867         );
4868         // error message if specified group name already exists
4869         if (DBM::is_result($rname))
4870                 throw new BadRequestException('group name already exists');
4871
4872         // check if specified group name is a deleted group
4873         $rname = q(
4874                 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
4875                 intval($uid),
4876                 dbesc($name)
4877         );
4878         // error message if specified group name already exists
4879         if (DBM::is_result($rname))
4880                 $reactivate_group = true;
4881
4882         // create group
4883         $ret = Group::create($uid, $name);
4884         if ($ret) {
4885                 $gid = Group::getIdByName($uid, $name);
4886         } else {
4887                 throw new BadRequestException('other API error');
4888         }
4889
4890         // add members
4891         $erroraddinguser = false;
4892         $errorusers = array();
4893         foreach ($users as $user) {
4894                 $cid = $user['cid'];
4895                 // check if user really exists as contact
4896                 $contact = q(
4897                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4898                         intval($cid),
4899                         intval($uid)
4900                 );
4901                 if (count($contact))
4902                         $result = Group::addMember($gid, $cid);
4903                 else {
4904                         $erroraddinguser = true;
4905                         $errorusers[] = $cid;
4906                 }
4907         }
4908
4909         // return success message incl. missing users in array
4910         $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
4911         $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4912         return api_format_data("group_create", $type, array('result' => $success));
4913 }
4914 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4915
4916
4917 // update the specified group with the posted array of contacts
4918 function api_friendica_group_update($type)
4919 {
4920         $a = get_app();
4921
4922         if (api_user() === false) throw new ForbiddenException();
4923
4924         // params
4925         $user_info = api_get_user($a);
4926         $uid = $user_info['uid'];
4927         $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4928         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4929         $json = json_decode($_POST['json'], true);
4930         $users = $json['user'];
4931
4932         // error if no name specified
4933         if ($name == "")
4934                 throw new BadRequestException('group name not specified');
4935
4936         // error if no gid specified
4937         if ($gid == "")
4938                 throw new BadRequestException('gid not specified');
4939
4940         // remove members
4941         $members = Contact::getByGroupId($gid);
4942         foreach ($members as $member) {
4943                 $cid = $member['id'];
4944                 foreach ($users as $user) {
4945                         $found = ($user['cid'] == $cid ? true : false);
4946                 }
4947                 if (!$found) {
4948                         $ret = Group::removeMemberByName($uid, $name, $cid);
4949                 }
4950         }
4951
4952         // add members
4953         $erroraddinguser = false;
4954         $errorusers = array();
4955         foreach ($users as $user) {
4956                 $cid = $user['cid'];
4957                 // check if user really exists as contact
4958                 $contact = q(
4959                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4960                         intval($cid),
4961                         intval($uid)
4962                 );
4963
4964                 if (count($contact)) {
4965                         $result = Group::addMember($gid, $cid);
4966                 } else {
4967                         $erroraddinguser = true;
4968                         $errorusers[] = $cid;
4969                 }
4970         }
4971
4972         // return success message incl. missing users in array
4973         $status = ($erroraddinguser ? "missing user" : "ok");
4974         $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4975         return api_format_data("group_update", $type, array('result' => $success));
4976 }
4977
4978 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4979
4980 function api_friendica_activity($type)
4981 {
4982         $a = get_app();
4983
4984         if (api_user() === false) throw new ForbiddenException();
4985         $verb = strtolower($a->argv[3]);
4986         $verb = preg_replace("|\..*$|", "", $verb);
4987
4988         $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4989
4990         $res = do_like($id, $verb);
4991
4992         if ($res) {
4993                 if ($type == "xml") {
4994                         $ok = "true";
4995                 } else {
4996                         $ok = "ok";
4997                 }
4998                 return api_format_data('ok', $type, array('ok' => $ok));
4999         } else {
5000                 throw new BadRequestException('Error adding activity');
5001         }
5002 }
5003
5004 /// @TODO move to top of file or somwhere better
5005 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5006 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5007 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5008 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5009 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5010 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5011 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5012 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5013 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5014 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5015
5016 /**
5017  * @brief Returns notifications
5018  *
5019  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5020  * @return string
5021 */
5022 function api_friendica_notification($type)
5023 {
5024         $a = get_app();
5025
5026         if (api_user() === false) throw new ForbiddenException();
5027         if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
5028         $nm = new NotificationsManager();
5029
5030         $notes = $nm->getAll(array(), "+seen -date", 50);
5031
5032         if ($type == "xml") {
5033                 $xmlnotes = array();
5034                 foreach ($notes as $note)
5035                         $xmlnotes[] = array("@attributes" => $note);
5036
5037                 $notes = $xmlnotes;
5038         }
5039
5040         return api_format_data("notes", $type, array('note' => $notes));
5041 }
5042
5043 /**
5044  * @brief Set notification as seen and returns associated item (if possible)
5045  *
5046  * POST request with 'id' param as notification id
5047  *
5048  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5049  * @return string
5050  */
5051 function api_friendica_notification_seen($type)
5052 {
5053         $a = get_app();
5054
5055         if (api_user() === false) throw new ForbiddenException();
5056         if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
5057
5058         $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5059
5060         $nm = new NotificationsManager();
5061         $note = $nm->getByID($id);
5062         if (is_null($note)) throw new BadRequestException("Invalid argument");
5063
5064         $nm->setSeen($note);
5065         if ($note['otype']=='item') {
5066                 // would be really better with an ItemsManager and $im->getByID() :-P
5067                 $r = q(
5068                         "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5069                         intval($note['iid']),
5070                         intval(local_user())
5071                 );
5072                 if ($r!==false) {
5073                         // we found the item, return it to the user
5074                         $user_info = api_get_user($a);
5075                         $ret = api_format_items($r, $user_info, false, $type);
5076                         $data = array('status' => $ret);
5077                         return api_format_data("status", $type, $data);
5078                 }
5079                 // the item can't be found, but we set the note as seen, so we count this as a success
5080         }
5081         return api_format_data('result', $type, array('result' => "success"));
5082 }
5083
5084 /// @TODO move to top of file or somwhere better
5085 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5086 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5087
5088 /**
5089  * @brief update a direct_message to seen state
5090  *
5091  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5092  * @return string (success result=ok, error result=error with error message)
5093  */
5094 function api_friendica_direct_messages_setseen($type)
5095 {
5096         $a = get_app();
5097         if (api_user() === false) {
5098                 throw new ForbiddenException();
5099         }
5100
5101         // params
5102         $user_info = api_get_user($a);
5103         $uid = $user_info['uid'];
5104         $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5105
5106         // return error if id is zero
5107         if ($id == "") {
5108                 $answer = array('result' => 'error', 'message' => 'message id not specified');
5109                 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5110         }
5111
5112         // get data of the specified message id
5113         $r = q(
5114                 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5115                 intval($id),
5116                 intval($uid)
5117         );
5118
5119         // error message if specified id is not in database
5120         if (!DBM::is_result($r)) {
5121                 $answer = array('result' => 'error', 'message' => 'message id not in database');
5122                 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5123         }
5124
5125         // update seen indicator
5126         $result = q(
5127                 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5128                 intval($id),
5129                 intval($uid)
5130         );
5131
5132         if ($result) {
5133                 // return success
5134                 $answer = array('result' => 'ok', 'message' => 'message set to seen');
5135                 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
5136         } else {
5137                 $answer = array('result' => 'error', 'message' => 'unknown error');
5138                 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5139         }
5140 }
5141
5142 /// @TODO move to top of file or somwhere better
5143 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5144
5145 /**
5146  * @brief search for direct_messages containing a searchstring through api
5147  *
5148  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5149  * @return string (success: success=true if found and search_result contains found messages
5150  *                          success=false if nothing was found, search_result='nothing found',
5151  *                 error: result=error with error message)
5152  */
5153 function api_friendica_direct_messages_search($type)
5154 {
5155         $a = get_app();
5156
5157         if (api_user() === false) {
5158                 throw new ForbiddenException();
5159         }
5160
5161         // params
5162         $user_info = api_get_user($a);
5163         $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5164         $uid = $user_info['uid'];
5165
5166         // error if no searchstring specified
5167         if ($searchstring == "") {
5168                 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
5169                 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
5170         }
5171
5172         // get data for the specified searchstring
5173         $r = q(
5174                 "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",
5175                 intval($uid),
5176                 dbesc('%'.$searchstring.'%')
5177         );
5178
5179         $profile_url = $user_info["url"];
5180
5181         // message if nothing was found
5182         if (!DBM::is_result($r)) {
5183                 $success = array('success' => false, 'search_results' => 'problem with query');
5184         } elseif (count($r) == 0) {
5185                 $success = array('success' => false, 'search_results' => 'nothing found');
5186         } else {
5187                 $ret = array();
5188                 foreach ($r as $item) {
5189                         if ($box == "inbox" || $item['from-url'] != $profile_url) {
5190                                 $recipient = $user_info;
5191                                 $sender = api_get_user($a, normalise_link($item['contact-url']));
5192                         } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5193                                 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5194                                 $sender = $user_info;
5195                         }
5196
5197                         $ret[] = api_format_messages($item, $recipient, $sender);
5198                 }
5199                 $success = array('success' => true, 'search_results' => $ret);
5200         }
5201
5202         return api_format_data("direct_message_search", $type, array('$result' => $success));
5203 }
5204
5205 /// @TODO move to top of file or somwhere better
5206 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5207
5208 /**
5209  * @brief return data of all the profiles a user has to the client
5210  *
5211  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5212  * @return string
5213  */
5214 function api_friendica_profile_show($type)
5215 {
5216         $a = get_app();
5217
5218         if (api_user() === false) {
5219                 throw new ForbiddenException();
5220         }
5221
5222         // input params
5223         $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5224
5225         // retrieve general information about profiles for user
5226         $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5227         $directory = Config::get('system', 'directory');
5228
5229         // get data of the specified profile id or all profiles of the user if not specified
5230         if ($profileid != 0) {
5231                 $r = q(
5232                         "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5233                         intval(api_user()),
5234                         intval($profileid)
5235                 );
5236
5237                 // error message if specified gid is not in database
5238                 if (!DBM::is_result($r)) {
5239                         throw new BadRequestException("profile_id not available");
5240                 }
5241         } else {
5242                 $r = q(
5243                         "SELECT * FROM `profile` WHERE `uid` = %d",
5244                         intval(api_user())
5245                 );
5246         }
5247         // loop through all returned profiles and retrieve data and users
5248         $k = 0;
5249         foreach ($r as $rr) {
5250                 $profile = api_format_items_profiles($rr, $type);
5251
5252                 // select all users from contact table, loop and prepare standard return for user data
5253                 $users = array();
5254                 $r = q(
5255                         "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5256                         intval(api_user()),
5257                         intval($rr['profile_id'])
5258                 );
5259
5260                 foreach ($r as $rr) {
5261                         $user = api_get_user($a, $rr['nurl']);
5262                         ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5263                 }
5264                 $profile['users'] = $users;
5265
5266                 // add prepared profile data to array for final return
5267                 if ($type == "xml") {
5268                         $profiles[$k++ . ":profile"] = $profile;
5269                 } else {
5270                         $profiles[] = $profile;
5271                 }
5272         }
5273
5274         // return settings, authenticated user and profiles data
5275         $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5276
5277         $result = array('multi_profiles' => $multi_profiles ? true : false,
5278                                         'global_dir' => $directory,
5279                                         'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5280                                         'profiles' => $profiles);
5281         return api_format_data("friendica_profiles", $type, array('$result' => $result));
5282 }
5283 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5284
5285 /*
5286 @TODO Maybe open to implement?
5287 To.Do:
5288     [pagename] => api/1.1/statuses/lookup.json
5289     [id] => 605138389168451584
5290     [include_cards] => true
5291     [cards_platform] => Android-12
5292     [include_entities] => true
5293     [include_my_retweet] => 1
5294     [include_rts] => 1
5295     [include_reply_count] => true
5296     [include_descendent_reply_count] => true
5297 (?)
5298
5299
5300 Not implemented by now:
5301 statuses/retweets_of_me
5302 friendships/create
5303 friendships/destroy
5304 friendships/exists
5305 friendships/show
5306 account/update_location
5307 account/update_profile_background_image
5308 blocks/create
5309 blocks/destroy
5310 friendica/profile/update
5311 friendica/profile/create
5312 friendica/profile/delete
5313
5314 Not implemented in status.net:
5315 statuses/retweeted_to_me
5316 statuses/retweeted_by_me
5317 direct_messages/destroy
5318 account/end_session
5319 account/update_delivery_device
5320 notifications/follow
5321 notifications/leave
5322 blocks/exists
5323 blocks/blocking
5324 lists
5325 */