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