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