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