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