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