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