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