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