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