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