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