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