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