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