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