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