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