]> git.mxchange.org Git - friendica.git/blob - include/api.php
Split the name in the hcard
[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 UnauthorizedException
1529  * @throws NotFoundException
1530  */
1531 function api_users_lookup($type)
1532 {
1533         $users = array();
1534
1535         if (x($_REQUEST['user_id'])) {
1536                 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1537                         if (!empty($id)) {
1538                                 $users[] = api_get_user(get_app(), $id);
1539                         }
1540                 }
1541         }
1542
1543         if (empty($users)) {
1544                 throw new NotFoundException;
1545         }
1546
1547         return api_format_data("users", $type, array('users' => $users));
1548 }
1549
1550 /// @TODO move to top of file or somewhere better
1551 api_register_func('api/users/lookup', 'api_users_lookup', true);
1552
1553 /**
1554  * Returns statuses that match a specified query.
1555  *
1556  * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1557  *
1558  * @param string $type Return format: json, xml, atom, rss
1559  *
1560  * @return array|string
1561  * @throws UnauthorizedException
1562  * @throws BadRequestException
1563  */
1564 function api_search($type)
1565 {
1566         $data = array();
1567
1568         if (!x($_REQUEST, 'q')) {
1569                 throw new BadRequestException("q parameter is required.");
1570         }
1571
1572         if (x($_REQUEST, 'rpp')) {
1573                 $count = $_REQUEST['rpp'];
1574         } elseif (x($_REQUEST, 'count')) {
1575                 $count = $_REQUEST['count'];
1576         } else {
1577                 $count = 15;
1578         }
1579
1580         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1581         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1582         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1583
1584         $start = $page * $count;
1585
1586         if ($max_id > 0) {
1587                 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1588         }
1589
1590         $r = dba::p(
1591                 "SELECT ".item_fieldlists()."
1592                 FROM `item` ".item_joins()."
1593                 WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1594                 AND `item`.`body` LIKE CONCAT('%',?,'%')
1595                 $sql_extra
1596                 AND `item`.`id`>?
1597                 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
1598                 api_user(),
1599                 $_REQUEST['q'],
1600                 $since_id
1601         );
1602
1603         $data['status'] = api_format_items(dba::inArray($r), api_get_user(get_app()));
1604
1605         return api_format_data("statuses", $type, $data);
1606 }
1607
1608 /// @TODO move to top of file or somewhere better
1609 api_register_func('api/search/tweets', 'api_search', true);
1610 api_register_func('api/search', 'api_search', true);
1611
1612 /**
1613  *
1614  * http://developer.twitter.com/doc/get/statuses/home_timeline
1615  *
1616  * TODO: Optional parameters
1617  * TODO: Add reply info
1618  */
1619 function api_statuses_home_timeline($type)
1620 {
1621         $a = get_app();
1622
1623         if (api_user() === false) {
1624                 throw new ForbiddenException();
1625         }
1626
1627         unset($_REQUEST["user_id"]);
1628         unset($_GET["user_id"]);
1629
1630         unset($_REQUEST["screen_name"]);
1631         unset($_GET["screen_name"]);
1632
1633         $user_info = api_get_user($a);
1634         // get last newtork messages
1635
1636         // params
1637         $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1638         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1639         if ($page < 0) {
1640                 $page = 0;
1641         }
1642         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1643         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1644         //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1645         $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1646         $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1647
1648         $start = $page * $count;
1649
1650         $sql_extra = '';
1651         if ($max_id > 0) {
1652                 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1653         }
1654         if ($exclude_replies > 0) {
1655                 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1656         }
1657         if ($conversation_id > 0) {
1658                 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1659         }
1660
1661         $r = q(
1662                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1663                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1664                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1665                 `contact`.`id` AS `cid`
1666                 FROM `item`
1667                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1668                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1669                 WHERE `item`.`uid` = %d AND `verb` = '%s'
1670                 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1671                 $sql_extra
1672                 AND `item`.`id`>%d
1673                 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1674                 intval(api_user()),
1675                 dbesc(ACTIVITY_POST),
1676                 intval($since_id),
1677                 intval($start),
1678                 intval($count)
1679         );
1680
1681         $ret = api_format_items($r, $user_info, false, $type);
1682
1683         // Set all posts from the query above to seen
1684         $idarray = array();
1685         foreach ($r as $item) {
1686                 $idarray[] = intval($item["id"]);
1687         }
1688
1689         $idlist = implode(",", $idarray);
1690
1691         if ($idlist != "") {
1692                 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1693
1694                 if ($unseen) {
1695                         $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1696                 }
1697         }
1698
1699         $data = array('status' => $ret);
1700         switch ($type) {
1701                 case "atom":
1702                 case "rss":
1703                         $data = api_rss_extra($a, $data, $user_info);
1704                         break;
1705         }
1706
1707         return api_format_data("statuses", $type, $data);
1708 }
1709
1710 /// @TODO move to top of file or somewhere better
1711 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1712 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1713
1714 function api_statuses_public_timeline($type)
1715 {
1716         $a = get_app();
1717
1718         if (api_user() === false) {
1719                 throw new ForbiddenException();
1720         }
1721
1722         $user_info = api_get_user($a);
1723         // get last newtork messages
1724
1725         // params
1726         $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1727         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1728         if ($page < 0) {
1729                 $page = 0;
1730         }
1731         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1732         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1733         //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1734         $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1735         $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1736
1737         $start = $page * $count;
1738
1739         if ($exclude_replies && !$conversation_id) {
1740                 if ($max_id > 0) {
1741                         $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1742                 }
1743
1744                 $r = dba::p("SELECT " . item_fieldlists() . "
1745                         FROM `thread`
1746                         STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1747                         " . item_joins() . "
1748                         STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1749                                 AND NOT `user`.`hidewall`
1750                         AND `verb` = ?
1751                         AND NOT `thread`.`private`
1752                         AND `thread`.`wall`
1753                         AND `thread`.`visible`
1754                         AND NOT `thread`.`deleted`
1755                         AND NOT `thread`.`moderated`
1756                         AND `thread`.`iid` > ?
1757                         $sql_extra
1758                         ORDER BY `thread`.`iid` DESC
1759                         LIMIT " . intval($start) . ", " . intval($count),
1760                         ACTIVITY_POST,
1761                         $since_id
1762                 );
1763
1764                 $r = dba::inArray($r);
1765         } else {
1766                 if ($max_id > 0) {
1767                         $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1768                 }
1769                 if ($conversation_id > 0) {
1770                         $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1771                 }
1772
1773                 $r = dba::p("SELECT " . item_fieldlists() . "
1774                         FROM `item`
1775                         " . item_joins() . "
1776                         STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1777                                 AND NOT `user`.`hidewall`
1778                         AND `verb` = ?
1779                         AND NOT `item`.`private`
1780                         AND `item`.`wall`
1781                         AND `item`.`visible`
1782                         AND NOT `item`.`deleted`
1783                         AND NOT `item`.`moderated`
1784                         AND `item`.`id` > ?
1785                         $sql_extra
1786                         ORDER BY `item`.`id` DESC
1787                         LIMIT " . intval($start) . ", " . intval($count),
1788                         ACTIVITY_POST,
1789                         $since_id
1790                 );
1791
1792                 $r = dba::inArray($r);
1793         }
1794
1795         $ret = api_format_items($r, $user_info, false, $type);
1796
1797         $data = array('status' => $ret);
1798         switch ($type) {
1799                 case "atom":
1800                 case "rss":
1801                         $data = api_rss_extra($a, $data, $user_info);
1802                         break;
1803         }
1804
1805         return api_format_data("statuses", $type, $data);
1806 }
1807
1808 /// @TODO move to top of file or somewhere better
1809 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1810
1811 /**
1812  * @brief Returns the list of public federated posts this node knows about
1813  *
1814  * @param string $type Return format: json, xml, atom, rss
1815  * @return array|string
1816  * @throws ForbiddenException
1817  */
1818 function api_statuses_networkpublic_timeline($type)
1819 {
1820         $a = get_app();
1821
1822         if (api_user() === false) {
1823                 throw new ForbiddenException();
1824         }
1825
1826         $user_info = api_get_user($a);
1827
1828         $since_id        = x($_REQUEST, 'since_id')        ? $_REQUEST['since_id']        : 0;
1829         $max_id          = x($_REQUEST, 'max_id')          ? $_REQUEST['max_id']          : 0;
1830
1831         // pagination
1832         $count = x($_REQUEST, 'count') ? $_REQUEST['count']   : 20;
1833         $page  = x($_REQUEST, 'page')  ? $_REQUEST['page']    : 1;
1834         if ($page < 1) {
1835                 $page = 1;
1836         }
1837         $start = ($page - 1) * $count;
1838
1839         $sql_extra = '';
1840         if ($max_id > 0) {
1841                 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1842         }
1843
1844         $r = dba::p("SELECT " . item_fieldlists() . "
1845                 FROM `thread`
1846                 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1847                 " . item_joins() . "
1848                 WHERE `thread`.`uid` = 0
1849                 AND `verb` = ?
1850                 AND NOT `thread`.`private`
1851                 AND `thread`.`visible`
1852                 AND NOT `thread`.`deleted`
1853                 AND NOT `thread`.`moderated`
1854                 AND `thread`.`iid` > ?
1855                 $sql_extra
1856                 ORDER BY `thread`.`iid` DESC
1857                 LIMIT " . intval($start) . ", " . intval($count),
1858                 ACTIVITY_POST,
1859                 $since_id
1860         );
1861
1862         $r = dba::inArray($r);
1863
1864         $ret = api_format_items($r, $user_info, false, $type);
1865
1866         $data = array('status' => $ret);
1867         switch ($type) {
1868                 case "atom":
1869                 case "rss":
1870                         $data = api_rss_extra($a, $data, $user_info);
1871                         break;
1872         }
1873
1874         return api_format_data("statuses", $type, $data);
1875 }
1876
1877 /// @TODO move to top of file or somewhere better
1878 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1879
1880 /**
1881  * @TODO nothing to say?
1882  */
1883 function api_statuses_show($type)
1884 {
1885         $a = get_app();
1886
1887         if (api_user() === false) {
1888                 throw new ForbiddenException();
1889         }
1890
1891         $user_info = api_get_user($a);
1892
1893         // params
1894         $id = intval($a->argv[3]);
1895
1896         if ($id == 0) {
1897                 $id = intval($_REQUEST["id"]);
1898         }
1899
1900         // Hotot workaround
1901         if ($id == 0) {
1902                 $id = intval($a->argv[4]);
1903         }
1904
1905         logger('API: api_statuses_show: ' . $id);
1906
1907         $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1908
1909         $sql_extra = '';
1910         if ($conversation) {
1911                 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1912         } else {
1913                 $sql_extra .= " AND `item`.`id` = %d";
1914         }
1915
1916         $r = q(
1917                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1918                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1919                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1920                 `contact`.`id` AS `cid`
1921                 FROM `item`
1922                 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1923                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1924                 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1925                 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1926                 $sql_extra",
1927                 intval(api_user()),
1928                 dbesc(ACTIVITY_POST),
1929                 intval($id)
1930         );
1931
1932         /// @TODO How about copying this to above methods which don't check $r ?
1933         if (!DBM::is_result($r)) {
1934                 throw new BadRequestException("There is no status with this id.");
1935         }
1936
1937         $ret = api_format_items($r, $user_info, false, $type);
1938
1939         if ($conversation) {
1940                 $data = array('status' => $ret);
1941                 return api_format_data("statuses", $type, $data);
1942         } else {
1943                 $data = array('status' => $ret[0]);
1944                 return api_format_data("status", $type, $data);
1945         }
1946 }
1947
1948 /// @TODO move to top of file or somewhere better
1949 api_register_func('api/statuses/show', 'api_statuses_show', true);
1950
1951 /**
1952  * @TODO nothing to say?
1953  */
1954 function api_conversation_show($type)
1955 {
1956         $a = get_app();
1957
1958         if (api_user() === false) {
1959                 throw new ForbiddenException();
1960         }
1961
1962         $user_info = api_get_user($a);
1963
1964         // params
1965         $id = intval($a->argv[3]);
1966         $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1967         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1968         if ($page < 0) {
1969                 $page = 0;
1970         }
1971         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1972         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1973
1974         $start = $page*$count;
1975
1976         if ($id == 0) {
1977                 $id = intval($_REQUEST["id"]);
1978         }
1979
1980         // Hotot workaround
1981         if ($id == 0) {
1982                 $id = intval($a->argv[4]);
1983         }
1984
1985         logger('API: api_conversation_show: '.$id);
1986
1987         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1988         if (DBM::is_result($r)) {
1989                 $id = $r[0]["parent"];
1990         }
1991
1992         $sql_extra = '';
1993
1994         if ($max_id > 0) {
1995                 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1996         }
1997
1998         // Not sure why this query was so complicated. We should keep it here for a while,
1999         // just to make sure that we really don't need it.
2000         //      FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
2001         //      ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
2002
2003         $r = q(
2004                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2005                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2006                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2007                 `contact`.`id` AS `cid`
2008                 FROM `item`
2009                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2010                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2011                 WHERE `item`.`parent` = %d AND `item`.`visible`
2012                 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2013                 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2014                 AND `item`.`id`>%d $sql_extra
2015                 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2016                 intval($id), intval(api_user()),
2017                 dbesc(ACTIVITY_POST),
2018                 intval($since_id),
2019                 intval($start), intval($count)
2020         );
2021
2022         if (!DBM::is_result($r)) {
2023                 throw new BadRequestException("There is no status with this id.");
2024         }
2025
2026         $ret = api_format_items($r, $user_info, false, $type);
2027
2028         $data = array('status' => $ret);
2029         return api_format_data("statuses", $type, $data);
2030 }
2031
2032 /// @TODO move to top of file or somewhere better
2033 api_register_func('api/conversation/show', 'api_conversation_show', true);
2034 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2035
2036 /**
2037  * @TODO nothing to say?
2038  */
2039 function api_statuses_repeat($type)
2040 {
2041         global $called_api;
2042
2043         $a = get_app();
2044
2045         if (api_user() === false) {
2046                 throw new ForbiddenException();
2047         }
2048
2049         $user_info = api_get_user($a);
2050
2051         // params
2052         $id = intval($a->argv[3]);
2053
2054         if ($id == 0) {
2055                 $id = intval($_REQUEST["id"]);
2056         }
2057
2058         // Hotot workaround
2059         if ($id == 0) {
2060                 $id = intval($a->argv[4]);
2061         }
2062
2063         logger('API: api_statuses_repeat: '.$id);
2064
2065         $r = q(
2066                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2067                 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2068                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2069                 `contact`.`id` AS `cid`
2070                 FROM `item`
2071                 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2072                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2073                 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2074                 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2075                 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2076                 $sql_extra
2077                 AND `item`.`id`=%d",
2078                 intval($id)
2079         );
2080
2081         /// @TODO other style than above functions!
2082         if (DBM::is_result($r) && $r[0]['body'] != "") {
2083                 if (strpos($r[0]['body'], "[/share]") !== false) {
2084                         $pos = strpos($r[0]['body'], "[share");
2085                         $post = substr($r[0]['body'], $pos);
2086                 } else {
2087                         $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2088
2089                         $post .= $r[0]['body'];
2090                         $post .= "[/share]";
2091                 }
2092                 $_REQUEST['body'] = $post;
2093                 $_REQUEST['profile_uid'] = api_user();
2094                 $_REQUEST['type'] = 'wall';
2095                 $_REQUEST['api_source'] = true;
2096
2097                 if (!x($_REQUEST, "source")) {
2098                         $_REQUEST["source"] = api_source();
2099                 }
2100
2101                 item_post($a);
2102         } else {
2103                 throw new ForbiddenException();
2104         }
2105
2106         // this should output the last post (the one we just posted).
2107         $called_api = null;
2108         return api_status_show($type);
2109 }
2110
2111 /// @TODO move to top of file or somewhere better
2112 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2113
2114 /**
2115  * @TODO nothing to say?
2116  */
2117 function api_statuses_destroy($type)
2118 {
2119         $a = get_app();
2120
2121         if (api_user() === false) {
2122                 throw new ForbiddenException();
2123         }
2124
2125         $user_info = api_get_user($a);
2126
2127         // params
2128         $id = intval($a->argv[3]);
2129
2130         if ($id == 0) {
2131                 $id = intval($_REQUEST["id"]);
2132         }
2133
2134         // Hotot workaround
2135         if ($id == 0) {
2136                 $id = intval($a->argv[4]);
2137         }
2138
2139         logger('API: api_statuses_destroy: '.$id);
2140
2141         $ret = api_statuses_show($type);
2142
2143         drop_item($id, false);
2144
2145         return $ret;
2146 }
2147
2148 /// @TODO move to top of file or somewhere better
2149 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2150
2151 /**
2152  * @TODO Nothing more than an URL to say?
2153  * http://developer.twitter.com/doc/get/statuses/mentions
2154  */
2155 function api_statuses_mentions($type)
2156 {
2157         $a = get_app();
2158
2159         if (api_user() === false) {
2160                 throw new ForbiddenException();
2161         }
2162
2163         unset($_REQUEST["user_id"]);
2164         unset($_GET["user_id"]);
2165
2166         unset($_REQUEST["screen_name"]);
2167         unset($_GET["screen_name"]);
2168
2169         $user_info = api_get_user($a);
2170         // get last newtork messages
2171
2172
2173         // params
2174         $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2175         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2176         if ($page < 0) {
2177                 $page = 0;
2178         }
2179         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2180         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2181         //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2182
2183         $start = $page * $count;
2184
2185         // Ugly code - should be changed
2186         $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2187         $myurl = substr($myurl, strpos($myurl, '://') + 3);
2188         //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
2189         $myurl = str_replace('www.', '', $myurl);
2190         $diasp_url = str_replace('/profile/', '/u/', $myurl);
2191
2192         if ($max_id > 0) {
2193                 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2194         }
2195
2196         $r = q(
2197                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2198                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2199                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2200                 `contact`.`id` AS `cid`
2201                 FROM `item` FORCE INDEX (`uid_id`)
2202                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2203                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2204                 WHERE `item`.`uid` = %d AND `verb` = '%s'
2205                 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2206                 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2207                 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2208                 $sql_extra
2209                 AND `item`.`id`>%d
2210                 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2211                 intval(api_user()),
2212                 dbesc(ACTIVITY_POST),
2213                 dbesc(protect_sprintf($myurl)),
2214                 dbesc(protect_sprintf($myurl)),
2215                 intval(api_user()),
2216                 intval($since_id),
2217                 intval($start),
2218                 intval($count)
2219         );
2220
2221         $ret = api_format_items($r, $user_info, false, $type);
2222
2223         $data = array('status' => $ret);
2224         switch ($type) {
2225                 case "atom":
2226                 case "rss":
2227                         $data = api_rss_extra($a, $data, $user_info);
2228                         break;
2229         }
2230
2231         return api_format_data("statuses", $type, $data);
2232 }
2233
2234 /// @TODO move to top of file or somewhere better
2235 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2236 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2237
2238 /**
2239  * @brief Returns a user's public timeline
2240  *
2241  * @param string $type Either "json" or "xml"
2242  * @return string|array
2243  * @throws ForbiddenException
2244  */
2245 function api_statuses_user_timeline($type)
2246 {
2247         $a = get_app();
2248
2249         if (api_user() === false) {
2250                 throw new ForbiddenException();
2251         }
2252
2253         $user_info = api_get_user($a);
2254
2255         logger(
2256                 "api_statuses_user_timeline: api_user: ". api_user() .
2257                         "\nuser_info: ".print_r($user_info, true) .
2258                         "\n_REQUEST:  ".print_r($_REQUEST, true),
2259                 LOGGER_DEBUG
2260         );
2261
2262         $since_id        = x($_REQUEST, 'since_id')        ? $_REQUEST['since_id']        : 0;
2263         $max_id          = x($_REQUEST, 'max_id')          ? $_REQUEST['max_id']          : 0;
2264         $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1                            : 0;
2265         $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2266
2267         // pagination
2268         $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2269         $page  = x($_REQUEST, 'page')  ? $_REQUEST['page']  : 1;
2270         if ($page < 1) {
2271                 $page = 1;
2272         }
2273         $start = ($page - 1) * $count;
2274
2275         $sql_extra = '';
2276         if ($user_info['self'] == 1) {
2277                 $sql_extra .= " AND `item`.`wall` = 1 ";
2278         }
2279
2280         if ($exclude_replies > 0) {
2281                 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2282         }
2283
2284         if ($conversation_id > 0) {
2285                 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2286         }
2287
2288         if ($max_id > 0) {
2289                 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2290         }
2291
2292         $r = q(
2293                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2294                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2295                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2296                 `contact`.`id` AS `cid`
2297                 FROM `item` FORCE INDEX (`uid_contactid_id`)
2298                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2299                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2300                 WHERE `item`.`uid` = %d AND `verb` = '%s'
2301                 AND `item`.`contact-id` = %d
2302                 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2303                 $sql_extra
2304                 AND `item`.`id` > %d
2305                 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2306                 intval(api_user()),
2307                 dbesc(ACTIVITY_POST),
2308                 intval($user_info['cid']),
2309                 intval($since_id),
2310                 intval($start),
2311                 intval($count)
2312         );
2313
2314         $ret = api_format_items($r, $user_info, true, $type);
2315
2316         $data = array('status' => $ret);
2317         switch ($type) {
2318                 case "atom":
2319                 case "rss":
2320                         $data = api_rss_extra($a, $data, $user_info);
2321                         break;
2322         }
2323
2324         return api_format_data("statuses", $type, $data);
2325 }
2326
2327 /// @TODO move to top of file or somwhere better
2328 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2329
2330 /**
2331  * Star/unstar an item
2332  * param: id : id of the item
2333  *
2334  * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2335  */
2336 function api_favorites_create_destroy($type)
2337 {
2338         $a = get_app();
2339
2340         if (api_user() === false) {
2341                 throw new ForbiddenException();
2342         }
2343
2344         // for versioned api.
2345         /// @TODO We need a better global soluton
2346         $action_argv_id = 2;
2347         if ($a->argv[1] == "1.1") {
2348                 $action_argv_id = 3;
2349         }
2350
2351         if ($a->argc <= $action_argv_id) {
2352                 throw new BadRequestException("Invalid request.");
2353         }
2354         $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2355         if ($a->argc == $action_argv_id + 2) {
2356                 $itemid = intval($a->argv[$action_argv_id + 1]);
2357         } else {
2358                 ///  @TODO use x() to check if _REQUEST contains 'id'
2359                 $itemid = intval($_REQUEST['id']);
2360         }
2361
2362         $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2363
2364         if (!DBM::is_result($item) || count($item) == 0) {
2365                 throw new BadRequestException("Invalid item.");
2366         }
2367
2368         switch ($action) {
2369                 case "create":
2370                         $item[0]['starred'] = 1;
2371                         break;
2372                 case "destroy":
2373                         $item[0]['starred'] = 0;
2374                         break;
2375                 default:
2376                         throw new BadRequestException("Invalid action ".$action);
2377         }
2378
2379         $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",     $item[0]['starred'], $itemid, api_user());
2380
2381         q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2382
2383         if ($r === false) {
2384                 throw new InternalServerErrorException("DB error");
2385         }
2386
2387
2388         $user_info = api_get_user($a);
2389         $rets = api_format_items($item, $user_info, false, $type);
2390         $ret = $rets[0];
2391
2392         $data = array('status' => $ret);
2393         switch ($type) {
2394                 case "atom":
2395                 case "rss":
2396                         $data = api_rss_extra($a, $data, $user_info);
2397         }
2398
2399         return api_format_data("status", $type, $data);
2400 }
2401
2402 /// @TODO move to top of file or somwhere better
2403 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2404 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2405
2406 function api_favorites($type)
2407 {
2408         global $called_api;
2409
2410         $a = get_app();
2411
2412         if (api_user() === false) {
2413                 throw new ForbiddenException();
2414         }
2415
2416         $called_api = array();
2417
2418         $user_info = api_get_user($a);
2419
2420         // in friendica starred item are private
2421         // return favorites only for self
2422         logger('api_favorites: self:' . $user_info['self']);
2423
2424         if ($user_info['self'] == 0) {
2425                 $ret = array();
2426         } else {
2427                 $sql_extra = "";
2428
2429                 // params
2430                 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2431                 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2432                 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2433                 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2434                 if ($page < 0) {
2435                         $page = 0;
2436                 }
2437
2438                 $start = $page*$count;
2439
2440                 if ($max_id > 0) {
2441                         $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2442                 }
2443
2444                 $r = q(
2445                         "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2446                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2447                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2448                         `contact`.`id` AS `cid`
2449                         FROM `item`, `contact`
2450                         WHERE `item`.`uid` = %d
2451                         AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2452                         AND `item`.`starred` = 1
2453                         AND `contact`.`id` = `item`.`contact-id`
2454                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2455                         $sql_extra
2456                         AND `item`.`id`>%d
2457                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2458                         intval(api_user()),
2459                         intval($since_id),
2460                         intval($start),
2461                         intval($count)
2462                 );
2463
2464                 $ret = api_format_items($r, $user_info, false, $type);
2465         }
2466
2467         $data = array('status' => $ret);
2468         switch ($type) {
2469                 case "atom":
2470                 case "rss":
2471                         $data = api_rss_extra($a, $data, $user_info);
2472         }
2473
2474         return api_format_data("statuses", $type, $data);
2475 }
2476
2477 /// @TODO move to top of file or somwhere better
2478 api_register_func('api/favorites', 'api_favorites', true);
2479
2480 function api_format_messages($item, $recipient, $sender)
2481 {
2482         // standard meta information
2483         $ret = array(
2484                         'id'                    => $item['id'],
2485                         'sender_id'             => $sender['id'] ,
2486                         'text'                  => "",
2487                         'recipient_id'          => $recipient['id'],
2488                         'created_at'            => api_date($item['created']),
2489                         'sender_screen_name'    => $sender['screen_name'],
2490                         'recipient_screen_name' => $recipient['screen_name'],
2491                         'sender'                => $sender,
2492                         'recipient'             => $recipient,
2493                         'title'                 => "",
2494                         'friendica_seen'        => $item['seen'],
2495                         'friendica_parent_uri'  => $item['parent-uri'],
2496         );
2497
2498         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2499         unset($ret["sender"]["uid"]);
2500         unset($ret["sender"]["self"]);
2501         unset($ret["recipient"]["uid"]);
2502         unset($ret["recipient"]["self"]);
2503
2504         //don't send title to regular StatusNET requests to avoid confusing these apps
2505         if (x($_GET, 'getText')) {
2506                 $ret['title'] = $item['title'];
2507                 if ($_GET['getText'] == 'html') {
2508                         $ret['text'] = bbcode($item['body'], false, false);
2509                 } elseif ($_GET['getText'] == 'plain') {
2510                         //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2511                         $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2512                 }
2513         } else {
2514                 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2515         }
2516         if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2517                 unset($ret['sender']);
2518                 unset($ret['recipient']);
2519         }
2520
2521         return $ret;
2522 }
2523
2524 function api_convert_item($item)
2525 {
2526         $body = $item['body'];
2527         $attachments = api_get_attachments($body);
2528
2529         // Workaround for ostatus messages where the title is identically to the body
2530         $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2531         $statusbody = trim(html2plain($html, 0));
2532
2533         // handle data: images
2534         $statusbody = api_format_items_embeded_images($item, $statusbody);
2535
2536         $statustitle = trim($item['title']);
2537
2538         if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2539                 $statustext = trim($statusbody);
2540         } else {
2541                 $statustext = trim($statustitle."\n\n".$statusbody);
2542         }
2543
2544         if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2545                 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2546         }
2547
2548         $statushtml = trim(bbcode($body, false, false));
2549
2550         // Workaround for clients with limited HTML parser functionality
2551         $search = array("<br>", "<blockquote>", "</blockquote>",
2552                         "<h1>", "</h1>", "<h2>", "</h2>",
2553                         "<h3>", "</h3>", "<h4>", "</h4>",
2554                         "<h5>", "</h5>", "<h6>", "</h6>");
2555         $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2556                         "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2557                         "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2558                         "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2559         $statushtml = str_replace($search, $replace, $statushtml);
2560
2561         if ($item['title'] != "") {
2562                 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2563         }
2564
2565         do {
2566                 $oldtext = $statushtml;
2567                 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2568         } while ($oldtext != $statushtml);
2569
2570         if (substr($statushtml, 0, 4) == '<br>') {
2571                 $statushtml = substr($statushtml, 4);
2572         }
2573
2574         if (substr($statushtml, 0, -4) == '<br>') {
2575                 $statushtml = substr($statushtml, -4);
2576         }
2577
2578         // feeds without body should contain the link
2579         if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2580                 $statushtml .= bbcode($item['plink']);
2581         }
2582
2583         $entities = api_get_entitities($statustext, $body);
2584
2585         return array(
2586                 "text" => $statustext,
2587                 "html" => $statushtml,
2588                 "attachments" => $attachments,
2589                 "entities" => $entities
2590         );
2591 }
2592
2593 function api_get_attachments(&$body)
2594 {
2595         $text = $body;
2596         $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2597
2598         $URLSearchString = "^\[\]";
2599         $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2600
2601         if (!$ret) {
2602                 return false;
2603         }
2604
2605         $attachments = array();
2606
2607         foreach ($images[1] as $image) {
2608                 $imagedata = Image::getInfoFromURL($image);
2609
2610                 if ($imagedata) {
2611                         $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2612                 }
2613         }
2614
2615         if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2616                 foreach ($images[0] as $orig) {
2617                         $body = str_replace($orig, "", $body);
2618                 }
2619         }
2620
2621         return $attachments;
2622 }
2623
2624 function api_get_entitities(&$text, $bbcode)
2625 {
2626         /*
2627         To-Do:
2628         * Links at the first character of the post
2629         */
2630
2631         $a = get_app();
2632
2633         $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2634
2635         if ($include_entities != "true") {
2636                 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2637
2638                 foreach ($images[1] as $image) {
2639                         $replace = proxy_url($image);
2640                         $text = str_replace($image, $replace, $text);
2641                 }
2642                 return array();
2643         }
2644
2645         $bbcode = bb_CleanPictureLinks($bbcode);
2646
2647         // Change pure links in text to bbcode uris
2648         $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2649
2650         $entities = array();
2651         $entities["hashtags"] = array();
2652         $entities["symbols"] = array();
2653         $entities["urls"] = array();
2654         $entities["user_mentions"] = array();
2655
2656         $URLSearchString = "^\[\]";
2657
2658         $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2659
2660         $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2661         //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2662         $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2663
2664         $bbcode = preg_replace(
2665                 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2666                 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2667                 $bbcode
2668         );
2669         $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2670
2671         $bbcode = preg_replace(
2672                 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2673                 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2674                 $bbcode
2675         );
2676         $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2677
2678         $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2679
2680         //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2681         preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2682
2683         $ordered_urls = array();
2684         foreach ($urls[1] as $id => $url) {
2685                 //$start = strpos($text, $url, $offset);
2686                 $start = iconv_strpos($text, $url, 0, "UTF-8");
2687                 if (!($start === false)) {
2688                         $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2689                 }
2690         }
2691
2692         ksort($ordered_urls);
2693
2694         $offset = 0;
2695         //foreach ($urls[1] AS $id=>$url) {
2696         foreach ($ordered_urls as $url) {
2697                 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2698                         && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2699                 )
2700                         $display_url = $url["title"];
2701                 else {
2702                         $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2703                         $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2704
2705                         if (strlen($display_url) > 26)
2706                                 $display_url = substr($display_url, 0, 25)."…";
2707                 }
2708
2709                 //$start = strpos($text, $url, $offset);
2710                 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2711                 if (!($start === false)) {
2712                         $entities["urls"][] = array("url" => $url["url"],
2713                                                         "expanded_url" => $url["url"],
2714                                                         "display_url" => $display_url,
2715                                                         "indices" => array($start, $start+strlen($url["url"])));
2716                         $offset = $start + 1;
2717                 }
2718         }
2719
2720         preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2721         $ordered_images = array();
2722         foreach ($images[1] as $image) {
2723                 //$start = strpos($text, $url, $offset);
2724                 $start = iconv_strpos($text, $image, 0, "UTF-8");
2725                 if (!($start === false))
2726                         $ordered_images[$start] = $image;
2727         }
2728         //$entities["media"] = array();
2729         $offset = 0;
2730
2731         foreach ($ordered_images as $url) {
2732                 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2733                 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2734
2735                 if (strlen($display_url) > 26)
2736                         $display_url = substr($display_url, 0, 25)."…";
2737
2738                 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2739                 if (!($start === false)) {
2740                         $image = Image::getInfoFromURL($url);
2741                         if ($image) {
2742                                 // If image cache is activated, then use the following sizes:
2743                                 // thumb  (150), small (340), medium (600) and large (1024)
2744                                 if (!Config::get("system", "proxy_disabled")) {
2745                                         $media_url = proxy_url($url);
2746
2747                                         $sizes = array();
2748                                         $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2749                                         $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2750
2751                                         if (($image[0] > 150) || ($image[1] > 150)) {
2752                                                 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2753                                                 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2754                                         }
2755
2756                                         $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2757                                         $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2758
2759                                         if (($image[0] > 600) || ($image[1] > 600)) {
2760                                                 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2761                                                 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2762                                         }
2763                                 } else {
2764                                         $media_url = $url;
2765                                         $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2766                                 }
2767
2768                                 $entities["media"][] = array(
2769                                                         "id" => $start+1,
2770                                                         "id_str" => (string)$start+1,
2771                                                         "indices" => array($start, $start+strlen($url)),
2772                                                         "media_url" => normalise_link($media_url),
2773                                                         "media_url_https" => $media_url,
2774                                                         "url" => $url,
2775                                                         "display_url" => $display_url,
2776                                                         "expanded_url" => $url,
2777                                                         "type" => "photo",
2778                                                         "sizes" => $sizes);
2779                         }
2780                         $offset = $start + 1;
2781                 }
2782         }
2783
2784         return $entities;
2785 }
2786 function api_format_items_embeded_images(&$item, $text)
2787 {
2788         $text = preg_replace_callback(
2789                 "|data:image/([^;]+)[^=]+=*|m",
2790                 function ($match) use ($item) {
2791                         return System::baseUrl()."/display/".$item['guid'];
2792                 },
2793                 $text
2794         );
2795         return $text;
2796 }
2797
2798
2799 /**
2800  * @brief return <a href='url'>name</a> as array
2801  *
2802  * @param string $txt text
2803  * @return array
2804  *                      name => 'name'
2805  *                      'url => 'url'
2806  */
2807 function api_contactlink_to_array($txt)
2808 {
2809         $match = array();
2810         $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2811         if ($r && count($match)==3) {
2812                 $res = array(
2813                         'name' => $match[2],
2814                         'url' => $match[1]
2815                 );
2816         } else {
2817                 $res = array(
2818                         'name' => $text,
2819                         'url' => ""
2820                 );
2821         }
2822         return $res;
2823 }
2824
2825
2826 /**
2827  * @brief return likes, dislikes and attend status for item
2828  *
2829  * @param array $item array
2830  * @return array
2831  *                      likes => int count
2832  *                      dislikes => int count
2833  */
2834 function api_format_items_activities(&$item, $type = "json")
2835 {
2836         $a = get_app();
2837
2838         $activities = array(
2839                 'like' => array(),
2840                 'dislike' => array(),
2841                 'attendyes' => array(),
2842                 'attendno' => array(),
2843                 'attendmaybe' => array(),
2844         );
2845
2846         $items = q(
2847                 'SELECT * FROM item
2848                         WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2849                 intval($item['uid']),
2850                 dbesc($item['uri'])
2851         );
2852
2853         foreach ($items as $i) {
2854                 // not used as result should be structured like other user data
2855                 //builtin_activity_puller($i, $activities);
2856
2857                 // get user data and add it to the array of the activity
2858                 $user = api_get_user($a, $i['author-link']);
2859                 switch ($i['verb']) {
2860                         case ACTIVITY_LIKE:
2861                                 $activities['like'][] = $user;
2862                                 break;
2863                         case ACTIVITY_DISLIKE:
2864                                 $activities['dislike'][] = $user;
2865                                 break;
2866                         case ACTIVITY_ATTEND:
2867                                 $activities['attendyes'][] = $user;
2868                                 break;
2869                         case ACTIVITY_ATTENDNO:
2870                                 $activities['attendno'][] = $user;
2871                                 break;
2872                         case ACTIVITY_ATTENDMAYBE:
2873                                 $activities['attendmaybe'][] = $user;
2874                                 break;
2875                         default:
2876                                 break;
2877                 }
2878         }
2879
2880         if ($type == "xml") {
2881                 $xml_activities = array();
2882                 foreach ($activities as $k => $v) {
2883                         // change xml element from "like" to "friendica:like"
2884                         $xml_activities["friendica:".$k] = $v;
2885                         // add user data into xml output
2886                         $k_user = 0;
2887                         foreach ($v as $user)
2888                                 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2889                 }
2890                 $activities = $xml_activities;
2891         }
2892
2893         return $activities;
2894 }
2895
2896
2897 /**
2898  * @brief return data from profiles
2899  *
2900  * @param array  $profile array containing data from db table 'profile'
2901  * @param string $type    Known types are 'atom', 'rss', 'xml' and 'json'
2902  * @return array
2903  */
2904 function api_format_items_profiles(&$profile = null, $type = "json")
2905 {
2906         if ($profile != null) {
2907                 $profile = array('profile_id' => $profile['id'],
2908                                                 'profile_name' => $profile['profile-name'],
2909                                                 'is_default' => $profile['is-default'] ? true : false,
2910                                                 'hide_friends'=> $profile['hide-friends'] ? true : false,
2911                                                 'profile_photo' => $profile['photo'],
2912                                                 'profile_thumb' => $profile['thumb'],
2913                                                 'publish' => $profile['publish'] ? true : false,
2914                                                 'net_publish' => $profile['net-publish'] ? true : false,
2915                                                 'description' => $profile['pdesc'],
2916                                                 'date_of_birth' => $profile['dob'],
2917                                                 'address' => $profile['address'],
2918                                                 'city' => $profile['locality'],
2919                                                 'region' => $profile['region'],
2920                                                 'postal_code' => $profile['postal-code'],
2921                                                 'country' => $profile['country-name'],
2922                                                 'hometown' => $profile['hometown'],
2923                                                 'gender' => $profile['gender'],
2924                                                 'marital' => $profile['marital'],
2925                                                 'marital_with' => $profile['with'],
2926                                                 'marital_since' => $profile['howlong'],
2927                                                 'sexual' => $profile['sexual'],
2928                                                 'politic' => $profile['politic'],
2929                                                 'religion' => $profile['religion'],
2930                                                 'public_keywords' => $profile['pub_keywords'],
2931                                                 'private_keywords' => $profile['prv_keywords'],
2932                                                 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2933                                                 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2934                                                 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2935                                                 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2936                                                 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2937                                                 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2938                                                 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2939                                                 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2940                                                 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2941                                                 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2942                                                 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2943                                                 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2944                                                 'homepage' => $profile['homepage'],
2945                                                 'users' => null);
2946                 return $profile;
2947         }
2948 }
2949
2950 /**
2951  * @brief format items to be returned by api
2952  *
2953  * @param array $r array of items
2954  * @param array $user_info
2955  * @param bool $filter_user filter items by $user_info
2956  */
2957 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2958 {
2959         $a = get_app();
2960
2961         $ret = array();
2962
2963         foreach ($r as $item) {
2964                 localize_item($item);
2965                 list($status_user, $owner_user) = api_item_get_user($a, $item);
2966
2967                 // Look if the posts are matching if they should be filtered by user id
2968                 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2969                         continue;
2970                 }
2971
2972                 $in_reply_to = api_in_reply_to($item);
2973
2974                 $converted = api_convert_item($item);
2975
2976                 if ($type == "xml") {
2977                         $geo = "georss:point";
2978                 } else {
2979                         $geo = "geo";
2980                 }
2981
2982                 $status = array(
2983                         'text'          => $converted["text"],
2984                         'truncated' => false,
2985                         'created_at'=> api_date($item['created']),
2986                         'in_reply_to_status_id' => $in_reply_to['status_id'],
2987                         'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2988                         'source'    => (($item['app']) ? $item['app'] : 'web'),
2989                         'id'            => intval($item['id']),
2990                         'id_str'        => (string) intval($item['id']),
2991                         'in_reply_to_user_id' => $in_reply_to['user_id'],
2992                         'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2993                         'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2994                         $geo => null,
2995                         'favorited' => $item['starred'] ? true : false,
2996                         'user' =>  $status_user ,
2997                         'friendica_owner' => $owner_user,
2998                         //'entities' => NULL,
2999                         'statusnet_html' => $converted["html"],
3000                         'statusnet_conversation_id' => $item['parent'],
3001                         'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3002                         'friendica_activities' => api_format_items_activities($item, $type),
3003                 );
3004
3005                 if (count($converted["attachments"]) > 0) {
3006                         $status["attachments"] = $converted["attachments"];
3007                 }
3008
3009                 if (count($converted["entities"]) > 0) {
3010                         $status["entities"] = $converted["entities"];
3011                 }
3012
3013                 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
3014                         $status["source"] = network_to_name($item['item_network'], $user_info['url']);
3015                 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
3016                         $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
3017                 }
3018
3019
3020                 // Retweets are only valid for top postings
3021                 // It doesn't work reliable with the link if its a feed
3022                 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
3023                 //if ($IsRetweet)
3024                 //      $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
3025
3026
3027                 if ($item["id"] == $item["parent"]) {
3028                         $retweeted_item = api_share_as_retweet($item);
3029                         if ($retweeted_item !== false) {
3030                                 $retweeted_status = $status;
3031                                 try {
3032                                         $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
3033                                 } catch (BadRequestException $e) {
3034                                         // user not found. should be found?
3035                                         /// @todo check if the user should be always found
3036                                         $retweeted_status["user"] = array();
3037                                 }
3038
3039                                 $rt_converted = api_convert_item($retweeted_item);
3040
3041                                 $retweeted_status['text'] = $rt_converted["text"];
3042                                 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3043                                 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3044                                 $retweeted_status['created_at'] =  api_date($retweeted_item['created']);
3045                                 $status['retweeted_status'] = $retweeted_status;
3046                         }
3047                 }
3048
3049                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3050                 unset($status["user"]["uid"]);
3051                 unset($status["user"]["self"]);
3052
3053                 if ($item["coord"] != "") {
3054                         $coords = explode(' ', $item["coord"]);
3055                         if (count($coords) == 2) {
3056                                 if ($type == "json")
3057                                         $status["geo"] = array('type' => 'Point',
3058                                                         'coordinates' => array((float) $coords[0],
3059                                                                                 (float) $coords[1]));
3060                                 else // Not sure if this is the official format - if someone founds a documentation we can check
3061                                         $status["georss:point"] = $item["coord"];
3062                         }
3063                 }
3064                 $ret[] = $status;
3065         };
3066         return $ret;
3067 }
3068
3069 function api_account_rate_limit_status($type)
3070 {
3071         if ($type == "xml") {
3072                 $hash = array(
3073                                 'remaining-hits' => '150',
3074                                 '@attributes' => array("type" => "integer"),
3075                                 'hourly-limit' => '150',
3076                                 '@attributes2' => array("type" => "integer"),
3077                                 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
3078                                 '@attributes3' => array("type" => "datetime"),
3079                                 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3080                                 '@attributes4' => array("type" => "integer"),
3081                         );
3082         } else {
3083                 $hash = array(
3084                                 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3085                                 'remaining_hits' => '150',
3086                                 'hourly_limit' => '150',
3087                                 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
3088                         );
3089         }
3090
3091         return api_format_data('hash', $type, array('hash' => $hash));
3092 }
3093
3094 /// @TODO move to top of file or somwhere better
3095 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3096
3097 function api_help_test($type)
3098 {
3099         if ($type == 'xml') {
3100                 $ok = "true";
3101         } else {
3102                 $ok = "ok";
3103         }
3104
3105         return api_format_data('ok', $type, array("ok" => $ok));
3106 }
3107
3108 /// @TODO move to top of file or somwhere better
3109 api_register_func('api/help/test', 'api_help_test', false);
3110
3111 function api_lists($type)
3112 {
3113         $ret = array();
3114         /// @TODO $ret is not filled here?
3115         return api_format_data('lists', $type, array("lists_list" => $ret));
3116 }
3117
3118 /// @TODO move to top of file or somwhere better
3119 api_register_func('api/lists', 'api_lists', true);
3120
3121 function api_lists_list($type)
3122 {
3123         $ret = array();
3124         /// @TODO $ret is not filled here?
3125         return api_format_data('lists', $type, array("lists_list" => $ret));
3126 }
3127
3128 /// @TODO move to top of file or somwhere better
3129 api_register_func('api/lists/list', 'api_lists_list', true);
3130
3131 /**
3132  * @brief Returns either the friends of the follower list
3133  *
3134  * Note: Considers friends and followers lists to be private and won't return
3135  * anything if any user_id parameter is passed.
3136  *
3137  * @param string $qtype Either "friends" or "followers"
3138  * @return boolean|array
3139  * @throws ForbiddenException
3140  */
3141 function api_statuses_f($qtype)
3142 {
3143         $a = get_app();
3144
3145         if (api_user() === false) {
3146                 throw new ForbiddenException();
3147         }
3148
3149         // pagination
3150         $count = x($_GET, 'count') ? $_GET['count'] : 20;
3151         $page = x($_GET, 'page') ? $_GET['page'] : 1;
3152         if ($page < 1) {
3153                 $page = 1;
3154         }
3155         $start = ($page - 1) * $count;
3156
3157         $user_info = api_get_user($a);
3158
3159         if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3160                 /* this is to stop Hotot to load friends multiple times
3161                 *  I'm not sure if I'm missing return something or
3162                 *  is a bug in hotot. Workaround, meantime
3163                 */
3164
3165                 /*$ret=Array();
3166                 return array('$users' => $ret);*/
3167                 return false;
3168         }
3169
3170         if ($qtype == 'friends') {
3171                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3172         }
3173         if ($qtype == 'followers') {
3174                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3175         }
3176
3177         // friends and followers only for self
3178         if ($user_info['self'] == 0) {
3179                 $sql_extra = " AND false ";
3180         }
3181
3182         if ($qtype == 'blocks') {
3183                 $sql_filter = 'AND `blocked` AND NOT `pending`';
3184         } elseif ($qtype == 'incoming') {
3185                 $sql_filter = 'AND `pending`';
3186         } else {
3187                 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3188         }
3189
3190         $r = q(
3191                 "SELECT `nurl`
3192                 FROM `contact`
3193                 WHERE `uid` = %d
3194                 AND NOT `self`
3195                 $sql_filter
3196                 $sql_extra
3197                 ORDER BY `nick`
3198                 LIMIT %d, %d",
3199                 intval(api_user()),
3200                 intval($start),
3201                 intval($count)
3202         );
3203
3204         $ret = array();
3205         foreach ($r as $cid) {
3206                 $user = api_get_user($a, $cid['nurl']);
3207                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3208                 unset($user["uid"]);
3209                 unset($user["self"]);
3210
3211                 if ($user) {
3212                         $ret[] = $user;
3213                 }
3214         }
3215
3216         return array('user' => $ret);
3217 }
3218
3219
3220 /**
3221  * @brief Returns the list of friends of the provided user
3222  *
3223  * @deprecated By Twitter API in favor of friends/list
3224  *
3225  * @param string $type Either "json" or "xml"
3226  * @return boolean|string|array
3227  */
3228 function api_statuses_friends($type)
3229 {
3230         $data =  api_statuses_f("friends");
3231         if ($data === false) {
3232                 return false;
3233         }
3234         return api_format_data("users", $type, $data);
3235 }
3236
3237 /**
3238  * @brief Returns the list of friends of the provided user
3239  *
3240  * @deprecated By Twitter API in favor of friends/list
3241  *
3242  * @param string $type Either "json" or "xml"
3243  * @return boolean|string|array
3244  */
3245 function api_statuses_followers($type)
3246 {
3247         $data = api_statuses_f("followers");
3248         if ($data === false) {
3249                 return false;
3250         }
3251         return api_format_data("users", $type, $data);
3252 }
3253
3254 /// @TODO move to top of file or somewhere better
3255 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3256 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3257
3258 /**
3259  * Returns the list of blocked users
3260  *
3261  * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3262  *
3263  * @param string $type Either "json" or "xml"
3264  *
3265  * @return boolean|string|array
3266  * @throws UnauthorizedException
3267  */
3268 function api_blocks_list($type)
3269 {
3270         $data =  api_statuses_f('blocks');
3271         if ($data === false) {
3272                 return false;
3273         }
3274         return api_format_data("users", $type, $data);
3275 }
3276
3277 /// @TODO move to top of file or somewhere better
3278 api_register_func('api/blocks/list', 'api_blocks_list', true);
3279
3280 /**
3281  * Returns the list of pending users IDs
3282  *
3283  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3284  *
3285  * @param string $type Either "json" or "xml"
3286  *
3287  * @return boolean|string|array
3288  * @throws UnauthorizedException
3289  */
3290 function api_friendships_incoming($type)
3291 {
3292         $data =  api_statuses_f('incoming');
3293         if ($data === false) {
3294                 return false;
3295         }
3296
3297         $ids = array();
3298         foreach ($data['user'] as $user) {
3299                 $ids[] = $user['id'];
3300         }
3301
3302         return api_format_data("ids", $type, array('id' => $ids));
3303 }
3304
3305 /// @TODO move to top of file or somewhere better
3306 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3307
3308 function api_statusnet_config($type)
3309 {
3310         $a = get_app();
3311
3312         $name = $a->config['sitename'];
3313         $server = $a->get_hostname();
3314         $logo = System::baseUrl() . '/images/friendica-64.png';
3315         $email = $a->config['admin_email'];
3316         $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3317         $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3318         $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3319         if ($a->config['api_import_size']) {
3320                 $texlimit = string($a->config['api_import_size']);
3321         }
3322         $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3323         $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3324
3325         $config = array(
3326                 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3327                         'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3328                         'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3329                         'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3330                         'shorturllength' => '30',
3331                         'friendica' => array(
3332                                         'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3333                                         'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3334                                         'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3335                                         'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3336                                         )
3337                 ),
3338         );
3339
3340         return api_format_data('config', $type, array('config' => $config));
3341 }
3342
3343 /// @TODO move to top of file or somewhere better
3344 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3345 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3346
3347 function api_statusnet_version($type)
3348 {
3349         // liar
3350         $fake_statusnet_version = "0.9.7";
3351
3352         return api_format_data('version', $type, array('version' => $fake_statusnet_version));
3353 }
3354
3355 /// @TODO move to top of file or somewhere better
3356 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3357 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3358
3359 /**
3360  * @todo use api_format_data() to return data
3361  */
3362 function api_ff_ids($type,$qtype)
3363 {
3364         $a = get_app();
3365
3366         if (! api_user()) {
3367                 throw new ForbiddenException();
3368         }
3369
3370         $user_info = api_get_user($a);
3371
3372         if ($qtype == 'friends') {
3373                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3374         }
3375         if ($qtype == 'followers') {
3376                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3377         }
3378
3379         if (!$user_info["self"]) {
3380                 $sql_extra = " AND false ";
3381         }
3382
3383         $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3384
3385         $r = q(
3386                 "SELECT `pcontact`.`id` FROM `contact`
3387                         INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3388                         WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3389                 intval(api_user())
3390         );
3391
3392         if (!DBM::is_result($r)) {
3393                 return;
3394         }
3395
3396         $ids = array();
3397         foreach ($r as $rr) {
3398                 if ($stringify_ids) {
3399                         $ids[] = $rr['id'];
3400                 } else {
3401                         $ids[] = intval($rr['id']);
3402                 }
3403         }
3404
3405         return api_format_data("ids", $type, array('id' => $ids));
3406 }
3407
3408 function api_friends_ids($type)
3409 {
3410         return api_ff_ids($type, 'friends');
3411 }
3412
3413 function api_followers_ids($type)
3414 {
3415         return api_ff_ids($type, 'followers');
3416 }
3417
3418 /// @TODO move to top of file or somewhere better
3419 api_register_func('api/friends/ids', 'api_friends_ids', true);
3420 api_register_func('api/followers/ids', 'api_followers_ids', true);
3421
3422 function api_direct_messages_new($type)
3423 {
3424
3425         $a = get_app();
3426
3427         if (api_user() === false) throw new ForbiddenException();
3428
3429         if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) return;
3430
3431         $sender = api_get_user($a);
3432
3433         if ($_POST['screen_name']) {
3434                 $r = q(
3435                         "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3436                         intval(api_user()),
3437                         dbesc($_POST['screen_name'])
3438                 );
3439
3440                 // Selecting the id by priority, friendica first
3441                 api_best_nickname($r);
3442
3443                 $recipient = api_get_user($a, $r[0]['nurl']);
3444         } else {
3445                 $recipient = api_get_user($a, $_POST['user_id']);
3446         }
3447
3448         $replyto = '';
3449         $sub     = '';
3450         if (x($_REQUEST, 'replyto')) {
3451                 $r = q(
3452                         'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3453                         intval(api_user()),
3454                         intval($_REQUEST['replyto'])
3455                 );
3456                 $replyto = $r[0]['parent-uri'];
3457                 $sub     = $r[0]['title'];
3458         } else {
3459                 if (x($_REQUEST, 'title')) {
3460                         $sub = $_REQUEST['title'];
3461                 } else {
3462                         $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3463                 }
3464         }
3465
3466         $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3467
3468         if ($id > -1) {
3469                 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3470                 $ret = api_format_messages($r[0], $recipient, $sender);
3471         } else {
3472                 $ret = array("error"=>$id);
3473         }
3474
3475         $data = array('direct_message'=>$ret);
3476
3477         switch ($type) {
3478                 case "atom":
3479                 case "rss":
3480                         $data = api_rss_extra($a, $data, $user_info);
3481         }
3482
3483         return api_format_data("direct-messages", $type, $data);
3484
3485 }
3486
3487 /// @TODO move to top of file or somewhere better
3488 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3489
3490 /**
3491  * @brief delete a direct_message from mail table through api
3492  *
3493  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3494  * @return string
3495  */
3496 function api_direct_messages_destroy($type)
3497 {
3498         $a = get_app();
3499
3500         if (api_user() === false) {
3501                 throw new ForbiddenException();
3502         }
3503
3504         // params
3505         $user_info = api_get_user($a);
3506         //required
3507         $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3508         // optional
3509         $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3510         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3511         /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3512
3513         $uid = $user_info['uid'];
3514         // error if no id or parenturi specified (for clients posting parent-uri as well)
3515         if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3516                 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3517                 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3518         }
3519
3520         // BadRequestException if no id specified (for clients using Twitter API)
3521         if ($id == 0) {
3522                 throw new BadRequestException('Message id not specified');
3523         }
3524
3525         // add parent-uri to sql command if specified by calling app
3526         $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3527
3528         // get data of the specified message id
3529         $r = q(
3530                 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3531                 intval($uid),
3532                 intval($id)
3533         );
3534
3535         // error message if specified id is not in database
3536         if (!DBM::is_result($r)) {
3537                 if ($verbose == "true") {
3538                         $answer = array('result' => 'error', 'message' => 'message id not in database');
3539                         return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3540                 }
3541                 /// @todo BadRequestException ok for Twitter API clients?
3542                 throw new BadRequestException('message id not in database');
3543         }
3544
3545         // delete message
3546         $result = q(
3547                 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3548                 intval($uid),
3549                 intval($id)
3550         );
3551
3552         if ($verbose == "true") {
3553                 if ($result) {
3554                         // return success
3555                         $answer = array('result' => 'ok', 'message' => 'message deleted');
3556                         return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3557                 } else {
3558                         $answer = array('result' => 'error', 'message' => 'unknown error');
3559                         return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3560                 }
3561         }
3562         /// @todo return JSON data like Twitter API not yet implemented
3563
3564 }
3565
3566 /// @TODO move to top of file or somewhere better
3567 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3568
3569 function api_direct_messages_box($type, $box, $verbose)
3570 {
3571         $a = get_app();
3572
3573         if (api_user() === false) {
3574                 throw new ForbiddenException();
3575         }
3576
3577         // params
3578         $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3579         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3580         if ($page < 0) {
3581                 $page = 0;
3582         }
3583
3584         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3585         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3586
3587         $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3588         $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3589
3590         //  caller user info
3591         unset($_REQUEST["user_id"]);
3592         unset($_GET["user_id"]);
3593
3594         unset($_REQUEST["screen_name"]);
3595         unset($_GET["screen_name"]);
3596
3597         $user_info = api_get_user($a);
3598         $profile_url = $user_info["url"];
3599
3600         // pagination
3601         $start = $page * $count;
3602
3603         // filters
3604         if ($box=="sentbox") {
3605                 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3606         } elseif ($box == "conversation") {
3607                 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"])  . "'";
3608         } elseif ($box == "all") {
3609                 $sql_extra = "true";
3610         } elseif ($box == "inbox") {
3611                 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3612         }
3613
3614         if ($max_id > 0) {
3615                 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3616         }
3617
3618         if ($user_id != "") {
3619                 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3620         } elseif ($screen_name !="") {
3621                 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3622         }
3623
3624         $r = q(
3625                 "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",
3626                 intval(api_user()),
3627                 intval($since_id),
3628                 intval($start),
3629                 intval($count)
3630         );
3631         if ($verbose == "true" && !DBM::is_result($r)) {
3632                 $answer = array('result' => 'error', 'message' => 'no mails available');
3633                 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3634         }
3635
3636         $ret = array();
3637         foreach ($r as $item) {
3638                 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3639                         $recipient = $user_info;
3640                         $sender = api_get_user($a, normalise_link($item['contact-url']));
3641                 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3642                         $recipient = api_get_user($a, normalise_link($item['contact-url']));
3643                         $sender = $user_info;
3644                 }
3645
3646                 $ret[] = api_format_messages($item, $recipient, $sender);
3647         }
3648
3649
3650         $data = array('direct_message' => $ret);
3651         switch ($type) {
3652                 case "atom":
3653                 case "rss":
3654                         $data = api_rss_extra($a, $data, $user_info);
3655         }
3656
3657         return api_format_data("direct-messages", $type, $data);
3658 }
3659
3660 function api_direct_messages_sentbox($type)
3661 {
3662         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3663         return api_direct_messages_box($type, "sentbox", $verbose);
3664 }
3665
3666 function api_direct_messages_inbox($type)
3667 {
3668         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3669         return api_direct_messages_box($type, "inbox", $verbose);
3670 }
3671
3672 function api_direct_messages_all($type)
3673 {
3674         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3675         return api_direct_messages_box($type, "all", $verbose);
3676 }
3677
3678 function api_direct_messages_conversation($type)
3679 {
3680         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3681         return api_direct_messages_box($type, "conversation", $verbose);
3682 }
3683
3684 /// @TODO move to top of file or somewhere better
3685 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3686 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3687 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3688 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3689
3690 function api_oauth_request_token($type)
3691 {
3692         $oauth1 = new FKOAuth1();
3693         try {
3694                 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3695         } catch (Exception $e) {
3696                 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3697                 killme();
3698         }
3699         echo $r;
3700         killme();
3701 }
3702
3703 function api_oauth_access_token($type)
3704 {
3705         $oauth1 = new FKOAuth1();
3706         try {
3707                 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3708         } catch (Exception $e) {
3709                 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3710                 killme();
3711         }
3712         echo $r;
3713         killme();
3714 }
3715
3716 /// @TODO move to top of file or somewhere better
3717 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3718 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3719
3720
3721 /**
3722  * @brief delete a complete photoalbum with all containing photos from database through api
3723  *
3724  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3725  * @return string
3726  */
3727 function api_fr_photoalbum_delete($type)
3728 {
3729         if (api_user() === false) {
3730                 throw new ForbiddenException();
3731         }
3732         // input params
3733         $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3734
3735         // we do not allow calls without album string
3736         if ($album == "") {
3737                 throw new BadRequestException("no albumname specified");
3738         }
3739         // check if album is existing
3740         $r = q(
3741                 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3742                 intval(api_user()),
3743                 dbesc($album)
3744         );
3745         if (!DBM::is_result($r))
3746                 throw new BadRequestException("album not available");
3747
3748         // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3749         // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3750         foreach ($r as $rr) {
3751                 $photo_item = q(
3752                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3753                         intval(local_user()),
3754                         dbesc($rr['resource-id'])
3755                 );
3756
3757                 if (!DBM::is_result($photo_item)) {
3758                         throw new InternalServerErrorException("problem with deleting items occured");
3759                 }
3760                 drop_item($photo_item[0]['id'], false);
3761         }
3762
3763         // now let's delete all photos from the album
3764         $result = dba::delete('photo', array('uid' => api_user(), 'album' => $album));
3765
3766         // return success of deletion or error message
3767         if ($result) {
3768                 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3769                 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3770         } else {
3771                 throw new InternalServerErrorException("unknown error - deleting from database failed");
3772         }
3773 }
3774
3775 /**
3776  * @brief update the name of the album for all photos of an album
3777  *
3778  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3779  * @return string
3780  */
3781 function api_fr_photoalbum_update($type)
3782 {
3783         if (api_user() === false) {
3784                 throw new ForbiddenException();
3785         }
3786         // input params
3787         $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3788         $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3789
3790         // we do not allow calls without album string
3791         if ($album == "") {
3792                 throw new BadRequestException("no albumname specified");
3793         }
3794         if ($album_new == "") {
3795                 throw new BadRequestException("no new albumname specified");
3796         }
3797         // check if album is existing
3798         $r = q(
3799                 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3800                 intval(api_user()),
3801                 dbesc($album)
3802         );
3803         if (!DBM::is_result($r)) {
3804                 throw new BadRequestException("album not available");
3805         }
3806         // now let's update all photos to the albumname
3807         $result = q(
3808                 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3809                 dbesc($album_new),
3810                 intval(api_user()),
3811                 dbesc($album)
3812         );
3813
3814         // return success of updating or error message
3815         if ($result) {
3816                 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3817                 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3818         } else {
3819                 throw new InternalServerErrorException("unknown error - updating in database failed");
3820         }
3821 }
3822
3823
3824 /**
3825  * @brief list all photos of the authenticated user
3826  *
3827  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3828  * @return string
3829  */
3830 function api_fr_photos_list($type)
3831 {
3832         if (api_user() === false) {
3833                 throw new ForbiddenException();
3834         }
3835         $r = q(
3836                 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3837                 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3838                 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3839                 intval(local_user())
3840         );
3841         $typetoext = array(
3842                 'image/jpeg' => 'jpg',
3843                 'image/png' => 'png',
3844                 'image/gif' => 'gif'
3845         );
3846         $data = array('photo'=>array());
3847         if (DBM::is_result($r)) {
3848                 foreach ($r as $rr) {
3849                         $photo = array();
3850                         $photo['id'] = $rr['resource-id'];
3851                         $photo['album'] = $rr['album'];
3852                         $photo['filename'] = $rr['filename'];
3853                         $photo['type'] = $rr['type'];
3854                         $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3855                         $photo['created'] = $rr['created'];
3856                         $photo['edited'] = $rr['edited'];
3857                         $photo['desc'] = $rr['desc'];
3858
3859                         if ($type == "xml") {
3860                                 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3861                         } else {
3862                                 $photo['thumb'] = $thumb;
3863                                 $data['photo'][] = $photo;
3864                         }
3865                 }
3866         }
3867         return api_format_data("photos", $type, $data);
3868 }
3869
3870 /**
3871  * @brief upload a new photo or change an existing photo
3872  *
3873  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3874  * @return string
3875  */
3876 function api_fr_photo_create_update($type)
3877 {
3878         if (api_user() === false) {
3879                 throw new ForbiddenException();
3880         }
3881         // input params
3882         $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3883         $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3884         $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3885         $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3886         $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3887         $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3888         $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3889         $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3890         $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3891
3892         // do several checks on input parameters
3893         // we do not allow calls without album string
3894         if ($album == null) {
3895                 throw new BadRequestException("no albumname specified");
3896         }
3897         // if photo_id == null --> we are uploading a new photo
3898         if ($photo_id == null) {
3899                 $mode = "create";
3900
3901                 // error if no media posted in create-mode
3902                 if (!x($_FILES, 'media')) {
3903                         // Output error
3904                         throw new BadRequestException("no media data submitted");
3905                 }
3906
3907                 // album_new will be ignored in create-mode
3908                 $album_new = "";
3909         } else {
3910                 $mode = "update";
3911
3912                 // check if photo is existing in database
3913                 $r = q(
3914                         "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3915                         intval(api_user()),
3916                         dbesc($photo_id),
3917                         dbesc($album)
3918                 );
3919                 if (!DBM::is_result($r)) {
3920                         throw new BadRequestException("photo not available");
3921                 }
3922         }
3923
3924         // checks on acl strings provided by clients
3925         $acl_input_error = false;
3926         $acl_input_error |= check_acl_input($allow_cid);
3927         $acl_input_error |= check_acl_input($deny_cid);
3928         $acl_input_error |= check_acl_input($allow_gid);
3929         $acl_input_error |= check_acl_input($deny_gid);
3930         if ($acl_input_error) {
3931                 throw new BadRequestException("acl data invalid");
3932         }
3933         // now let's upload the new media in create-mode
3934         if ($mode == "create") {
3935                 $media = $_FILES['media'];
3936                 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3937
3938                 // return success of updating or error message
3939                 if (!is_null($data)) {
3940                         return api_format_data("photo_create", $type, $data);
3941                 } else {
3942                         throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3943                 }
3944         }
3945
3946         // now let's do the changes in update-mode
3947         if ($mode == "update") {
3948                 $sql_extra = "";
3949
3950                 if (!is_null($desc)) {
3951                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3952                 }
3953
3954                 if (!is_null($album_new)) {
3955                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3956                 }
3957
3958                 if (!is_null($allow_cid)) {
3959                         $allow_cid = trim($allow_cid);
3960                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3961                 }
3962
3963                 if (!is_null($deny_cid)) {
3964                         $deny_cid = trim($deny_cid);
3965                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3966                 }
3967
3968                 if (!is_null($allow_gid)) {
3969                         $allow_gid = trim($allow_gid);
3970                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3971                 }
3972
3973                 if (!is_null($deny_gid)) {
3974                         $deny_gid = trim($deny_gid);
3975                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3976                 }
3977
3978                 $result = false;
3979                 if ($sql_extra != "") {
3980                         $nothingtodo = false;
3981                         $result = q(
3982                                 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3983                                 $sql_extra,
3984                                 datetime_convert(),   // update edited timestamp
3985                                 intval(api_user()),
3986                                 dbesc($photo_id),
3987                                 dbesc($album)
3988                         );
3989                 } else {
3990                         $nothingtodo = true;
3991                 }
3992
3993                 if (x($_FILES, 'media')) {
3994                         $nothingtodo = false;
3995                         $media = $_FILES['media'];
3996                         $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3997                         if (!is_null($data)) {
3998                                 return api_format_data("photo_update", $type, $data);
3999                         }
4000                 }
4001
4002                 // return success of updating or error message
4003                 if ($result) {
4004                         $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
4005                         return api_format_data("photo_update", $type, array('$result' => $answer));
4006                 } else {
4007                         if ($nothingtodo) {
4008                                 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
4009                                 return api_format_data("photo_update", $type, array('$result' => $answer));
4010                         }
4011                         throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4012                 }
4013         }
4014         throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4015 }
4016
4017
4018 /**
4019  * @brief delete a single photo from the database through api
4020  *
4021  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4022  * @return string
4023  */
4024 function api_fr_photo_delete($type)
4025 {
4026         if (api_user() === false) {
4027                 throw new ForbiddenException();
4028         }
4029         // input params
4030         $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4031
4032         // do several checks on input parameters
4033         // we do not allow calls without photo id
4034         if ($photo_id == null) {
4035                 throw new BadRequestException("no photo_id specified");
4036         }
4037         // check if photo is existing in database
4038         $r = q(
4039                 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4040                 intval(api_user()),
4041                 dbesc($photo_id)
4042         );
4043         if (!DBM::is_result($r)) {
4044                 throw new BadRequestException("photo not available");
4045         }
4046         // now we can perform on the deletion of the photo
4047         $result = dba::delete('photo', array('uid' => api_user(), 'resource-id' => $photo_id));
4048
4049         // return success of deletion or error message
4050         if ($result) {
4051                 // retrieve the id of the parent element (the photo element)
4052                 $photo_item = q(
4053                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4054                         intval(local_user()),
4055                         dbesc($photo_id)
4056                 );
4057
4058                 if (!DBM::is_result($photo_item)) {
4059                         throw new InternalServerErrorException("problem with deleting items occured");
4060                 }
4061                 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4062                 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4063                 drop_item($photo_item[0]['id'], false);
4064
4065                 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
4066                 return api_format_data("photo_delete", $type, array('$result' => $answer));
4067         } else {
4068                 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4069         }
4070 }
4071
4072
4073 /**
4074  * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4075  *
4076  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4077  * @return string
4078  */
4079 function api_fr_photo_detail($type)
4080 {
4081         if (api_user() === false) {
4082                 throw new ForbiddenException();
4083         }
4084         if (!x($_REQUEST, 'photo_id')) {
4085                 throw new BadRequestException("No photo id.");
4086         }
4087
4088         $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4089         $photo_id = $_REQUEST['photo_id'];
4090
4091         // prepare json/xml output with data from database for the requested photo
4092         $data = prepare_photo_data($type, $scale, $photo_id);
4093
4094         return api_format_data("photo_detail", $type, $data);
4095 }
4096
4097
4098 /**
4099  * @brief updates the profile image for the user (either a specified profile or the default profile)
4100  *
4101  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4102  * @return string
4103  */
4104 function api_account_update_profile_image($type)
4105 {
4106         if (api_user() === false) {
4107                 throw new ForbiddenException();
4108         }
4109         // input params
4110         $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
4111
4112         // error if image data is missing
4113         if (!x($_FILES, 'image')) {
4114                 throw new BadRequestException("no media data submitted");
4115         }
4116
4117         // check if specified profile id is valid
4118         if ($profileid != 0) {
4119                 $r = q(
4120                         "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4121                         intval(api_user()),
4122                         intval($profileid)
4123                 );
4124                 // error message if specified profile id is not in database
4125                 if (!DBM::is_result($r)) {
4126                         throw new BadRequestException("profile_id not available");
4127                 }
4128                 $is_default_profile = $r['profile'];
4129         } else {
4130                 $is_default_profile = 1;
4131         }
4132
4133         // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4134         $media = null;
4135         if (x($_FILES, 'image')) {
4136                 $media = $_FILES['image'];
4137         } elseif (x($_FILES, 'media')) {
4138                 $media = $_FILES['media'];
4139         }
4140         // save new profile image
4141         $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4142
4143         // get filetype
4144         if (is_array($media['type'])) {
4145                 $filetype = $media['type'][0];
4146         } else {
4147                 $filetype = $media['type'];
4148         }
4149         if ($filetype == "image/jpeg") {
4150                 $fileext = "jpg";
4151         } elseif ($filetype == "image/png") {
4152                 $fileext = "png";
4153         }
4154         // change specified profile or all profiles to the new resource-id
4155         if ($is_default_profile) {
4156                 $r = q(
4157                         "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4158                         dbesc($data['photo']['id']),
4159                         intval(local_user())
4160                 );
4161
4162                 $r = q(
4163                         "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s'  WHERE `self` AND `uid` = %d",
4164                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4165                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4166                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4167                         intval(local_user())
4168                 );
4169         } else {
4170                 $r = q(
4171                         "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4172                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4173                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4174                         intval($_REQUEST['profile']),
4175                         intval(local_user())
4176                 );
4177         }
4178
4179         // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4180         // so that browsers will do a cache update unconditionally
4181
4182         $r = q(
4183                 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4184                 dbesc(datetime_convert()),
4185                 intval(local_user())
4186         );
4187
4188         // Update global directory in background
4189         //$user = api_get_user(get_app());
4190         $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4191         if ($url && strlen(Config::get('system', 'directory'))) {
4192                 Worker::add(PRIORITY_LOW, "Directory", $url);
4193         }
4194
4195         Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4196
4197         // output for client
4198         if ($data) {
4199                 return api_account_verify_credentials($type);
4200         } else {
4201                 // SaveMediaToDatabase failed for some reason
4202                 throw new InternalServerErrorException("image upload failed");
4203         }
4204 }
4205
4206 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4207 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4208 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4209 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4210 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4211 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4212 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4213 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4214 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4215
4216
4217 function check_acl_input($acl_string)
4218 {
4219         if ($acl_string == null || $acl_string == " ") {
4220                 return false;
4221         }
4222         $contact_not_found = false;
4223
4224         // split <x><y><z> into array of cid's
4225         preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4226
4227         // check for each cid if it is available on server
4228         $cid_array = $array[0];
4229         foreach ($cid_array as $cid) {
4230                 $cid = str_replace("<", "", $cid);
4231                 $cid = str_replace(">", "", $cid);
4232                 $contact = q(
4233                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4234                         intval($cid),
4235                         intval(api_user())
4236                 );
4237                 $contact_not_found |= !DBM::is_result($contact);
4238         }
4239         return $contact_not_found;
4240 }
4241
4242 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)
4243 {
4244         $visitor   = 0;
4245         $src = "";
4246         $filetype = "";
4247         $filename = "";
4248         $filesize = 0;
4249
4250         if (is_array($media)) {
4251                 if (is_array($media['tmp_name'])) {
4252                         $src = $media['tmp_name'][0];
4253                 } else {
4254                         $src = $media['tmp_name'];
4255                 }
4256                 if (is_array($media['name'])) {
4257                         $filename = basename($media['name'][0]);
4258                 } else {
4259                         $filename = basename($media['name']);
4260                 }
4261                 if (is_array($media['size'])) {
4262                         $filesize = intval($media['size'][0]);
4263                 } else {
4264                         $filesize = intval($media['size']);
4265                 }
4266                 if (is_array($media['type'])) {
4267                         $filetype = $media['type'][0];
4268                 } else {
4269                         $filetype = $media['type'];
4270                 }
4271         }
4272
4273         if ($filetype == "") {
4274                 $filetype=Image::guessType($filename);
4275         }
4276         $imagedata = getimagesize($src);
4277         if ($imagedata) {
4278                 $filetype = $imagedata['mime'];
4279         }
4280         logger(
4281                 "File upload src: " . $src . " - filename: " . $filename .
4282                 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG
4283         );
4284
4285         // check if there was a php upload error
4286         if ($filesize == 0 && $media['error'] == 1) {
4287                 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4288         }
4289         // check against max upload size within Friendica instance
4290         $maximagesize = Config::get('system', 'maximagesize');
4291         if (($maximagesize) && ($filesize > $maximagesize)) {
4292                 $formattedBytes = formatBytes($maximagesize);
4293                 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4294         }
4295
4296         // create Photo instance with the data of the image
4297         $imagedata = @file_get_contents($src);
4298         $Image = new Image($imagedata, $filetype);
4299         if (! $Image->isValid()) {
4300                 throw new InternalServerErrorException("unable to process image data");
4301         }
4302
4303         // check orientation of image
4304         $Image->orient($src);
4305         @unlink($src);
4306
4307         // check max length of images on server
4308         $max_length = Config::get('system', 'max_image_length');
4309         if (! $max_length) {
4310                 $max_length = MAX_IMAGE_LENGTH;
4311         }
4312         if ($max_length > 0) {
4313                 $Image->scaleDown($max_length);
4314                 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4315         }
4316         $width = $Image->getWidth();
4317         $height = $Image->getHeight();
4318
4319         // create a new resource-id if not already provided
4320         $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
4321
4322         if ($mediatype == "photo") {
4323                 // upload normal image (scales 0, 1, 2)
4324                 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4325
4326                 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4327                 if (! $r) {
4328                         logger("photo upload: image upload with scale 0 (original size) failed");
4329                 }
4330                 if ($width > 640 || $height > 640) {
4331                         $Image->scaleDown(640);
4332                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4333                         if (! $r) {
4334                                 logger("photo upload: image upload with scale 1 (640x640) failed");
4335                         }
4336                 }
4337
4338                 if ($width > 320 || $height > 320) {
4339                         $Image->scaleDown(320);
4340                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4341                         if (! $r) {
4342                                 logger("photo upload: image upload with scale 2 (320x320) failed");
4343                         }
4344                 }
4345                 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4346         } elseif ($mediatype == "profileimage") {
4347                 // upload profile image (scales 4, 5, 6)
4348                 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4349
4350                 if ($width > 175 || $height > 175) {
4351                         $Image->scaleDown(175);
4352                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4353                         if (! $r) {
4354                                 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4355                         }
4356                 }
4357
4358                 if ($width > 80 || $height > 80) {
4359                         $Image->scaleDown(80);
4360                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4361                         if (! $r) {
4362                                 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4363                         }
4364                 }
4365
4366                 if ($width > 48 || $height > 48) {
4367                         $Image->scaleDown(48);
4368                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4369                         if (! $r) {
4370                                 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4371                         }
4372                 }
4373                 $Image->__destruct();
4374                 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4375         }
4376
4377         if ($r) {
4378                 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4379                 if ($photo_id == null && $mediatype == "photo") {
4380                         post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4381                 }
4382                 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4383                 return prepare_photo_data($type, false, $hash);
4384         } else {
4385                 throw new InternalServerErrorException("image upload failed");
4386         }
4387 }
4388
4389 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4390 {
4391         // get data about the api authenticated user
4392         $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4393         $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4394
4395         $arr = array();
4396         $arr['guid']          = get_guid(32);
4397         $arr['uid']           = intval(api_user());
4398         $arr['uri']           = $uri;
4399         $arr['parent-uri']    = $uri;
4400         $arr['type']          = 'photo';
4401         $arr['wall']          = 1;
4402         $arr['resource-id']   = $hash;
4403         $arr['contact-id']    = $owner_record[0]['id'];
4404         $arr['owner-name']    = $owner_record[0]['name'];
4405         $arr['owner-link']    = $owner_record[0]['url'];
4406         $arr['owner-avatar']  = $owner_record[0]['thumb'];
4407         $arr['author-name']   = $owner_record[0]['name'];
4408         $arr['author-link']   = $owner_record[0]['url'];
4409         $arr['author-avatar'] = $owner_record[0]['thumb'];
4410         $arr['title']         = "";
4411         $arr['allow_cid']     = $allow_cid;
4412         $arr['allow_gid']     = $allow_gid;
4413         $arr['deny_cid']      = $deny_cid;
4414         $arr['deny_gid']      = $deny_gid;
4415         $arr['last-child']    = 1;
4416         $arr['visible']       = $visibility;
4417         $arr['origin']        = 1;
4418
4419         $typetoext = array(
4420                         'image/jpeg' => 'jpg',
4421                         'image/png' => 'png',
4422                         'image/gif' => 'gif'
4423                         );
4424
4425         // adds link to the thumbnail scale photo
4426         $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4427                                 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4428                                 . '[/url]';
4429
4430         // do the magic for storing the item in the database and trigger the federation to other contacts
4431         item_store($arr);
4432 }
4433
4434 function prepare_photo_data($type, $scale, $photo_id)
4435 {
4436         $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4437         $data_sql = ($scale === false ? "" : "data, ");
4438
4439         // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4440         // clients needs to convert this in their way for further processing
4441         $r = q(
4442                 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4443                                         `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4444                                         MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4445                         FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4446                 $data_sql,
4447                 intval(local_user()),
4448                 dbesc($photo_id),
4449                 $scale_sql
4450         );
4451
4452         $typetoext = array(
4453                 'image/jpeg' => 'jpg',
4454                 'image/png' => 'png',
4455                 'image/gif' => 'gif'
4456         );
4457
4458         // prepare output data for photo
4459         if (DBM::is_result($r)) {
4460                 $data = array('photo' => $r[0]);
4461                 $data['photo']['id'] = $data['photo']['resource-id'];
4462                 if ($scale !== false) {
4463                         $data['photo']['data'] = base64_encode($data['photo']['data']);
4464                 } else {
4465                         unset($data['photo']['datasize']); //needed only with scale param
4466                 }
4467                 if ($type == "xml") {
4468                         $data['photo']['links'] = array();
4469                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4470                                 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4471                                                                                 "scale" => $k,
4472                                                                                 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4473                         }
4474                 } else {
4475                         $data['photo']['link'] = array();
4476                         // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4477                         $i = 0;
4478                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4479                                 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4480                                 $i++;
4481                         }
4482                 }
4483                 unset($data['photo']['resource-id']);
4484                 unset($data['photo']['minscale']);
4485                 unset($data['photo']['maxscale']);
4486         } else {
4487                 throw new NotFoundException();
4488         }
4489
4490         // retrieve item element for getting activities (like, dislike etc.) related to photo
4491         $item = q(
4492                 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4493                 intval(local_user()),
4494                 dbesc($photo_id)
4495         );
4496         $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4497
4498         // retrieve comments on photo
4499         $r = q(
4500                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4501                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4502                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4503                 `contact`.`id` AS `cid`
4504                 FROM `item`
4505                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4506                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4507                 WHERE `item`.`parent` = %d AND `item`.`visible`
4508                 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4509                 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4510                 intval($item[0]['parent']),
4511                 intval(api_user()),
4512                 dbesc(ACTIVITY_POST)
4513         );
4514
4515         // prepare output of comments
4516         $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4517         $comments = array();
4518         if ($type == "xml") {
4519                 $k = 0;
4520                 foreach ($commentData as $comment) {
4521                         $comments[$k++ . ":comment"] = $comment;
4522                 }
4523         } else {
4524                 foreach ($commentData as $comment) {
4525                         $comments[] = $comment;
4526                 }
4527         }
4528         $data['photo']['friendica_comments'] = $comments;
4529
4530         // include info if rights on photo and rights on item are mismatching
4531         $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4532                 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4533                 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4534                 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4535         $data['photo']['rights_mismatch'] = $rights_mismatch;
4536
4537         return $data;
4538 }
4539
4540
4541 /**
4542  * Similar as /mod/redir.php
4543  * redirect to 'url' after dfrn auth
4544  *
4545  * Why this when there is mod/redir.php already?
4546  * This use api_user() and api_login()
4547  *
4548  * params
4549  *              c_url: url of remote contact to auth to
4550  *              url: string, url to redirect after auth
4551  */
4552 function api_friendica_remoteauth()
4553 {
4554         $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4555         $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4556
4557         if ($url === '' || $c_url === '') {
4558                 throw new BadRequestException("Wrong parameters.");
4559         }
4560
4561         $c_url = normalise_link($c_url);
4562
4563         // traditional DFRN
4564
4565         $r = q(
4566                 "SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4567                 dbesc($c_url),
4568                 intval(api_user())
4569         );
4570
4571         if ((! DBM::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4572                 throw new BadRequestException("Unknown contact");
4573         }
4574
4575         $cid = $r[0]['id'];
4576
4577         $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4578
4579         if ($r[0]['duplex'] && $r[0]['issued-id']) {
4580                 $orig_id = $r[0]['issued-id'];
4581                 $dfrn_id = '1:' . $orig_id;
4582         }
4583         if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4584                 $orig_id = $r[0]['dfrn-id'];
4585                 $dfrn_id = '0:' . $orig_id;
4586         }
4587
4588         $sec = random_string();
4589
4590         q(
4591                 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4592                 VALUES( %d, %s, '%s', '%s', %d )",
4593                 intval(api_user()),
4594                 intval($cid),
4595                 dbesc($dfrn_id),
4596                 dbesc($sec),
4597                 intval(time() + 45)
4598         );
4599
4600         logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4601         $dest = (($url) ? '&destination_url=' . $url : '');
4602         goaway(
4603                 $r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4604                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4605                 . '&type=profile&sec=' . $sec . $dest . $quiet
4606         );
4607 }
4608 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4609
4610 /**
4611  * @brief Return the item shared, if the item contains only the [share] tag
4612  *
4613  * @param array $item Sharer item
4614  * @return array Shared item or false if not a reshare
4615  */
4616 function api_share_as_retweet(&$item)
4617 {
4618         $body = trim($item["body"]);
4619
4620         if (Diaspora::isReshare($body, false)===false) {
4621                 return false;
4622         }
4623
4624         /// @TODO "$1" should maybe mean '$1' ?
4625         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4626         /*
4627                 * Skip if there is no shared message in there
4628                 * we already checked this in diaspora::isReshare()
4629                 * but better one more than one less...
4630                 */
4631         if ($body == $attributes) {
4632                 return false;
4633         }
4634
4635
4636         // build the fake reshared item
4637         $reshared_item = $item;
4638
4639         $author = "";
4640         preg_match("/author='(.*?)'/ism", $attributes, $matches);
4641         if ($matches[1] != "") {
4642                 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4643         }
4644
4645         preg_match('/author="(.*?)"/ism', $attributes, $matches);
4646         if ($matches[1] != "") {
4647                 $author = $matches[1];
4648         }
4649
4650         $profile = "";
4651         preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4652         if ($matches[1] != "") {
4653                 $profile = $matches[1];
4654         }
4655
4656         preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4657         if ($matches[1] != "") {
4658                 $profile = $matches[1];
4659         }
4660
4661         $avatar = "";
4662         preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4663         if ($matches[1] != "") {
4664                 $avatar = $matches[1];
4665         }
4666
4667         preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4668         if ($matches[1] != "") {
4669                 $avatar = $matches[1];
4670         }
4671
4672         $link = "";
4673         preg_match("/link='(.*?)'/ism", $attributes, $matches);
4674         if ($matches[1] != "") {
4675                 $link = $matches[1];
4676         }
4677
4678         preg_match('/link="(.*?)"/ism', $attributes, $matches);
4679         if ($matches[1] != "") {
4680                 $link = $matches[1];
4681         }
4682
4683         $posted = "";
4684         preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4685         if ($matches[1] != "")
4686                 $posted = $matches[1];
4687
4688         preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4689         if ($matches[1] != "") {
4690                 $posted = $matches[1];
4691         }
4692
4693         $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4694
4695         if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4696                 return false;
4697         }
4698
4699         $reshared_item["body"] = $shared_body;
4700         $reshared_item["author-name"] = $author;
4701         $reshared_item["author-link"] = $profile;
4702         $reshared_item["author-avatar"] = $avatar;
4703         $reshared_item["plink"] = $link;
4704         $reshared_item["created"] = $posted;
4705         $reshared_item["edited"] = $posted;
4706
4707         return $reshared_item;
4708
4709 }
4710
4711 function api_get_nick($profile)
4712 {
4713         /* To-Do:
4714                 - remove trailing junk from profile url
4715                 - pump.io check has to check the website
4716         */
4717
4718         $nick = "";
4719
4720         $r = q(
4721                 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4722                 dbesc(normalise_link($profile))
4723         );
4724
4725         if (DBM::is_result($r)) {
4726                 $nick = $r[0]["nick"];
4727         }
4728
4729         if (!$nick == "") {
4730                 $r = q(
4731                         "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4732                         dbesc(normalise_link($profile))
4733                 );
4734
4735                 if (DBM::is_result($r)) {
4736                         $nick = $r[0]["nick"];
4737                 }
4738         }
4739
4740         if (!$nick == "") {
4741                 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4742                 if ($friendica != $profile) {
4743                         $nick = $friendica;
4744                 }
4745         }
4746
4747         if (!$nick == "") {
4748                 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4749                 if ($diaspora != $profile) {
4750                         $nick = $diaspora;
4751                 }
4752         }
4753
4754         if (!$nick == "") {
4755                 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4756                 if ($twitter != $profile) {
4757                         $nick = $twitter;
4758                 }
4759         }
4760
4761
4762         if (!$nick == "") {
4763                 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4764                 if ($StatusnetHost != $profile) {
4765                         $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4766                         if ($StatusnetUser != $profile) {
4767                                 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4768                                 $user = json_decode($UserData);
4769                                 if ($user) {
4770                                         $nick = $user->screen_name;
4771                                 }
4772                         }
4773                 }
4774         }
4775
4776         // To-Do: look at the page if its really a pumpio site
4777         //if (!$nick == "") {
4778         //      $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4779         //      if ($pumpio != $profile)
4780         //              $nick = $pumpio;
4781                 //      <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4782
4783         //}
4784
4785         if ($nick != "") {
4786                 return $nick;
4787         }
4788
4789         return false;
4790 }
4791
4792 function api_in_reply_to($item)
4793 {
4794         $in_reply_to = array();
4795
4796         $in_reply_to['status_id'] = null;
4797         $in_reply_to['user_id'] = null;
4798         $in_reply_to['status_id_str'] = null;
4799         $in_reply_to['user_id_str'] = null;
4800         $in_reply_to['screen_name'] = null;
4801
4802         if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4803                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4804                         intval($item['uid']),
4805                         dbesc($item['thr-parent']));
4806
4807                 if (DBM::is_result($r)) {
4808                         $in_reply_to['status_id'] = intval($r[0]['id']);
4809                 } else {
4810                         $in_reply_to['status_id'] = intval($item['parent']);
4811                 }
4812
4813                 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4814
4815                 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4816                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4817                         WHERE `item`.`id` = %d LIMIT 1",
4818                         intval($in_reply_to['status_id'])
4819                 );
4820
4821                 if (DBM::is_result($r)) {
4822                         if ($r[0]['nick'] == "") {
4823                                 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4824                         }
4825
4826                         $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4827                         $in_reply_to['user_id'] = intval($r[0]['id']);
4828                         $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4829                 }
4830
4831                 // There seems to be situation, where both fields are identical:
4832                 // https://github.com/friendica/friendica/issues/1010
4833                 // This is a bugfix for that.
4834                 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4835                         logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4836                         $in_reply_to['status_id'] = null;
4837                         $in_reply_to['user_id'] = null;
4838                         $in_reply_to['status_id_str'] = null;
4839                         $in_reply_to['user_id_str'] = null;
4840                         $in_reply_to['screen_name'] = null;
4841                 }
4842         }
4843
4844         return $in_reply_to;
4845 }
4846
4847 function api_clean_plain_items($Text)
4848 {
4849         $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4850
4851         $Text = bb_CleanPictureLinks($Text);
4852         $URLSearchString = "^\[\]";
4853
4854         $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
4855
4856         if ($include_entities == "true") {
4857                 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
4858         }
4859
4860         // Simplify "attachment" element
4861         $Text = api_clean_attachments($Text);
4862
4863         return($Text);
4864 }
4865
4866 /**
4867  * @brief Removes most sharing information for API text export
4868  *
4869  * @param string $body The original body
4870  *
4871  * @return string Cleaned body
4872  */
4873 function api_clean_attachments($body)
4874 {
4875         $data = get_attachment_data($body);
4876
4877         if (!$data)
4878                 return $body;
4879
4880         $body = "";
4881
4882         if (isset($data["text"]))
4883                 $body = $data["text"];
4884
4885         if (($body == "") && (isset($data["title"])))
4886                 $body = $data["title"];
4887
4888         if (isset($data["url"]))
4889                 $body .= "\n".$data["url"];
4890
4891         $body .= $data["after"];
4892
4893         return $body;
4894 }
4895
4896 function api_best_nickname(&$contacts)
4897 {
4898         $best_contact = array();
4899
4900         if (count($contact) == 0)
4901                 return;
4902
4903         foreach ($contacts as $contact)
4904                 if ($contact["network"] == "") {
4905                         $contact["network"] = "dfrn";
4906                         $best_contact = array($contact);
4907                 }
4908
4909         if (sizeof($best_contact) == 0)
4910                 foreach ($contacts as $contact)
4911                         if ($contact["network"] == "dfrn")
4912                                 $best_contact = array($contact);
4913
4914         if (sizeof($best_contact) == 0)
4915                 foreach ($contacts as $contact)
4916                         if ($contact["network"] == "dspr")
4917                                 $best_contact = array($contact);
4918
4919         if (sizeof($best_contact) == 0)
4920                 foreach ($contacts as $contact)
4921                         if ($contact["network"] == "stat")
4922                                 $best_contact = array($contact);
4923
4924         if (sizeof($best_contact) == 0)
4925                 foreach ($contacts as $contact)
4926                         if ($contact["network"] == "pump")
4927                                 $best_contact = array($contact);
4928
4929         if (sizeof($best_contact) == 0)
4930                 foreach ($contacts as $contact)
4931                         if ($contact["network"] == "twit")
4932                                 $best_contact = array($contact);
4933
4934         if (sizeof($best_contact) == 1) {
4935                 $contacts = $best_contact;
4936         } else {
4937                 $contacts = array($contacts[0]);
4938         }
4939 }
4940
4941 // return all or a specified group of the user with the containing contacts
4942 function api_friendica_group_show($type)
4943 {
4944         $a = get_app();
4945
4946         if (api_user() === false) throw new ForbiddenException();
4947
4948         // params
4949         $user_info = api_get_user($a);
4950         $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4951         $uid = $user_info['uid'];
4952
4953         // get data of the specified group id or all groups if not specified
4954         if ($gid != 0) {
4955                 $r = q(
4956                         "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4957                         intval($uid),
4958                         intval($gid)
4959                 );
4960                 // error message if specified gid is not in database
4961                 if (!DBM::is_result($r))
4962                         throw new BadRequestException("gid not available");
4963         } else {
4964                 $r = q(
4965                         "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4966                         intval($uid)
4967                 );
4968         }
4969
4970         // loop through all groups and retrieve all members for adding data in the user array
4971         foreach ($r as $rr) {
4972                 $members = Contact::getByGroupId($rr['id']);
4973                 $users = array();
4974
4975                 if ($type == "xml") {
4976                         $user_element = "users";
4977                         $k = 0;
4978                         foreach ($members as $member) {
4979                                 $user = api_get_user($a, $member['nurl']);
4980                                 $users[$k++.":user"] = $user;
4981                         }
4982                 } else {
4983                         $user_element = "user";
4984                         foreach ($members as $member) {
4985                                 $user = api_get_user($a, $member['nurl']);
4986                                 $users[] = $user;
4987                         }
4988                 }
4989                 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4990         }
4991         return api_format_data("groups", $type, array('group' => $grps));
4992 }
4993 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4994
4995
4996 // delete the specified group of the user
4997 function api_friendica_group_delete($type)
4998 {
4999         $a = get_app();
5000
5001         if (api_user() === false) {
5002                 throw new ForbiddenException();
5003         }
5004
5005         // params
5006         $user_info = api_get_user($a);
5007         $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5008         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5009         $uid = $user_info['uid'];
5010
5011         // error if no gid specified
5012         if ($gid == 0 || $name == "") {
5013                 throw new BadRequestException('gid or name not specified');
5014         }
5015
5016         // get data of the specified group id
5017         $r = q(
5018                 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5019                 intval($uid),
5020                 intval($gid)
5021         );
5022         // error message if specified gid is not in database
5023         if (!DBM::is_result($r)) {
5024                 throw new BadRequestException('gid not available');
5025         }
5026
5027         // get data of the specified group id and group name
5028         $rname = q(
5029                 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5030                 intval($uid),
5031                 intval($gid),
5032                 dbesc($name)
5033         );
5034         // error message if specified gid is not in database
5035         if (!DBM::is_result($rname)) {
5036                 throw new BadRequestException('wrong group name');
5037         }
5038
5039         // delete group
5040         $ret = Group::removeByName($uid, $name);
5041         if ($ret) {
5042                 // return success
5043                 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
5044                 return api_format_data("group_delete", $type, array('result' => $success));
5045         } else {
5046                 throw new BadRequestException('other API error');
5047         }
5048 }
5049 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5050
5051
5052 // create the specified group with the posted array of contacts
5053 function api_friendica_group_create($type)
5054 {
5055         $a = get_app();
5056
5057         if (api_user() === false) throw new ForbiddenException();
5058
5059         // params
5060         $user_info = api_get_user($a);
5061         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5062         $uid = $user_info['uid'];
5063         $json = json_decode($_POST['json'], true);
5064         $users = $json['user'];
5065
5066         // error if no name specified
5067         if ($name == "")
5068                 throw new BadRequestException('group name not specified');
5069
5070         // get data of the specified group name
5071         $rname = q(
5072                 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5073                 intval($uid),
5074                 dbesc($name)
5075         );
5076         // error message if specified group name already exists
5077         if (DBM::is_result($rname))
5078                 throw new BadRequestException('group name already exists');
5079
5080         // check if specified group name is a deleted group
5081         $rname = q(
5082                 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5083                 intval($uid),
5084                 dbesc($name)
5085         );
5086         // error message if specified group name already exists
5087         if (DBM::is_result($rname))
5088                 $reactivate_group = true;
5089
5090         // create group
5091         $ret = Group::create($uid, $name);
5092         if ($ret) {
5093                 $gid = Group::getIdByName($uid, $name);
5094         } else {
5095                 throw new BadRequestException('other API error');
5096         }
5097
5098         // add members
5099         $erroraddinguser = false;
5100         $errorusers = array();
5101         foreach ($users as $user) {
5102                 $cid = $user['cid'];
5103                 // check if user really exists as contact
5104                 $contact = q(
5105                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5106                         intval($cid),
5107                         intval($uid)
5108                 );
5109                 if (count($contact))
5110                         $result = Group::addMember($gid, $cid);
5111                 else {
5112                         $erroraddinguser = true;
5113                         $errorusers[] = $cid;
5114                 }
5115         }
5116
5117         // return success message incl. missing users in array
5118         $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
5119         $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
5120         return api_format_data("group_create", $type, array('result' => $success));
5121 }
5122 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5123
5124
5125 // update the specified group with the posted array of contacts
5126 function api_friendica_group_update($type)
5127 {
5128         $a = get_app();
5129
5130         if (api_user() === false) throw new ForbiddenException();
5131
5132         // params
5133         $user_info = api_get_user($a);
5134         $uid = $user_info['uid'];
5135         $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5136         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5137         $json = json_decode($_POST['json'], true);
5138         $users = $json['user'];
5139
5140         // error if no name specified
5141         if ($name == "")
5142                 throw new BadRequestException('group name not specified');
5143
5144         // error if no gid specified
5145         if ($gid == "")
5146                 throw new BadRequestException('gid not specified');
5147
5148         // remove members
5149         $members = Contact::getByGroupId($gid);
5150         foreach ($members as $member) {
5151                 $cid = $member['id'];
5152                 foreach ($users as $user) {
5153                         $found = ($user['cid'] == $cid ? true : false);
5154                 }
5155                 if (!$found) {
5156                         $ret = Group::removeMemberByName($uid, $name, $cid);
5157                 }
5158         }
5159
5160         // add members
5161         $erroraddinguser = false;
5162         $errorusers = array();
5163         foreach ($users as $user) {
5164                 $cid = $user['cid'];
5165                 // check if user really exists as contact
5166                 $contact = q(
5167                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5168                         intval($cid),
5169                         intval($uid)
5170                 );
5171
5172                 if (count($contact)) {
5173                         $result = Group::addMember($gid, $cid);
5174                 } else {
5175                         $erroraddinguser = true;
5176                         $errorusers[] = $cid;
5177                 }
5178         }
5179
5180         // return success message incl. missing users in array
5181         $status = ($erroraddinguser ? "missing user" : "ok");
5182         $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
5183         return api_format_data("group_update", $type, array('result' => $success));
5184 }
5185
5186 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5187
5188 function api_friendica_activity($type)
5189 {
5190         $a = get_app();
5191
5192         if (api_user() === false) throw new ForbiddenException();
5193         $verb = strtolower($a->argv[3]);
5194         $verb = preg_replace("|\..*$|", "", $verb);
5195
5196         $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5197
5198         $res = do_like($id, $verb);
5199
5200         if ($res) {
5201                 if ($type == "xml") {
5202                         $ok = "true";
5203                 } else {
5204                         $ok = "ok";
5205                 }
5206                 return api_format_data('ok', $type, array('ok' => $ok));
5207         } else {
5208                 throw new BadRequestException('Error adding activity');
5209         }
5210 }
5211
5212 /// @TODO move to top of file or somwhere better
5213 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5214 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5215 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5216 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5217 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5218 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5219 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5220 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5221 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5222 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5223
5224 /**
5225  * @brief Returns notifications
5226  *
5227  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5228  * @return string
5229 */
5230 function api_friendica_notification($type)
5231 {
5232         $a = get_app();
5233
5234         if (api_user() === false) throw new ForbiddenException();
5235         if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
5236         $nm = new NotificationsManager();
5237
5238         $notes = $nm->getAll(array(), "+seen -date", 50);
5239
5240         if ($type == "xml") {
5241                 $xmlnotes = array();
5242                 foreach ($notes as $note)
5243                         $xmlnotes[] = array("@attributes" => $note);
5244
5245                 $notes = $xmlnotes;
5246         }
5247
5248         return api_format_data("notes", $type, array('note' => $notes));
5249 }
5250
5251 /**
5252  * @brief Set notification as seen and returns associated item (if possible)
5253  *
5254  * POST request with 'id' param as notification id
5255  *
5256  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5257  * @return string
5258  */
5259 function api_friendica_notification_seen($type)
5260 {
5261         $a = get_app();
5262
5263         if (api_user() === false) throw new ForbiddenException();
5264         if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
5265
5266         $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5267
5268         $nm = new NotificationsManager();
5269         $note = $nm->getByID($id);
5270         if (is_null($note)) throw new BadRequestException("Invalid argument");
5271
5272         $nm->setSeen($note);
5273         if ($note['otype']=='item') {
5274                 // would be really better with an ItemsManager and $im->getByID() :-P
5275                 $r = q(
5276                         "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5277                         intval($note['iid']),
5278                         intval(local_user())
5279                 );
5280                 if ($r!==false) {
5281                         // we found the item, return it to the user
5282                         $user_info = api_get_user($a);
5283                         $ret = api_format_items($r, $user_info, false, $type);
5284                         $data = array('status' => $ret);
5285                         return api_format_data("status", $type, $data);
5286                 }
5287                 // the item can't be found, but we set the note as seen, so we count this as a success
5288         }
5289         return api_format_data('result', $type, array('result' => "success"));
5290 }
5291
5292 /// @TODO move to top of file or somwhere better
5293 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5294 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5295
5296 /**
5297  * @brief update a direct_message to seen state
5298  *
5299  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5300  * @return string (success result=ok, error result=error with error message)
5301  */
5302 function api_friendica_direct_messages_setseen($type)
5303 {
5304         $a = get_app();
5305         if (api_user() === false) {
5306                 throw new ForbiddenException();
5307         }
5308
5309         // params
5310         $user_info = api_get_user($a);
5311         $uid = $user_info['uid'];
5312         $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5313
5314         // return error if id is zero
5315         if ($id == "") {
5316                 $answer = array('result' => 'error', 'message' => 'message id not specified');
5317                 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5318         }
5319
5320         // get data of the specified message id
5321         $r = q(
5322                 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5323                 intval($id),
5324                 intval($uid)
5325         );
5326
5327         // error message if specified id is not in database
5328         if (!DBM::is_result($r)) {
5329                 $answer = array('result' => 'error', 'message' => 'message id not in database');
5330                 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5331         }
5332
5333         // update seen indicator
5334         $result = q(
5335                 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5336                 intval($id),
5337                 intval($uid)
5338         );
5339
5340         if ($result) {
5341                 // return success
5342                 $answer = array('result' => 'ok', 'message' => 'message set to seen');
5343                 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
5344         } else {
5345                 $answer = array('result' => 'error', 'message' => 'unknown error');
5346                 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5347         }
5348 }
5349
5350 /// @TODO move to top of file or somwhere better
5351 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5352
5353 /**
5354  * @brief search for direct_messages containing a searchstring through api
5355  *
5356  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5357  * @return string (success: success=true if found and search_result contains found messages
5358  *                          success=false if nothing was found, search_result='nothing found',
5359  *                 error: result=error with error message)
5360  */
5361 function api_friendica_direct_messages_search($type)
5362 {
5363         $a = get_app();
5364
5365         if (api_user() === false) {
5366                 throw new ForbiddenException();
5367         }
5368
5369         // params
5370         $user_info = api_get_user($a);
5371         $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5372         $uid = $user_info['uid'];
5373
5374         // error if no searchstring specified
5375         if ($searchstring == "") {
5376                 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
5377                 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
5378         }
5379
5380         // get data for the specified searchstring
5381         $r = q(
5382                 "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",
5383                 intval($uid),
5384                 dbesc('%'.$searchstring.'%')
5385         );
5386
5387         $profile_url = $user_info["url"];
5388
5389         // message if nothing was found
5390         if (!DBM::is_result($r)) {
5391                 $success = array('success' => false, 'search_results' => 'problem with query');
5392         } elseif (count($r) == 0) {
5393                 $success = array('success' => false, 'search_results' => 'nothing found');
5394         } else {
5395                 $ret = array();
5396                 foreach ($r as $item) {
5397                         if ($box == "inbox" || $item['from-url'] != $profile_url) {
5398                                 $recipient = $user_info;
5399                                 $sender = api_get_user($a, normalise_link($item['contact-url']));
5400                         } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5401                                 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5402                                 $sender = $user_info;
5403                         }
5404
5405                         $ret[] = api_format_messages($item, $recipient, $sender);
5406                 }
5407                 $success = array('success' => true, 'search_results' => $ret);
5408         }
5409
5410         return api_format_data("direct_message_search", $type, array('$result' => $success));
5411 }
5412
5413 /// @TODO move to top of file or somwhere better
5414 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5415
5416 /**
5417  * @brief return data of all the profiles a user has to the client
5418  *
5419  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5420  * @return string
5421  */
5422 function api_friendica_profile_show($type)
5423 {
5424         $a = get_app();
5425
5426         if (api_user() === false) {
5427                 throw new ForbiddenException();
5428         }
5429
5430         // input params
5431         $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5432
5433         // retrieve general information about profiles for user
5434         $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5435         $directory = Config::get('system', 'directory');
5436
5437         // get data of the specified profile id or all profiles of the user if not specified
5438         if ($profileid != 0) {
5439                 $r = q(
5440                         "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5441                         intval(api_user()),
5442                         intval($profileid)
5443                 );
5444
5445                 // error message if specified gid is not in database
5446                 if (!DBM::is_result($r)) {
5447                         throw new BadRequestException("profile_id not available");
5448                 }
5449         } else {
5450                 $r = q(
5451                         "SELECT * FROM `profile` WHERE `uid` = %d",
5452                         intval(api_user())
5453                 );
5454         }
5455         // loop through all returned profiles and retrieve data and users
5456         $k = 0;
5457         foreach ($r as $rr) {
5458                 $profile = api_format_items_profiles($rr, $type);
5459
5460                 // select all users from contact table, loop and prepare standard return for user data
5461                 $users = array();
5462                 $r = q(
5463                         "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5464                         intval(api_user()),
5465                         intval($rr['profile_id'])
5466                 );
5467
5468                 foreach ($r as $rr) {
5469                         $user = api_get_user($a, $rr['nurl']);
5470                         ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5471                 }
5472                 $profile['users'] = $users;
5473
5474                 // add prepared profile data to array for final return
5475                 if ($type == "xml") {
5476                         $profiles[$k++ . ":profile"] = $profile;
5477                 } else {
5478                         $profiles[] = $profile;
5479                 }
5480         }
5481
5482         // return settings, authenticated user and profiles data
5483         $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5484
5485         $result = array('multi_profiles' => $multi_profiles ? true : false,
5486                                         'global_dir' => $directory,
5487                                         'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5488                                         'profiles' => $profiles);
5489         return api_format_data("friendica_profiles", $type, array('$result' => $result));
5490 }
5491 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5492
5493 /*
5494 @TODO Maybe open to implement?
5495 To.Do:
5496     [pagename] => api/1.1/statuses/lookup.json
5497     [id] => 605138389168451584
5498     [include_cards] => true
5499     [cards_platform] => Android-12
5500     [include_entities] => true
5501     [include_my_retweet] => 1
5502     [include_rts] => 1
5503     [include_reply_count] => true
5504     [include_descendent_reply_count] => true
5505 (?)
5506
5507
5508 Not implemented by now:
5509 statuses/retweets_of_me
5510 friendships/create
5511 friendships/destroy
5512 friendships/exists
5513 friendships/show
5514 account/update_location
5515 account/update_profile_background_image
5516 blocks/create
5517 blocks/destroy
5518 friendica/profile/update
5519 friendica/profile/create
5520 friendica/profile/delete
5521
5522 Not implemented in status.net:
5523 statuses/retweeted_to_me
5524 statuses/retweeted_by_me
5525 direct_messages/destroy
5526 account/end_session
5527 account/update_delivery_device
5528 notifications/follow
5529 notifications/leave
5530 blocks/exists
5531 blocks/blocking
5532 lists
5533 */