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