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