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