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