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