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