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