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