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