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