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