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