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