]> git.mxchange.org Git - friendica.git/blob - include/api.php
Standards and a new function to fetch content
[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         $countitems = 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($countitems),
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(Item::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 = Item::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 = Item::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 = Item::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(Item::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(Item::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(Item::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(Item::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(Item::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(Item::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 ($item = Item::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, $item['author-id']);
2737                 switch ($item['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(Item::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         if (api_user() === false) {
3621                 throw new ForbiddenException();
3622         }
3623         // params
3624         $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3625         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3626         if ($page < 0) {
3627                 $page = 0;
3628         }
3629
3630         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3631         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3632
3633         $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3634         $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3635
3636         //  caller user info
3637         unset($_REQUEST["user_id"]);
3638         unset($_GET["user_id"]);
3639
3640         unset($_REQUEST["screen_name"]);
3641         unset($_GET["screen_name"]);
3642
3643         $user_info = api_get_user($a);
3644         if ($user_info === false) {
3645                 throw new ForbiddenException();
3646         }
3647         $profile_url = $user_info["url"];
3648
3649         // pagination
3650         $start = $page * $count;
3651
3652         $sql_extra = "";
3653
3654         // filters
3655         if ($box=="sentbox") {
3656                 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3657         } elseif ($box == "conversation") {
3658                 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"])  . "'";
3659         } elseif ($box == "all") {
3660                 $sql_extra = "true";
3661         } elseif ($box == "inbox") {
3662                 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3663         }
3664
3665         if ($max_id > 0) {
3666                 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3667         }
3668
3669         if ($user_id != "") {
3670                 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3671         } elseif ($screen_name !="") {
3672                 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3673         }
3674
3675         $r = q(
3676                 "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",
3677                 intval(api_user()),
3678                 intval($since_id),
3679                 intval($start),
3680                 intval($count)
3681         );
3682         if ($verbose == "true" && !DBM::is_result($r)) {
3683                 $answer = ['result' => 'error', 'message' => 'no mails available'];
3684                 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3685         }
3686
3687         $ret = [];
3688         foreach ($r as $item) {
3689                 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3690                         $recipient = $user_info;
3691                         $sender = api_get_user($a, normalise_link($item['contact-url']));
3692                 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3693                         $recipient = api_get_user($a, normalise_link($item['contact-url']));
3694                         $sender = $user_info;
3695                 }
3696
3697                 if (isset($recipient) && isset($sender)) {
3698                         $ret[] = api_format_messages($item, $recipient, $sender);
3699                 }
3700         }
3701
3702
3703         $data = ['direct_message' => $ret];
3704         switch ($type) {
3705                 case "atom":
3706                 case "rss":
3707                         $data = api_rss_extra($a, $data, $user_info);
3708         }
3709
3710         return api_format_data("direct-messages", $type, $data);
3711 }
3712
3713 /**
3714  * Returns the most recent direct messages sent by the user.
3715  *
3716  * @param string $type Return type (atom, rss, xml, json)
3717  *
3718  * @return array|string
3719  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3720  */
3721 function api_direct_messages_sentbox($type)
3722 {
3723         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3724         return api_direct_messages_box($type, "sentbox", $verbose);
3725 }
3726
3727 /**
3728  * Returns the most recent direct messages sent to the user.
3729  *
3730  * @param string $type Return type (atom, rss, xml, json)
3731  *
3732  * @return array|string
3733  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3734  */
3735 function api_direct_messages_inbox($type)
3736 {
3737         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3738         return api_direct_messages_box($type, "inbox", $verbose);
3739 }
3740
3741 /**
3742  *
3743  * @param string $type Return type (atom, rss, xml, json)
3744  *
3745  * @return array|string
3746  */
3747 function api_direct_messages_all($type)
3748 {
3749         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3750         return api_direct_messages_box($type, "all", $verbose);
3751 }
3752
3753 /**
3754  *
3755  * @param string $type Return type (atom, rss, xml, json)
3756  *
3757  * @return array|string
3758  */
3759 function api_direct_messages_conversation($type)
3760 {
3761         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3762         return api_direct_messages_box($type, "conversation", $verbose);
3763 }
3764
3765 /// @TODO move to top of file or somewhere better
3766 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3767 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3768 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3769 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3770
3771 /**
3772  * Returns an OAuth Request Token.
3773  *
3774  * @see https://oauth.net/core/1.0/#auth_step1
3775  */
3776 function api_oauth_request_token()
3777 {
3778         $oauth1 = new FKOAuth1();
3779         try {
3780                 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3781         } catch (Exception $e) {
3782                 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3783                 killme();
3784         }
3785         echo $r;
3786         killme();
3787 }
3788
3789 /**
3790  * Returns an OAuth Access Token.
3791  *
3792  * @return array|string
3793  * @see https://oauth.net/core/1.0/#auth_step3
3794  */
3795 function api_oauth_access_token()
3796 {
3797         $oauth1 = new FKOAuth1();
3798         try {
3799                 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3800         } catch (Exception $e) {
3801                 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3802                 killme();
3803         }
3804         echo $r;
3805         killme();
3806 }
3807
3808 /// @TODO move to top of file or somewhere better
3809 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3810 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3811
3812
3813 /**
3814  * @brief delete a complete photoalbum with all containing photos from database through api
3815  *
3816  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3817  * @return string|array
3818  */
3819 function api_fr_photoalbum_delete($type)
3820 {
3821         if (api_user() === false) {
3822                 throw new ForbiddenException();
3823         }
3824         // input params
3825         $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3826
3827         // we do not allow calls without album string
3828         if ($album == "") {
3829                 throw new BadRequestException("no albumname specified");
3830         }
3831         // check if album is existing
3832         $r = q(
3833                 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3834                 intval(api_user()),
3835                 dbesc($album)
3836         );
3837         if (!DBM::is_result($r)) {
3838                 throw new BadRequestException("album not available");
3839         }
3840
3841         // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3842         // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3843         foreach ($r as $rr) {
3844                 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
3845                 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
3846
3847                 if (!DBM::is_result($photo_item)) {
3848                         throw new InternalServerErrorException("problem with deleting items occured");
3849                 }
3850                 Item::deleteForUser(['id' => $photo_item['id']], api_user());
3851         }
3852
3853         // now let's delete all photos from the album
3854         $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
3855
3856         // return success of deletion or error message
3857         if ($result) {
3858                 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
3859                 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
3860         } else {
3861                 throw new InternalServerErrorException("unknown error - deleting from database failed");
3862         }
3863 }
3864
3865 /**
3866  * @brief update the name of the album for all photos of an album
3867  *
3868  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3869  * @return string|array
3870  */
3871 function api_fr_photoalbum_update($type)
3872 {
3873         if (api_user() === false) {
3874                 throw new ForbiddenException();
3875         }
3876         // input params
3877         $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3878         $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3879
3880         // we do not allow calls without album string
3881         if ($album == "") {
3882                 throw new BadRequestException("no albumname specified");
3883         }
3884         if ($album_new == "") {
3885                 throw new BadRequestException("no new albumname specified");
3886         }
3887         // check if album is existing
3888         if (!dba::exists('photo', ['uid' => api_user(), 'album' => $album])) {
3889                 throw new BadRequestException("album not available");
3890         }
3891         // now let's update all photos to the albumname
3892         $result = dba::update('photo', ['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
3893
3894         // return success of updating or error message
3895         if ($result) {
3896                 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
3897                 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
3898         } else {
3899                 throw new InternalServerErrorException("unknown error - updating in database failed");
3900         }
3901 }
3902
3903
3904 /**
3905  * @brief list all photos of the authenticated user
3906  *
3907  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3908  * @return string|array
3909  */
3910 function api_fr_photos_list($type)
3911 {
3912         if (api_user() === false) {
3913                 throw new ForbiddenException();
3914         }
3915         $r = q(
3916                 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3917                 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3918                 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3919                 intval(local_user())
3920         );
3921         $typetoext = [
3922                 'image/jpeg' => 'jpg',
3923                 'image/png' => 'png',
3924                 'image/gif' => 'gif'
3925         ];
3926         $data = ['photo'=>[]];
3927         if (DBM::is_result($r)) {
3928                 foreach ($r as $rr) {
3929                         $photo = [];
3930                         $photo['id'] = $rr['resource-id'];
3931                         $photo['album'] = $rr['album'];
3932                         $photo['filename'] = $rr['filename'];
3933                         $photo['type'] = $rr['type'];
3934                         $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3935                         $photo['created'] = $rr['created'];
3936                         $photo['edited'] = $rr['edited'];
3937                         $photo['desc'] = $rr['desc'];
3938
3939                         if ($type == "xml") {
3940                                 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3941                         } else {
3942                                 $photo['thumb'] = $thumb;
3943                                 $data['photo'][] = $photo;
3944                         }
3945                 }
3946         }
3947         return api_format_data("photos", $type, $data);
3948 }
3949
3950 /**
3951  * @brief upload a new photo or change an existing photo
3952  *
3953  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3954  * @return string|array
3955  */
3956 function api_fr_photo_create_update($type)
3957 {
3958         if (api_user() === false) {
3959                 throw new ForbiddenException();
3960         }
3961         // input params
3962         $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3963         $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3964         $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3965         $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3966         $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3967         $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3968         $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3969         $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3970         $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3971
3972         // do several checks on input parameters
3973         // we do not allow calls without album string
3974         if ($album == null) {
3975                 throw new BadRequestException("no albumname specified");
3976         }
3977         // if photo_id == null --> we are uploading a new photo
3978         if ($photo_id == null) {
3979                 $mode = "create";
3980
3981                 // error if no media posted in create-mode
3982                 if (!x($_FILES, 'media')) {
3983                         // Output error
3984                         throw new BadRequestException("no media data submitted");
3985                 }
3986
3987                 // album_new will be ignored in create-mode
3988                 $album_new = "";
3989         } else {
3990                 $mode = "update";
3991
3992                 // check if photo is existing in database
3993                 $r = q(
3994                         "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3995                         intval(api_user()),
3996                         dbesc($photo_id),
3997                         dbesc($album)
3998                 );
3999                 if (!DBM::is_result($r)) {
4000                         throw new BadRequestException("photo not available");
4001                 }
4002         }
4003
4004         // checks on acl strings provided by clients
4005         $acl_input_error = false;
4006         $acl_input_error |= check_acl_input($allow_cid);
4007         $acl_input_error |= check_acl_input($deny_cid);
4008         $acl_input_error |= check_acl_input($allow_gid);
4009         $acl_input_error |= check_acl_input($deny_gid);
4010         if ($acl_input_error) {
4011                 throw new BadRequestException("acl data invalid");
4012         }
4013         // now let's upload the new media in create-mode
4014         if ($mode == "create") {
4015                 $media = $_FILES['media'];
4016                 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4017
4018                 // return success of updating or error message
4019                 if (!is_null($data)) {
4020                         return api_format_data("photo_create", $type, $data);
4021                 } else {
4022                         throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4023                 }
4024         }
4025
4026         // now let's do the changes in update-mode
4027         if ($mode == "update") {
4028                 $sql_extra = "";
4029
4030                 if (!is_null($desc)) {
4031                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4032                 }
4033
4034                 if (!is_null($album_new)) {
4035                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4036                 }
4037
4038                 if (!is_null($allow_cid)) {
4039                         $allow_cid = trim($allow_cid);
4040                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4041                 }
4042
4043                 if (!is_null($deny_cid)) {
4044                         $deny_cid = trim($deny_cid);
4045                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4046                 }
4047
4048                 if (!is_null($allow_gid)) {
4049                         $allow_gid = trim($allow_gid);
4050                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4051                 }
4052
4053                 if (!is_null($deny_gid)) {
4054                         $deny_gid = trim($deny_gid);
4055                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4056                 }
4057
4058                 $result = false;
4059                 if ($sql_extra != "") {
4060                         $nothingtodo = false;
4061                         $result = q(
4062                                 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4063                                 $sql_extra,
4064                                 DateTimeFormat::utcNow(),   // update edited timestamp
4065                                 intval(api_user()),
4066                                 dbesc($photo_id),
4067                                 dbesc($album)
4068                         );
4069                 } else {
4070                         $nothingtodo = true;
4071                 }
4072
4073                 if (x($_FILES, 'media')) {
4074                         $nothingtodo = false;
4075                         $media = $_FILES['media'];
4076                         $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4077                         if (!is_null($data)) {
4078                                 return api_format_data("photo_update", $type, $data);
4079                         }
4080                 }
4081
4082                 // return success of updating or error message
4083                 if ($result) {
4084                         $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4085                         return api_format_data("photo_update", $type, ['$result' => $answer]);
4086                 } else {
4087                         if ($nothingtodo) {
4088                                 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4089                                 return api_format_data("photo_update", $type, ['$result' => $answer]);
4090                         }
4091                         throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4092                 }
4093         }
4094         throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4095 }
4096
4097 /**
4098  * @brief delete a single photo from the database through api
4099  *
4100  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4101  * @return string|array
4102  */
4103 function api_fr_photo_delete($type)
4104 {
4105         if (api_user() === false) {
4106                 throw new ForbiddenException();
4107         }
4108         // input params
4109         $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4110
4111         // do several checks on input parameters
4112         // we do not allow calls without photo id
4113         if ($photo_id == null) {
4114                 throw new BadRequestException("no photo_id specified");
4115         }
4116         // check if photo is existing in database
4117         $r = q(
4118                 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4119                 intval(api_user()),
4120                 dbesc($photo_id)
4121         );
4122         if (!DBM::is_result($r)) {
4123                 throw new BadRequestException("photo not available");
4124         }
4125         // now we can perform on the deletion of the photo
4126         $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4127
4128         // return success of deletion or error message
4129         if ($result) {
4130                 // retrieve the id of the parent element (the photo element)
4131                 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4132                 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4133
4134                 if (!DBM::is_result($photo_item)) {
4135                         throw new InternalServerErrorException("problem with deleting items occured");
4136                 }
4137                 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4138                 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4139                 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4140
4141                 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4142                 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4143         } else {
4144                 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4145         }
4146 }
4147
4148
4149 /**
4150  * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4151  *
4152  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4153  * @return string|array
4154  */
4155 function api_fr_photo_detail($type)
4156 {
4157         if (api_user() === false) {
4158                 throw new ForbiddenException();
4159         }
4160         if (!x($_REQUEST, 'photo_id')) {
4161                 throw new BadRequestException("No photo id.");
4162         }
4163
4164         $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4165         $photo_id = $_REQUEST['photo_id'];
4166
4167         // prepare json/xml output with data from database for the requested photo
4168         $data = prepare_photo_data($type, $scale, $photo_id);
4169
4170         return api_format_data("photo_detail", $type, $data);
4171 }
4172
4173
4174 /**
4175  * Updates the user’s profile image.
4176  *
4177  * @brief updates the profile image for the user (either a specified profile or the default profile)
4178  *
4179  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4180  *
4181  * @return string|array
4182  * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4183  */
4184 function api_account_update_profile_image($type)
4185 {
4186         if (api_user() === false) {
4187                 throw new ForbiddenException();
4188         }
4189         // input params
4190         $profile_id = defaults($_REQUEST, 'profile_id', 0);
4191
4192         // error if image data is missing
4193         if (!x($_FILES, 'image')) {
4194                 throw new BadRequestException("no media data submitted");
4195         }
4196
4197         // check if specified profile id is valid
4198         if ($profile_id != 0) {
4199                 $profile = dba::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4200                 // error message if specified profile id is not in database
4201                 if (!DBM::is_result($profile)) {
4202                         throw new BadRequestException("profile_id not available");
4203                 }
4204                 $is_default_profile = $profile['is-default'];
4205         } else {
4206                 $is_default_profile = 1;
4207         }
4208
4209         // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4210         $media = null;
4211         if (x($_FILES, 'image')) {
4212                 $media = $_FILES['image'];
4213         } elseif (x($_FILES, 'media')) {
4214                 $media = $_FILES['media'];
4215         }
4216         // save new profile image
4217         $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4218
4219         // get filetype
4220         if (is_array($media['type'])) {
4221                 $filetype = $media['type'][0];
4222         } else {
4223                 $filetype = $media['type'];
4224         }
4225         if ($filetype == "image/jpeg") {
4226                 $fileext = "jpg";
4227         } elseif ($filetype == "image/png") {
4228                 $fileext = "png";
4229         } else {
4230                 throw new InternalServerErrorException('Unsupported filetype');
4231         }
4232
4233         // change specified profile or all profiles to the new resource-id
4234         if ($is_default_profile) {
4235                 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4236                 dba::update('photo', ['profile' => false], $condition);
4237         } else {
4238                 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype,
4239                         'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype];
4240                 dba::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4241         }
4242
4243         Contact::updateSelfFromUserID(api_user(), true);
4244
4245         // Update global directory in background
4246         $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4247         if ($url && strlen(Config::get('system', 'directory'))) {
4248                 Worker::add(PRIORITY_LOW, "Directory", $url);
4249         }
4250
4251         Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4252
4253         // output for client
4254         if ($data) {
4255                 return api_account_verify_credentials($type);
4256         } else {
4257                 // SaveMediaToDatabase failed for some reason
4258                 throw new InternalServerErrorException("image upload failed");
4259         }
4260 }
4261
4262 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4263 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4264 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4265 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4266 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4267 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4268 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4269 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4270 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4271
4272 /**
4273  * Update user profile
4274  *
4275  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4276  *
4277  * @return array|string
4278  */
4279 function api_account_update_profile($type)
4280 {
4281         $local_user = api_user();
4282         $api_user = api_get_user(get_app());
4283
4284         if (!empty($_POST['name'])) {
4285                 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4286                 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4287                 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4288                 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4289         }
4290
4291         if (isset($_POST['description'])) {
4292                 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4293                 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4294                 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4295         }
4296
4297         Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4298         // Update global directory in background
4299         if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4300                 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4301         }
4302
4303         return api_account_verify_credentials($type);
4304 }
4305
4306 /// @TODO move to top of file or somewhere better
4307 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4308
4309 /**
4310  *
4311  * @param string $acl_string
4312  */
4313 function check_acl_input($acl_string)
4314 {
4315         if ($acl_string == null || $acl_string == " ") {
4316                 return false;
4317         }
4318         $contact_not_found = false;
4319
4320         // split <x><y><z> into array of cid's
4321         preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4322
4323         // check for each cid if it is available on server
4324         $cid_array = $array[0];
4325         foreach ($cid_array as $cid) {
4326                 $cid = str_replace("<", "", $cid);
4327                 $cid = str_replace(">", "", $cid);
4328                 $contact = q(
4329                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4330                         intval($cid),
4331                         intval(api_user())
4332                 );
4333                 $contact_not_found |= !DBM::is_result($contact);
4334         }
4335         return $contact_not_found;
4336 }
4337
4338 /**
4339  *
4340  * @param string  $mediatype
4341  * @param array   $media
4342  * @param string  $type
4343  * @param string  $album
4344  * @param string  $allow_cid
4345  * @param string  $deny_cid
4346  * @param string  $allow_gid
4347  * @param string  $deny_gid
4348  * @param string  $desc
4349  * @param integer $profile
4350  * @param boolean $visibility
4351  * @param string  $photo_id
4352  */
4353 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)
4354 {
4355         $visitor   = 0;
4356         $src = "";
4357         $filetype = "";
4358         $filename = "";
4359         $filesize = 0;
4360
4361         if (is_array($media)) {
4362                 if (is_array($media['tmp_name'])) {
4363                         $src = $media['tmp_name'][0];
4364                 } else {
4365                         $src = $media['tmp_name'];
4366                 }
4367                 if (is_array($media['name'])) {
4368                         $filename = basename($media['name'][0]);
4369                 } else {
4370                         $filename = basename($media['name']);
4371                 }
4372                 if (is_array($media['size'])) {
4373                         $filesize = intval($media['size'][0]);
4374                 } else {
4375                         $filesize = intval($media['size']);
4376                 }
4377                 if (is_array($media['type'])) {
4378                         $filetype = $media['type'][0];
4379                 } else {
4380                         $filetype = $media['type'];
4381                 }
4382         }
4383
4384         if ($filetype == "") {
4385                 $filetype=Image::guessType($filename);
4386         }
4387         $imagedata = getimagesize($src);
4388         if ($imagedata) {
4389                 $filetype = $imagedata['mime'];
4390         }
4391         logger(
4392                 "File upload src: " . $src . " - filename: " . $filename .
4393                 " - size: " . $filesize . " - type: " . $filetype,
4394                 LOGGER_DEBUG
4395         );
4396
4397         // check if there was a php upload error
4398         if ($filesize == 0 && $media['error'] == 1) {
4399                 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4400         }
4401         // check against max upload size within Friendica instance
4402         $maximagesize = Config::get('system', 'maximagesize');
4403         if ($maximagesize && ($filesize > $maximagesize)) {
4404                 $formattedBytes = formatBytes($maximagesize);
4405                 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4406         }
4407
4408         // create Photo instance with the data of the image
4409         $imagedata = @file_get_contents($src);
4410         $Image = new Image($imagedata, $filetype);
4411         if (! $Image->isValid()) {
4412                 throw new InternalServerErrorException("unable to process image data");
4413         }
4414
4415         // check orientation of image
4416         $Image->orient($src);
4417         @unlink($src);
4418
4419         // check max length of images on server
4420         $max_length = Config::get('system', 'max_image_length');
4421         if (! $max_length) {
4422                 $max_length = MAX_IMAGE_LENGTH;
4423         }
4424         if ($max_length > 0) {
4425                 $Image->scaleDown($max_length);
4426                 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4427         }
4428         $width = $Image->getWidth();
4429         $height = $Image->getHeight();
4430
4431         // create a new resource-id if not already provided
4432         $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4433
4434         if ($mediatype == "photo") {
4435                 // upload normal image (scales 0, 1, 2)
4436                 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4437
4438                 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4439                 if (! $r) {
4440                         logger("photo upload: image upload with scale 0 (original size) failed");
4441                 }
4442                 if ($width > 640 || $height > 640) {
4443                         $Image->scaleDown(640);
4444                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4445                         if (! $r) {
4446                                 logger("photo upload: image upload with scale 1 (640x640) failed");
4447                         }
4448                 }
4449
4450                 if ($width > 320 || $height > 320) {
4451                         $Image->scaleDown(320);
4452                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4453                         if (! $r) {
4454                                 logger("photo upload: image upload with scale 2 (320x320) failed");
4455                         }
4456                 }
4457                 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4458         } elseif ($mediatype == "profileimage") {
4459                 // upload profile image (scales 4, 5, 6)
4460                 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4461
4462                 if ($width > 175 || $height > 175) {
4463                         $Image->scaleDown(175);
4464                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4465                         if (! $r) {
4466                                 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4467                         }
4468                 }
4469
4470                 if ($width > 80 || $height > 80) {
4471                         $Image->scaleDown(80);
4472                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4473                         if (! $r) {
4474                                 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4475                         }
4476                 }
4477
4478                 if ($width > 48 || $height > 48) {
4479                         $Image->scaleDown(48);
4480                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4481                         if (! $r) {
4482                                 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4483                         }
4484                 }
4485                 $Image->__destruct();
4486                 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4487         }
4488
4489         if (isset($r) && $r) {
4490                 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4491                 if ($photo_id == null && $mediatype == "photo") {
4492                         post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4493                 }
4494                 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4495                 return prepare_photo_data($type, false, $hash);
4496         } else {
4497                 throw new InternalServerErrorException("image upload failed");
4498         }
4499 }
4500
4501 /**
4502  *
4503  * @param string  $hash
4504  * @param string  $allow_cid
4505  * @param string  $deny_cid
4506  * @param string  $allow_gid
4507  * @param string  $deny_gid
4508  * @param string  $filetype
4509  * @param boolean $visibility
4510  */
4511 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4512 {
4513         // get data about the api authenticated user
4514         $uri = Item::newURI(intval(api_user()));
4515         $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4516
4517         $arr = [];
4518         $arr['guid']          = get_guid(32);
4519         $arr['uid']           = intval(api_user());
4520         $arr['uri']           = $uri;
4521         $arr['parent-uri']    = $uri;
4522         $arr['type']          = 'photo';
4523         $arr['wall']          = 1;
4524         $arr['resource-id']   = $hash;
4525         $arr['contact-id']    = $owner_record[0]['id'];
4526         $arr['owner-name']    = $owner_record[0]['name'];
4527         $arr['owner-link']    = $owner_record[0]['url'];
4528         $arr['owner-avatar']  = $owner_record[0]['thumb'];
4529         $arr['author-name']   = $owner_record[0]['name'];
4530         $arr['author-link']   = $owner_record[0]['url'];
4531         $arr['author-avatar'] = $owner_record[0]['thumb'];
4532         $arr['title']         = "";
4533         $arr['allow_cid']     = $allow_cid;
4534         $arr['allow_gid']     = $allow_gid;
4535         $arr['deny_cid']      = $deny_cid;
4536         $arr['deny_gid']      = $deny_gid;
4537         $arr['visible']       = $visibility;
4538         $arr['origin']        = 1;
4539
4540         $typetoext = [
4541                         'image/jpeg' => 'jpg',
4542                         'image/png' => 'png',
4543                         'image/gif' => 'gif'
4544                         ];
4545
4546         // adds link to the thumbnail scale photo
4547         $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4548                                 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4549                                 . '[/url]';
4550
4551         // do the magic for storing the item in the database and trigger the federation to other contacts
4552         Item::insert($arr);
4553 }
4554
4555 /**
4556  *
4557  * @param string $type
4558  * @param int    $scale
4559  * @param string $photo_id
4560  *
4561  * @return array
4562  */
4563 function prepare_photo_data($type, $scale, $photo_id)
4564 {
4565         $a = get_app();
4566         $user_info = api_get_user($a);
4567
4568         if ($user_info === false) {
4569                 throw new ForbiddenException();
4570         }
4571
4572         $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4573         $data_sql = ($scale === false ? "" : "data, ");
4574
4575         // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4576         // clients needs to convert this in their way for further processing
4577         $r = q(
4578                 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4579                                         `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4580                                         MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4581                         FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4582                 $data_sql,
4583                 intval(local_user()),
4584                 dbesc($photo_id),
4585                 $scale_sql
4586         );
4587
4588         $typetoext = [
4589                 'image/jpeg' => 'jpg',
4590                 'image/png' => 'png',
4591                 'image/gif' => 'gif'
4592         ];
4593
4594         // prepare output data for photo
4595         if (DBM::is_result($r)) {
4596                 $data = ['photo' => $r[0]];
4597                 $data['photo']['id'] = $data['photo']['resource-id'];
4598                 if ($scale !== false) {
4599                         $data['photo']['data'] = base64_encode($data['photo']['data']);
4600                 } else {
4601                         unset($data['photo']['datasize']); //needed only with scale param
4602                 }
4603                 if ($type == "xml") {
4604                         $data['photo']['links'] = [];
4605                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4606                                 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4607                                                                                 "scale" => $k,
4608                                                                                 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4609                         }
4610                 } else {
4611                         $data['photo']['link'] = [];
4612                         // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4613                         $i = 0;
4614                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4615                                 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4616                                 $i++;
4617                         }
4618                 }
4619                 unset($data['photo']['resource-id']);
4620                 unset($data['photo']['minscale']);
4621                 unset($data['photo']['maxscale']);
4622         } else {
4623                 throw new NotFoundException();
4624         }
4625
4626         // retrieve item element for getting activities (like, dislike etc.) related to photo
4627         $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4628         $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4629
4630         $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4631
4632         // retrieve comments on photo
4633         $condition = ["`parent` = ? AND `uid` = ? AND (`verb` = ? OR `type`='photo')",
4634                 $item[0]['parent'], api_user(), ACTIVITY_POST];
4635
4636         $statuses = Item::selectForUser(api_user(), [], $condition);
4637
4638         // prepare output of comments
4639         $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
4640         $comments = [];
4641         if ($type == "xml") {
4642                 $k = 0;
4643                 foreach ($commentData as $comment) {
4644                         $comments[$k++ . ":comment"] = $comment;
4645                 }
4646         } else {
4647                 foreach ($commentData as $comment) {
4648                         $comments[] = $comment;
4649                 }
4650         }
4651         $data['photo']['friendica_comments'] = $comments;
4652
4653         // include info if rights on photo and rights on item are mismatching
4654         $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4655                 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4656                 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4657                 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4658         $data['photo']['rights_mismatch'] = $rights_mismatch;
4659
4660         return $data;
4661 }
4662
4663
4664 /**
4665  * Similar as /mod/redir.php
4666  * redirect to 'url' after dfrn auth
4667  *
4668  * Why this when there is mod/redir.php already?
4669  * This use api_user() and api_login()
4670  *
4671  * params
4672  *              c_url: url of remote contact to auth to
4673  *              url: string, url to redirect after auth
4674  */
4675 function api_friendica_remoteauth()
4676 {
4677         $url = (x($_GET, 'url') ? $_GET['url'] : '');
4678         $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4679
4680         if ($url === '' || $c_url === '') {
4681                 throw new BadRequestException("Wrong parameters.");
4682         }
4683
4684         $c_url = normalise_link($c_url);
4685
4686         // traditional DFRN
4687
4688         $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4689
4690         if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
4691                 throw new BadRequestException("Unknown contact");
4692         }
4693
4694         $cid = $contact['id'];
4695
4696         $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4697
4698         if ($contact['duplex'] && $contact['issued-id']) {
4699                 $orig_id = $contact['issued-id'];
4700                 $dfrn_id = '1:' . $orig_id;
4701         }
4702         if ($contact['duplex'] && $contact['dfrn-id']) {
4703                 $orig_id = $contact['dfrn-id'];
4704                 $dfrn_id = '0:' . $orig_id;
4705         }
4706
4707         $sec = random_string();
4708
4709         $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4710                 'sec' => $sec, 'expire' => time() + 45];
4711         dba::insert('profile_check', $fields);
4712
4713         logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
4714         $dest = ($url ? '&destination_url=' . $url : '');
4715         goaway(
4716                 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4717                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4718                 . '&type=profile&sec=' . $sec . $dest
4719         );
4720 }
4721 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4722
4723 /**
4724  * @brief Return the item shared, if the item contains only the [share] tag
4725  *
4726  * @param array $item Sharer item
4727  * @return array|false Shared item or false if not a reshare
4728  */
4729 function api_share_as_retweet(&$item)
4730 {
4731         $body = trim($item["body"]);
4732
4733         if (Diaspora::isReshare($body, false)===false) {
4734                 return false;
4735         }
4736
4737         /// @TODO "$1" should maybe mean '$1' ?
4738         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4739         /*
4740                 * Skip if there is no shared message in there
4741                 * we already checked this in diaspora::isReshare()
4742                 * but better one more than one less...
4743                 */
4744         if ($body == $attributes) {
4745                 return false;
4746         }
4747
4748
4749         // build the fake reshared item
4750         $reshared_item = $item;
4751
4752         $author = "";
4753         preg_match("/author='(.*?)'/ism", $attributes, $matches);
4754         if ($matches[1] != "") {
4755                 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4756         }
4757
4758         preg_match('/author="(.*?)"/ism', $attributes, $matches);
4759         if ($matches[1] != "") {
4760                 $author = $matches[1];
4761         }
4762
4763         $profile = "";
4764         preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4765         if ($matches[1] != "") {
4766                 $profile = $matches[1];
4767         }
4768
4769         preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4770         if ($matches[1] != "") {
4771                 $profile = $matches[1];
4772         }
4773
4774         $avatar = "";
4775         preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4776         if ($matches[1] != "") {
4777                 $avatar = $matches[1];
4778         }
4779
4780         preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4781         if ($matches[1] != "") {
4782                 $avatar = $matches[1];
4783         }
4784
4785         $link = "";
4786         preg_match("/link='(.*?)'/ism", $attributes, $matches);
4787         if ($matches[1] != "") {
4788                 $link = $matches[1];
4789         }
4790
4791         preg_match('/link="(.*?)"/ism', $attributes, $matches);
4792         if ($matches[1] != "") {
4793                 $link = $matches[1];
4794         }
4795
4796         $posted = "";
4797         preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4798         if ($matches[1] != "") {
4799                 $posted = $matches[1];
4800         }
4801
4802         preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4803         if ($matches[1] != "") {
4804                 $posted = $matches[1];
4805         }
4806
4807         $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4808
4809         if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4810                 return false;
4811         }
4812
4813         $reshared_item["body"] = $shared_body;
4814         $reshared_item["author-name"] = $author;
4815         $reshared_item["author-link"] = $profile;
4816         $reshared_item["author-avatar"] = $avatar;
4817         $reshared_item["plink"] = $link;
4818         $reshared_item["created"] = $posted;
4819         $reshared_item["edited"] = $posted;
4820
4821         return $reshared_item;
4822 }
4823
4824 /**
4825  *
4826  * @param string $profile
4827  *
4828  * @return string|false
4829  * @todo remove trailing junk from profile url
4830  * @todo pump.io check has to check the website
4831  */
4832 function api_get_nick($profile)
4833 {
4834         $nick = "";
4835
4836         $r = q(
4837                 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4838                 dbesc(normalise_link($profile))
4839         );
4840
4841         if (DBM::is_result($r)) {
4842                 $nick = $r[0]["nick"];
4843         }
4844
4845         if (!$nick == "") {
4846                 $r = q(
4847                         "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4848                         dbesc(normalise_link($profile))
4849                 );
4850
4851                 if (DBM::is_result($r)) {
4852                         $nick = $r[0]["nick"];
4853                 }
4854         }
4855
4856         if (!$nick == "") {
4857                 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4858                 if ($friendica != $profile) {
4859                         $nick = $friendica;
4860                 }
4861         }
4862
4863         if (!$nick == "") {
4864                 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4865                 if ($diaspora != $profile) {
4866                         $nick = $diaspora;
4867                 }
4868         }
4869
4870         if (!$nick == "") {
4871                 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4872                 if ($twitter != $profile) {
4873                         $nick = $twitter;
4874                 }
4875         }
4876
4877
4878         if (!$nick == "") {
4879                 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4880                 if ($StatusnetHost != $profile) {
4881                         $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4882                         if ($StatusnetUser != $profile) {
4883                                 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4884                                 $user = json_decode($UserData);
4885                                 if ($user) {
4886                                         $nick = $user->screen_name;
4887                                 }
4888                         }
4889                 }
4890         }
4891
4892         // To-Do: look at the page if its really a pumpio site
4893         //if (!$nick == "") {
4894         //      $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4895         //      if ($pumpio != $profile)
4896         //              $nick = $pumpio;
4897                 //      <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4898
4899         //}
4900
4901         if ($nick != "") {
4902                 return $nick;
4903         }
4904
4905         return false;
4906 }
4907
4908 /**
4909  *
4910  * @param array $item
4911  *
4912  * @return array
4913  */
4914 function api_in_reply_to($item)
4915 {
4916         $in_reply_to = [];
4917
4918         $in_reply_to['status_id'] = null;
4919         $in_reply_to['user_id'] = null;
4920         $in_reply_to['status_id_str'] = null;
4921         $in_reply_to['user_id_str'] = null;
4922         $in_reply_to['screen_name'] = null;
4923
4924         if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4925                 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
4926                 if (DBM::is_result($parent)) {
4927                         $in_reply_to['status_id'] = intval($parent['id']);
4928                 } else {
4929                         $in_reply_to['status_id'] = intval($item['parent']);
4930                 }
4931
4932                 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4933
4934                 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
4935                 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
4936
4937                 if (DBM::is_result($parent)) {
4938                         if ($parent['author-nick'] == "") {
4939                                 $parent['author-nick'] = api_get_nick($parent['author-link']);
4940                         }
4941
4942                         $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
4943                         $in_reply_to['user_id'] = intval($parent['author-id']);
4944                         $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
4945                 }
4946
4947                 // There seems to be situation, where both fields are identical:
4948                 // https://github.com/friendica/friendica/issues/1010
4949                 // This is a bugfix for that.
4950                 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4951                         logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4952                         $in_reply_to['status_id'] = null;
4953                         $in_reply_to['user_id'] = null;
4954                         $in_reply_to['status_id_str'] = null;
4955                         $in_reply_to['user_id_str'] = null;
4956                         $in_reply_to['screen_name'] = null;
4957                 }
4958         }
4959
4960         return $in_reply_to;
4961 }
4962
4963 /**
4964  *
4965  * @param string $text
4966  *
4967  * @return string
4968  */
4969 function api_clean_plain_items($text)
4970 {
4971         $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4972
4973         $text = BBCode::cleanPictureLinks($text);
4974         $URLSearchString = "^\[\]";
4975
4976         $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4977
4978         if ($include_entities == "true") {
4979                 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4980         }
4981
4982         // Simplify "attachment" element
4983         $text = api_clean_attachments($text);
4984
4985         return $text;
4986 }
4987
4988 /**
4989  * @brief Removes most sharing information for API text export
4990  *
4991  * @param string $body The original body
4992  *
4993  * @return string Cleaned body
4994  */
4995 function api_clean_attachments($body)
4996 {
4997         $data = BBCode::getAttachmentData($body);
4998
4999         if (empty($data)) {
5000                 return $body;
5001         }
5002         $body = "";
5003
5004         if (isset($data["text"])) {
5005                 $body = $data["text"];
5006         }
5007         if (($body == "") && isset($data["title"])) {
5008                 $body = $data["title"];
5009         }
5010         if (isset($data["url"])) {
5011                 $body .= "\n".$data["url"];
5012         }
5013         $body .= $data["after"];
5014
5015         return $body;
5016 }
5017
5018 /**
5019  *
5020  * @param array $contacts
5021  *
5022  * @return array
5023  */
5024 function api_best_nickname(&$contacts)
5025 {
5026         $best_contact = [];
5027
5028         if (count($contacts) == 0) {
5029                 return;
5030         }
5031
5032         foreach ($contacts as $contact) {
5033                 if ($contact["network"] == "") {
5034                         $contact["network"] = "dfrn";
5035                         $best_contact = [$contact];
5036                 }
5037         }
5038
5039         if (sizeof($best_contact) == 0) {
5040                 foreach ($contacts as $contact) {
5041                         if ($contact["network"] == "dfrn") {
5042                                 $best_contact = [$contact];
5043                         }
5044                 }
5045         }
5046
5047         if (sizeof($best_contact) == 0) {
5048                 foreach ($contacts as $contact) {
5049                         if ($contact["network"] == "dspr") {
5050                                 $best_contact = [$contact];
5051                         }
5052                 }
5053         }
5054
5055         if (sizeof($best_contact) == 0) {
5056                 foreach ($contacts as $contact) {
5057                         if ($contact["network"] == "stat") {
5058                                 $best_contact = [$contact];
5059                         }
5060                 }
5061         }
5062
5063         if (sizeof($best_contact) == 0) {
5064                 foreach ($contacts as $contact) {
5065                         if ($contact["network"] == "pump") {
5066                                 $best_contact = [$contact];
5067                         }
5068                 }
5069         }
5070
5071         if (sizeof($best_contact) == 0) {
5072                 foreach ($contacts as $contact) {
5073                         if ($contact["network"] == "twit") {
5074                                 $best_contact = [$contact];
5075                         }
5076                 }
5077         }
5078
5079         if (sizeof($best_contact) == 1) {
5080                 $contacts = $best_contact;
5081         } else {
5082                 $contacts = [$contacts[0]];
5083         }
5084 }
5085
5086 /**
5087  * Return all or a specified group of the user with the containing contacts.
5088  *
5089  * @param string $type Return type (atom, rss, xml, json)
5090  *
5091  * @return array|string
5092  */
5093 function api_friendica_group_show($type)
5094 {
5095         $a = get_app();
5096
5097         if (api_user() === false) {
5098                 throw new ForbiddenException();
5099         }
5100
5101         // params
5102         $user_info = api_get_user($a);
5103         $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5104         $uid = $user_info['uid'];
5105
5106         // get data of the specified group id or all groups if not specified
5107         if ($gid != 0) {
5108                 $r = q(
5109                         "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5110                         intval($uid),
5111                         intval($gid)
5112                 );
5113                 // error message if specified gid is not in database
5114                 if (!DBM::is_result($r)) {
5115                         throw new BadRequestException("gid not available");
5116                 }
5117         } else {
5118                 $r = q(
5119                         "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5120                         intval($uid)
5121                 );
5122         }
5123
5124         // loop through all groups and retrieve all members for adding data in the user array
5125         $grps = [];
5126         foreach ($r as $rr) {
5127                 $members = Contact::getByGroupId($rr['id']);
5128                 $users = [];
5129
5130                 if ($type == "xml") {
5131                         $user_element = "users";
5132                         $k = 0;
5133                         foreach ($members as $member) {
5134                                 $user = api_get_user($a, $member['nurl']);
5135                                 $users[$k++.":user"] = $user;
5136                         }
5137                 } else {
5138                         $user_element = "user";
5139                         foreach ($members as $member) {
5140                                 $user = api_get_user($a, $member['nurl']);
5141                                 $users[] = $user;
5142                         }
5143                 }
5144                 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5145         }
5146         return api_format_data("groups", $type, ['group' => $grps]);
5147 }
5148 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5149
5150
5151 /**
5152  * Delete the specified group of the user.
5153  *
5154  * @param string $type Return type (atom, rss, xml, json)
5155  *
5156  * @return array|string
5157  */
5158 function api_friendica_group_delete($type)
5159 {
5160         $a = get_app();
5161
5162         if (api_user() === false) {
5163                 throw new ForbiddenException();
5164         }
5165
5166         // params
5167         $user_info = api_get_user($a);
5168         $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5169         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5170         $uid = $user_info['uid'];
5171
5172         // error if no gid specified
5173         if ($gid == 0 || $name == "") {
5174                 throw new BadRequestException('gid or name not specified');
5175         }
5176
5177         // get data of the specified group id
5178         $r = q(
5179                 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5180                 intval($uid),
5181                 intval($gid)
5182         );
5183         // error message if specified gid is not in database
5184         if (!DBM::is_result($r)) {
5185                 throw new BadRequestException('gid not available');
5186         }
5187
5188         // get data of the specified group id and group name
5189         $rname = q(
5190                 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5191                 intval($uid),
5192                 intval($gid),
5193                 dbesc($name)
5194         );
5195         // error message if specified gid is not in database
5196         if (!DBM::is_result($rname)) {
5197                 throw new BadRequestException('wrong group name');
5198         }
5199
5200         // delete group
5201         $ret = Group::removeByName($uid, $name);
5202         if ($ret) {
5203                 // return success
5204                 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5205                 return api_format_data("group_delete", $type, ['result' => $success]);
5206         } else {
5207                 throw new BadRequestException('other API error');
5208         }
5209 }
5210 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5211
5212 /**
5213  * Delete a group.
5214  *
5215  * @param string $type Return type (atom, rss, xml, json)
5216  *
5217  * @return array|string
5218  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5219  */
5220 function api_lists_destroy($type)
5221 {
5222         $a = get_app();
5223
5224         if (api_user() === false) {
5225                 throw new ForbiddenException();
5226         }
5227
5228         // params
5229         $user_info = api_get_user($a);
5230         $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5231         $uid = $user_info['uid'];
5232
5233         // error if no gid specified
5234         if ($gid == 0) {
5235                 throw new BadRequestException('gid not specified');
5236         }
5237
5238         // get data of the specified group id
5239         $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5240         // error message if specified gid is not in database
5241         if (!$group) {
5242                 throw new BadRequestException('gid not available');
5243         }
5244
5245         if (Group::remove($gid)) {
5246                 $list = [
5247                         'name' => $group['name'],
5248                         'id' => intval($gid),
5249                         'id_str' => (string) $gid,
5250                         'user' => $user_info
5251                 ];
5252
5253                 return api_format_data("lists", $type, ['lists' => $list]);
5254         }
5255 }
5256 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5257
5258 /**
5259  * Add a new group to the database.
5260  *
5261  * @param  string $name  Group name
5262  * @param  int    $uid   User ID
5263  * @param  array  $users List of users to add to the group
5264  *
5265  * @return array
5266  */
5267 function group_create($name, $uid, $users = [])
5268 {
5269         // error if no name specified
5270         if ($name == "") {
5271                 throw new BadRequestException('group name not specified');
5272         }
5273
5274         // get data of the specified group name
5275         $rname = q(
5276                 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5277                 intval($uid),
5278                 dbesc($name)
5279         );
5280         // error message if specified group name already exists
5281         if (DBM::is_result($rname)) {
5282                 throw new BadRequestException('group name already exists');
5283         }
5284
5285         // check if specified group name is a deleted group
5286         $rname = q(
5287                 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5288                 intval($uid),
5289                 dbesc($name)
5290         );
5291         // error message if specified group name already exists
5292         if (DBM::is_result($rname)) {
5293                 $reactivate_group = true;
5294         }
5295
5296         // create group
5297         $ret = Group::create($uid, $name);
5298         if ($ret) {
5299                 $gid = Group::getIdByName($uid, $name);
5300         } else {
5301                 throw new BadRequestException('other API error');
5302         }
5303
5304         // add members
5305         $erroraddinguser = false;
5306         $errorusers = [];
5307         foreach ($users as $user) {
5308                 $cid = $user['cid'];
5309                 // check if user really exists as contact
5310                 $contact = q(
5311                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5312                         intval($cid),
5313                         intval($uid)
5314                 );
5315                 if (count($contact)) {
5316                         Group::addMember($gid, $cid);
5317                 } else {
5318                         $erroraddinguser = true;
5319                         $errorusers[] = $cid;
5320                 }
5321         }
5322
5323         // return success message incl. missing users in array
5324         $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5325
5326         return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5327 }
5328
5329 /**
5330  * Create the specified group with the posted array of contacts.
5331  *
5332  * @param string $type Return type (atom, rss, xml, json)
5333  *
5334  * @return array|string
5335  */
5336 function api_friendica_group_create($type)
5337 {
5338         $a = get_app();
5339
5340         if (api_user() === false) {
5341                 throw new ForbiddenException();
5342         }
5343
5344         // params
5345         $user_info = api_get_user($a);
5346         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5347         $uid = $user_info['uid'];
5348         $json = json_decode($_POST['json'], true);
5349         $users = $json['user'];
5350
5351         $success = group_create($name, $uid, $users);
5352
5353         return api_format_data("group_create", $type, ['result' => $success]);
5354 }
5355 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5356
5357 /**
5358  * Create a new group.
5359  *
5360  * @param string $type Return type (atom, rss, xml, json)
5361  *
5362  * @return array|string
5363  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5364  */
5365 function api_lists_create($type)
5366 {
5367         $a = get_app();
5368
5369         if (api_user() === false) {
5370                 throw new ForbiddenException();
5371         }
5372
5373         // params
5374         $user_info = api_get_user($a);
5375         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5376         $uid = $user_info['uid'];
5377
5378         $success = group_create($name, $uid);
5379         if ($success['success']) {
5380                 $grp = [
5381                         'name' => $success['name'],
5382                         'id' => intval($success['gid']),
5383                         'id_str' => (string) $success['gid'],
5384                         'user' => $user_info
5385                 ];
5386
5387                 return api_format_data("lists", $type, ['lists'=>$grp]);
5388         }
5389 }
5390 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5391
5392 /**
5393  * Update the specified group with the posted array of contacts.
5394  *
5395  * @param string $type Return type (atom, rss, xml, json)
5396  *
5397  * @return array|string
5398  */
5399 function api_friendica_group_update($type)
5400 {
5401         $a = get_app();
5402
5403         if (api_user() === false) {
5404                 throw new ForbiddenException();
5405         }
5406
5407         // params
5408         $user_info = api_get_user($a);
5409         $uid = $user_info['uid'];
5410         $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5411         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5412         $json = json_decode($_POST['json'], true);
5413         $users = $json['user'];
5414
5415         // error if no name specified
5416         if ($name == "") {
5417                 throw new BadRequestException('group name not specified');
5418         }
5419
5420         // error if no gid specified
5421         if ($gid == "") {
5422                 throw new BadRequestException('gid not specified');
5423         }
5424
5425         // remove members
5426         $members = Contact::getByGroupId($gid);
5427         foreach ($members as $member) {
5428                 $cid = $member['id'];
5429                 foreach ($users as $user) {
5430                         $found = ($user['cid'] == $cid ? true : false);
5431                 }
5432                 if (!isset($found) || !$found) {
5433                         Group::removeMemberByName($uid, $name, $cid);
5434                 }
5435         }
5436
5437         // add members
5438         $erroraddinguser = false;
5439         $errorusers = [];
5440         foreach ($users as $user) {
5441                 $cid = $user['cid'];
5442                 // check if user really exists as contact
5443                 $contact = q(
5444                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5445                         intval($cid),
5446                         intval($uid)
5447                 );
5448
5449                 if (count($contact)) {
5450                         Group::addMember($gid, $cid);
5451                 } else {
5452                         $erroraddinguser = true;
5453                         $errorusers[] = $cid;
5454                 }
5455         }
5456
5457         // return success message incl. missing users in array
5458         $status = ($erroraddinguser ? "missing user" : "ok");
5459         $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5460         return api_format_data("group_update", $type, ['result' => $success]);
5461 }
5462
5463 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5464
5465 /**
5466  * Update information about a group.
5467  *
5468  * @param string $type Return type (atom, rss, xml, json)
5469  *
5470  * @return array|string
5471  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5472  */
5473 function api_lists_update($type)
5474 {
5475         $a = get_app();
5476
5477         if (api_user() === false) {
5478                 throw new ForbiddenException();
5479         }
5480
5481         // params
5482         $user_info = api_get_user($a);
5483         $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
5484         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5485         $uid = $user_info['uid'];
5486
5487         // error if no gid specified
5488         if ($gid == 0) {
5489                 throw new BadRequestException('gid not specified');
5490         }
5491
5492         // get data of the specified group id
5493         $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5494         // error message if specified gid is not in database
5495         if (!$group) {
5496                 throw new BadRequestException('gid not available');
5497         }
5498
5499         if (Group::update($gid, $name)) {
5500                 $list = [
5501                         'name' => $name,
5502                         'id' => intval($gid),
5503                         'id_str' => (string) $gid,
5504                         'user' => $user_info
5505                 ];
5506
5507                 return api_format_data("lists", $type, ['lists' => $list]);
5508         }
5509 }
5510
5511 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5512
5513 /**
5514  *
5515  * @param string $type Return type (atom, rss, xml, json)
5516  *
5517  * @return array|string
5518  */
5519 function api_friendica_activity($type)
5520 {
5521         $a = get_app();
5522
5523         if (api_user() === false) {
5524                 throw new ForbiddenException();
5525         }
5526         $verb = strtolower($a->argv[3]);
5527         $verb = preg_replace("|\..*$|", "", $verb);
5528
5529         $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5530
5531         $res = Item::performLike($id, $verb);
5532
5533         if ($res) {
5534                 if ($type == "xml") {
5535                         $ok = "true";
5536                 } else {
5537                         $ok = "ok";
5538                 }
5539                 return api_format_data('ok', $type, ['ok' => $ok]);
5540         } else {
5541                 throw new BadRequestException('Error adding activity');
5542         }
5543 }
5544
5545 /// @TODO move to top of file or somewhere better
5546 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5547 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5548 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5549 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5550 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5551 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5552 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5553 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5554 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5555 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5556
5557 /**
5558  * @brief Returns notifications
5559  *
5560  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5561  * @return string|array
5562 */
5563 function api_friendica_notification($type)
5564 {
5565         $a = get_app();
5566
5567         if (api_user() === false) {
5568                 throw new ForbiddenException();
5569         }
5570         if ($a->argc!==3) {
5571                 throw new BadRequestException("Invalid argument count");
5572         }
5573         $nm = new NotificationsManager();
5574
5575         $notes = $nm->getAll([], "+seen -date", 50);
5576
5577         if ($type == "xml") {
5578                 $xmlnotes = [];
5579                 foreach ($notes as $note) {
5580                         $xmlnotes[] = ["@attributes" => $note];
5581                 }
5582
5583                 $notes = $xmlnotes;
5584         }
5585
5586         return api_format_data("notes", $type, ['note' => $notes]);
5587 }
5588
5589 /**
5590  * POST request with 'id' param as notification id
5591  *
5592  * @brief Set notification as seen and returns associated item (if possible)
5593  *
5594  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5595  * @return string|array
5596  */
5597 function api_friendica_notification_seen($type)
5598 {
5599         $a = get_app();
5600         $user_info = api_get_user($a);
5601
5602         if (api_user() === false || $user_info === false) {
5603                 throw new ForbiddenException();
5604         }
5605         if ($a->argc!==4) {
5606                 throw new BadRequestException("Invalid argument count");
5607         }
5608
5609         $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5610
5611         $nm = new NotificationsManager();
5612         $note = $nm->getByID($id);
5613         if (is_null($note)) {
5614                 throw new BadRequestException("Invalid argument");
5615         }
5616
5617         $nm->setSeen($note);
5618         if ($note['otype']=='item') {
5619                 // would be really better with an ItemsManager and $im->getByID() :-P
5620                 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5621                 if (DBM::is_result($$item)) {
5622                         // we found the item, return it to the user
5623                         $ret = api_format_items([$item], $user_info, false, $type);
5624                         $data = ['status' => $ret];
5625                         return api_format_data("status", $type, $data);
5626                 }
5627                 // the item can't be found, but we set the note as seen, so we count this as a success
5628         }
5629         return api_format_data('result', $type, ['result' => "success"]);
5630 }
5631
5632 /// @TODO move to top of file or somewhere better
5633 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5634 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5635
5636 /**
5637  * @brief update a direct_message to seen state
5638  *
5639  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5640  * @return string|array (success result=ok, error result=error with error message)
5641  */
5642 function api_friendica_direct_messages_setseen($type)
5643 {
5644         $a = get_app();
5645         if (api_user() === false) {
5646                 throw new ForbiddenException();
5647         }
5648
5649         // params
5650         $user_info = api_get_user($a);
5651         $uid = $user_info['uid'];
5652         $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5653
5654         // return error if id is zero
5655         if ($id == "") {
5656                 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5657                 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5658         }
5659
5660         // error message if specified id is not in database
5661         if (!dba::exists('mail', ['id' => $id, 'uid' => $uid])) {
5662                 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5663                 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5664         }
5665
5666         // update seen indicator
5667         $result = dba::update('mail', ['seen' => true], ['id' => $id]);
5668
5669         if ($result) {
5670                 // return success
5671                 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5672                 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5673         } else {
5674                 $answer = ['result' => 'error', 'message' => 'unknown error'];
5675                 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5676         }
5677 }
5678
5679 /// @TODO move to top of file or somewhere better
5680 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5681
5682 /**
5683  * @brief search for direct_messages containing a searchstring through api
5684  *
5685  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5686  * @param string $box
5687  * @return string|array (success: success=true if found and search_result contains found messages,
5688  *                          success=false if nothing was found, search_result='nothing found',
5689  *                 error: result=error with error message)
5690  */
5691 function api_friendica_direct_messages_search($type, $box = "")
5692 {
5693         $a = get_app();
5694
5695         if (api_user() === false) {
5696                 throw new ForbiddenException();
5697         }
5698
5699         // params
5700         $user_info = api_get_user($a);
5701         $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5702         $uid = $user_info['uid'];
5703
5704         // error if no searchstring specified
5705         if ($searchstring == "") {
5706                 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5707                 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5708         }
5709
5710         // get data for the specified searchstring
5711         $r = q(
5712                 "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",
5713                 intval($uid),
5714                 dbesc('%'.$searchstring.'%')
5715         );
5716
5717         $profile_url = $user_info["url"];
5718
5719         // message if nothing was found
5720         if (!DBM::is_result($r)) {
5721                 $success = ['success' => false, 'search_results' => 'problem with query'];
5722         } elseif (count($r) == 0) {
5723                 $success = ['success' => false, 'search_results' => 'nothing found'];
5724         } else {
5725                 $ret = [];
5726                 foreach ($r as $item) {
5727                         if ($box == "inbox" || $item['from-url'] != $profile_url) {
5728                                 $recipient = $user_info;
5729                                 $sender = api_get_user($a, normalise_link($item['contact-url']));
5730                         } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5731                                 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5732                                 $sender = $user_info;
5733                         }
5734
5735                         if (isset($recipient) && isset($sender)) {
5736                                 $ret[] = api_format_messages($item, $recipient, $sender);
5737                         }
5738                 }
5739                 $success = ['success' => true, 'search_results' => $ret];
5740         }
5741
5742         return api_format_data("direct_message_search", $type, ['$result' => $success]);
5743 }
5744
5745 /// @TODO move to top of file or somewhere better
5746 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5747
5748 /**
5749  * @brief return data of all the profiles a user has to the client
5750  *
5751  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5752  * @return string|array
5753  */
5754 function api_friendica_profile_show($type)
5755 {
5756         $a = get_app();
5757
5758         if (api_user() === false) {
5759                 throw new ForbiddenException();
5760         }
5761
5762         // input params
5763         $profile_id = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5764
5765         // retrieve general information about profiles for user
5766         $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5767         $directory = Config::get('system', 'directory');
5768
5769         // get data of the specified profile id or all profiles of the user if not specified
5770         if ($profile_id != 0) {
5771                 $r = q(
5772                         "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5773                         intval(api_user()),
5774                         intval($profile_id)
5775                 );
5776
5777                 // error message if specified gid is not in database
5778                 if (!DBM::is_result($r)) {
5779                         throw new BadRequestException("profile_id not available");
5780                 }
5781         } else {
5782                 $r = q(
5783                         "SELECT * FROM `profile` WHERE `uid` = %d",
5784                         intval(api_user())
5785                 );
5786         }
5787         // loop through all returned profiles and retrieve data and users
5788         $k = 0;
5789         $profiles = [];
5790         foreach ($r as $rr) {
5791                 $profile = api_format_items_profiles($rr);
5792
5793                 // select all users from contact table, loop and prepare standard return for user data
5794                 $users = [];
5795                 $nurls = q(
5796                         "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5797                         intval(api_user()),
5798                         intval($rr['profile_id'])
5799                 );
5800
5801                 foreach ($nurls as $nurl) {
5802                         $user = api_get_user($a, $nurl['nurl']);
5803                         ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5804                 }
5805                 $profile['users'] = $users;
5806
5807                 // add prepared profile data to array for final return
5808                 if ($type == "xml") {
5809                         $profiles[$k++ . ":profile"] = $profile;
5810                 } else {
5811                         $profiles[] = $profile;
5812                 }
5813         }
5814
5815         // return settings, authenticated user and profiles data
5816         $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5817
5818         $result = ['multi_profiles' => $multi_profiles ? true : false,
5819                                         'global_dir' => $directory,
5820                                         'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5821                                         'profiles' => $profiles];
5822         return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5823 }
5824 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5825
5826 /**
5827  * Returns a list of saved searches.
5828  *
5829  * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5830  *
5831  * @param  string $type Return format: json or xml
5832  *
5833  * @return string|array
5834  */
5835 function api_saved_searches_list($type)
5836 {
5837         $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
5838
5839         $result = [];
5840         while ($term = $terms->fetch()) {
5841                 $result[] = [
5842                         'created_at' => api_date(time()),
5843                         'id' => intval($term['id']),
5844                         'id_str' => $term['id'],
5845                         'name' => $term['term'],
5846                         'position' => null,
5847                         'query' => $term['term']
5848                 ];
5849         }
5850
5851         dba::close($terms);
5852
5853         return api_format_data("terms", $type, ['terms' => $result]);
5854 }
5855
5856 /// @TODO move to top of file or somewhere better
5857 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5858
5859 /*
5860 @TODO Maybe open to implement?
5861 To.Do:
5862         [pagename] => api/1.1/statuses/lookup.json
5863         [id] => 605138389168451584
5864         [include_cards] => true
5865         [cards_platform] => Android-12
5866         [include_entities] => true
5867         [include_my_retweet] => 1
5868         [include_rts] => 1
5869         [include_reply_count] => true
5870         [include_descendent_reply_count] => true
5871 (?)
5872
5873
5874 Not implemented by now:
5875 statuses/retweets_of_me
5876 friendships/create
5877 friendships/destroy
5878 friendships/exists
5879 friendships/show
5880 account/update_location
5881 account/update_profile_background_image
5882 blocks/create
5883 blocks/destroy
5884 friendica/profile/update
5885 friendica/profile/create
5886 friendica/profile/delete
5887
5888 Not implemented in status.net:
5889 statuses/retweeted_to_me
5890 statuses/retweeted_by_me
5891 direct_messages/destroy
5892 account/end_session
5893 account/update_delivery_device
5894 notifications/follow
5895 notifications/leave
5896 blocks/exists
5897 blocks/blocking
5898 lists
5899 */