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