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