]> git.mxchange.org Git - friendica.git/blob - include/api.php
Merge pull request #4103 from Rudloff/feature/profile_colors
[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  * Returns statuses that match a specified query.
1522  *
1523  * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1524  *
1525  * @param string $type Return format: json, xml, atom, rss
1526  *
1527  * @return array|string
1528  * @throws UnauthorizedException
1529  * @throws BadRequestException
1530  */
1531 function api_search($type)
1532 {
1533         $data = array();
1534
1535         if (!x($_REQUEST, 'q')) {
1536                 throw new BadRequestException("q parameter is required.");
1537         }
1538
1539         if (x($_REQUEST, 'rpp')) {
1540                 $count = $_REQUEST['rpp'];
1541         } elseif (x($_REQUEST, 'count')) {
1542                 $count = $_REQUEST['count'];
1543         } else {
1544                 $count = 15;
1545         }
1546
1547         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1548         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1549         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1550
1551         $start = $page * $count;
1552
1553         if ($max_id > 0) {
1554                 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1555         }
1556
1557         $r = dba::p(
1558                 "SELECT ".item_fieldlists()."
1559                 FROM `item` ".item_joins()."
1560                 WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1561                 AND `item`.`body` LIKE CONCAT('%',?,'%')
1562                 $sql_extra
1563                 AND `item`.`id`>?
1564                 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
1565                 api_user(),
1566                 $_REQUEST['q'],
1567                 $since_id
1568         );
1569
1570         $data['status'] = api_format_items(dba::inArray($r), api_get_user(get_app()));
1571
1572         return api_format_data("statuses", $type, $data);
1573 }
1574
1575 /// @TODO move to top of file or somewhere better
1576 api_register_func('api/search/tweets', 'api_search', true);
1577 api_register_func('api/search', 'api_search', true);
1578
1579 /**
1580  *
1581  * http://developer.twitter.com/doc/get/statuses/home_timeline
1582  *
1583  * TODO: Optional parameters
1584  * TODO: Add reply info
1585  */
1586 function api_statuses_home_timeline($type)
1587 {
1588         $a = get_app();
1589
1590         if (api_user() === false) {
1591                 throw new ForbiddenException();
1592         }
1593
1594         unset($_REQUEST["user_id"]);
1595         unset($_GET["user_id"]);
1596
1597         unset($_REQUEST["screen_name"]);
1598         unset($_GET["screen_name"]);
1599
1600         $user_info = api_get_user($a);
1601         // get last newtork messages
1602
1603         // params
1604         $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1605         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1606         if ($page < 0) {
1607                 $page = 0;
1608         }
1609         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1610         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1611         //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1612         $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1613         $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1614
1615         $start = $page * $count;
1616
1617         $sql_extra = '';
1618         if ($max_id > 0) {
1619                 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1620         }
1621         if ($exclude_replies > 0) {
1622                 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1623         }
1624         if ($conversation_id > 0) {
1625                 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1626         }
1627
1628         $r = q(
1629                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1630                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1631                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1632                 `contact`.`id` AS `cid`
1633                 FROM `item`
1634                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1635                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1636                 WHERE `item`.`uid` = %d AND `verb` = '%s'
1637                 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1638                 $sql_extra
1639                 AND `item`.`id`>%d
1640                 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1641                 intval(api_user()),
1642                 dbesc(ACTIVITY_POST),
1643                 intval($since_id),
1644                 intval($start),
1645                 intval($count)
1646         );
1647
1648         $ret = api_format_items($r, $user_info, false, $type);
1649
1650         // Set all posts from the query above to seen
1651         $idarray = array();
1652         foreach ($r as $item) {
1653                 $idarray[] = intval($item["id"]);
1654         }
1655
1656         $idlist = implode(",", $idarray);
1657
1658         if ($idlist != "") {
1659                 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1660
1661                 if ($unseen) {
1662                         $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1663                 }
1664         }
1665
1666         $data = array('status' => $ret);
1667         switch ($type) {
1668                 case "atom":
1669                 case "rss":
1670                         $data = api_rss_extra($a, $data, $user_info);
1671                         break;
1672         }
1673
1674         return api_format_data("statuses", $type, $data);
1675 }
1676
1677 /// @TODO move to top of file or somewhere better
1678 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1679 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1680
1681 function api_statuses_public_timeline($type)
1682 {
1683         $a = get_app();
1684
1685         if (api_user() === false) {
1686                 throw new ForbiddenException();
1687         }
1688
1689         $user_info = api_get_user($a);
1690         // get last newtork messages
1691
1692         // params
1693         $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1694         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1695         if ($page < 0) {
1696                 $page = 0;
1697         }
1698         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1699         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1700         //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1701         $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1702         $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1703
1704         $start = $page * $count;
1705
1706         if ($exclude_replies && !$conversation_id) {
1707                 if ($max_id > 0) {
1708                         $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1709                 }
1710
1711                 $r = dba::p("SELECT " . item_fieldlists() . "
1712                         FROM `thread`
1713                         STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1714                         " . item_joins() . "
1715                         STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1716                                 AND NOT `user`.`hidewall`
1717                         AND `verb` = ?
1718                         AND NOT `thread`.`private`
1719                         AND `thread`.`wall`
1720                         AND `thread`.`visible`
1721                         AND NOT `thread`.`deleted`
1722                         AND NOT `thread`.`moderated`
1723                         AND `thread`.`iid` > ?
1724                         $sql_extra
1725                         ORDER BY `thread`.`iid` DESC
1726                         LIMIT " . intval($start) . ", " . intval($count),
1727                         ACTIVITY_POST,
1728                         $since_id
1729                 );
1730
1731                 $r = dba::inArray($r);
1732         } else {
1733                 if ($max_id > 0) {
1734                         $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1735                 }
1736                 if ($conversation_id > 0) {
1737                         $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1738                 }
1739
1740                 $r = dba::p("SELECT " . item_fieldlists() . "
1741                         FROM `item`
1742                         " . item_joins() . "
1743                         STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1744                                 AND NOT `user`.`hidewall`
1745                         AND `verb` = ?
1746                         AND NOT `item`.`private`
1747                         AND `item`.`wall`
1748                         AND `item`.`visible`
1749                         AND NOT `item`.`deleted`
1750                         AND NOT `item`.`moderated`
1751                         AND `item`.`id` > ?
1752                         $sql_extra
1753                         ORDER BY `item`.`id` DESC
1754                         LIMIT " . intval($start) . ", " . intval($count),
1755                         ACTIVITY_POST,
1756                         $since_id
1757                 );
1758
1759                 $r = dba::inArray($r);
1760         }
1761
1762         $ret = api_format_items($r, $user_info, false, $type);
1763
1764         $data = array('status' => $ret);
1765         switch ($type) {
1766                 case "atom":
1767                 case "rss":
1768                         $data = api_rss_extra($a, $data, $user_info);
1769                         break;
1770         }
1771
1772         return api_format_data("statuses", $type, $data);
1773 }
1774
1775 /// @TODO move to top of file or somewhere better
1776 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1777
1778 /**
1779  * @brief Returns the list of public federated posts this node knows about
1780  *
1781  * @param string $type Return format: json, xml, atom, rss
1782  * @return array|string
1783  * @throws ForbiddenException
1784  */
1785 function api_statuses_networkpublic_timeline($type)
1786 {
1787         $a = get_app();
1788
1789         if (api_user() === false) {
1790                 throw new ForbiddenException();
1791         }
1792
1793         $user_info = api_get_user($a);
1794
1795         $since_id        = x($_REQUEST, 'since_id')        ? $_REQUEST['since_id']        : 0;
1796         $max_id          = x($_REQUEST, 'max_id')          ? $_REQUEST['max_id']          : 0;
1797
1798         // pagination
1799         $count = x($_REQUEST, 'count') ? $_REQUEST['count']   : 20;
1800         $page  = x($_REQUEST, 'page')  ? $_REQUEST['page']    : 1;
1801         if ($page < 1) {
1802                 $page = 1;
1803         }
1804         $start = ($page - 1) * $count;
1805
1806         $sql_extra = '';
1807         if ($max_id > 0) {
1808                 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1809         }
1810
1811         $r = dba::p("SELECT " . item_fieldlists() . "
1812                 FROM `thread`
1813                 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1814                 " . item_joins() . "
1815                 WHERE `thread`.`uid` = 0
1816                 AND `verb` = ?
1817                 AND NOT `thread`.`private`
1818                 AND `thread`.`visible`
1819                 AND NOT `thread`.`deleted`
1820                 AND NOT `thread`.`moderated`
1821                 AND `thread`.`iid` > ?
1822                 $sql_extra
1823                 ORDER BY `thread`.`iid` DESC
1824                 LIMIT " . intval($start) . ", " . intval($count),
1825                 ACTIVITY_POST,
1826                 $since_id
1827         );
1828
1829         $r = dba::inArray($r);
1830
1831         $ret = api_format_items($r, $user_info, false, $type);
1832
1833         $data = array('status' => $ret);
1834         switch ($type) {
1835                 case "atom":
1836                 case "rss":
1837                         $data = api_rss_extra($a, $data, $user_info);
1838                         break;
1839         }
1840
1841         return api_format_data("statuses", $type, $data);
1842 }
1843
1844 /// @TODO move to top of file or somewhere better
1845 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1846
1847 /**
1848  * @TODO nothing to say?
1849  */
1850 function api_statuses_show($type)
1851 {
1852         $a = get_app();
1853
1854         if (api_user() === false) {
1855                 throw new ForbiddenException();
1856         }
1857
1858         $user_info = api_get_user($a);
1859
1860         // params
1861         $id = intval($a->argv[3]);
1862
1863         if ($id == 0) {
1864                 $id = intval($_REQUEST["id"]);
1865         }
1866
1867         // Hotot workaround
1868         if ($id == 0) {
1869                 $id = intval($a->argv[4]);
1870         }
1871
1872         logger('API: api_statuses_show: ' . $id);
1873
1874         $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1875
1876         $sql_extra = '';
1877         if ($conversation) {
1878                 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1879         } else {
1880                 $sql_extra .= " AND `item`.`id` = %d";
1881         }
1882
1883         $r = q(
1884                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1885                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1886                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1887                 `contact`.`id` AS `cid`
1888                 FROM `item`
1889                 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1890                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1891                 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1892                 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1893                 $sql_extra",
1894                 intval(api_user()),
1895                 dbesc(ACTIVITY_POST),
1896                 intval($id)
1897         );
1898
1899         /// @TODO How about copying this to above methods which don't check $r ?
1900         if (!DBM::is_result($r)) {
1901                 throw new BadRequestException("There is no status with this id.");
1902         }
1903
1904         $ret = api_format_items($r, $user_info, false, $type);
1905
1906         if ($conversation) {
1907                 $data = array('status' => $ret);
1908                 return api_format_data("statuses", $type, $data);
1909         } else {
1910                 $data = array('status' => $ret[0]);
1911                 return api_format_data("status", $type, $data);
1912         }
1913 }
1914
1915 /// @TODO move to top of file or somewhere better
1916 api_register_func('api/statuses/show', 'api_statuses_show', true);
1917
1918 /**
1919  * @TODO nothing to say?
1920  */
1921 function api_conversation_show($type)
1922 {
1923         $a = get_app();
1924
1925         if (api_user() === false) {
1926                 throw new ForbiddenException();
1927         }
1928
1929         $user_info = api_get_user($a);
1930
1931         // params
1932         $id = intval($a->argv[3]);
1933         $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1934         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1935         if ($page < 0) {
1936                 $page = 0;
1937         }
1938         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1939         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1940
1941         $start = $page*$count;
1942
1943         if ($id == 0) {
1944                 $id = intval($_REQUEST["id"]);
1945         }
1946
1947         // Hotot workaround
1948         if ($id == 0) {
1949                 $id = intval($a->argv[4]);
1950         }
1951
1952         logger('API: api_conversation_show: '.$id);
1953
1954         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1955         if (DBM::is_result($r)) {
1956                 $id = $r[0]["parent"];
1957         }
1958
1959         $sql_extra = '';
1960
1961         if ($max_id > 0) {
1962                 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1963         }
1964
1965         // Not sure why this query was so complicated. We should keep it here for a while,
1966         // just to make sure that we really don't need it.
1967         //      FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1968         //      ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1969
1970         $r = q(
1971                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1972                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1973                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1974                 `contact`.`id` AS `cid`
1975                 FROM `item`
1976                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1977                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1978                 WHERE `item`.`parent` = %d AND `item`.`visible`
1979                 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1980                 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1981                 AND `item`.`id`>%d $sql_extra
1982                 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1983                 intval($id), intval(api_user()),
1984                 dbesc(ACTIVITY_POST),
1985                 intval($since_id),
1986                 intval($start), intval($count)
1987         );
1988
1989         if (!DBM::is_result($r)) {
1990                 throw new BadRequestException("There is no status with this id.");
1991         }
1992
1993         $ret = api_format_items($r, $user_info, false, $type);
1994
1995         $data = array('status' => $ret);
1996         return api_format_data("statuses", $type, $data);
1997 }
1998
1999 /// @TODO move to top of file or somewhere better
2000 api_register_func('api/conversation/show', 'api_conversation_show', true);
2001 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2002
2003 /**
2004  * @TODO nothing to say?
2005  */
2006 function api_statuses_repeat($type)
2007 {
2008         global $called_api;
2009
2010         $a = get_app();
2011
2012         if (api_user() === false) {
2013                 throw new ForbiddenException();
2014         }
2015
2016         $user_info = api_get_user($a);
2017
2018         // params
2019         $id = intval($a->argv[3]);
2020
2021         if ($id == 0) {
2022                 $id = intval($_REQUEST["id"]);
2023         }
2024
2025         // Hotot workaround
2026         if ($id == 0) {
2027                 $id = intval($a->argv[4]);
2028         }
2029
2030         logger('API: api_statuses_repeat: '.$id);
2031
2032         $r = q(
2033                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2034                 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2035                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2036                 `contact`.`id` AS `cid`
2037                 FROM `item`
2038                 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2039                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2040                 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2041                 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2042                 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2043                 $sql_extra
2044                 AND `item`.`id`=%d",
2045                 intval($id)
2046         );
2047
2048         /// @TODO other style than above functions!
2049         if (DBM::is_result($r) && $r[0]['body'] != "") {
2050                 if (strpos($r[0]['body'], "[/share]") !== false) {
2051                         $pos = strpos($r[0]['body'], "[share");
2052                         $post = substr($r[0]['body'], $pos);
2053                 } else {
2054                         $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2055
2056                         $post .= $r[0]['body'];
2057                         $post .= "[/share]";
2058                 }
2059                 $_REQUEST['body'] = $post;
2060                 $_REQUEST['profile_uid'] = api_user();
2061                 $_REQUEST['type'] = 'wall';
2062                 $_REQUEST['api_source'] = true;
2063
2064                 if (!x($_REQUEST, "source")) {
2065                         $_REQUEST["source"] = api_source();
2066                 }
2067
2068                 item_post($a);
2069         } else {
2070                 throw new ForbiddenException();
2071         }
2072
2073         // this should output the last post (the one we just posted).
2074         $called_api = null;
2075         return api_status_show($type);
2076 }
2077
2078 /// @TODO move to top of file or somewhere better
2079 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2080
2081 /**
2082  * @TODO nothing to say?
2083  */
2084 function api_statuses_destroy($type)
2085 {
2086         $a = get_app();
2087
2088         if (api_user() === false) {
2089                 throw new ForbiddenException();
2090         }
2091
2092         $user_info = api_get_user($a);
2093
2094         // params
2095         $id = intval($a->argv[3]);
2096
2097         if ($id == 0) {
2098                 $id = intval($_REQUEST["id"]);
2099         }
2100
2101         // Hotot workaround
2102         if ($id == 0) {
2103                 $id = intval($a->argv[4]);
2104         }
2105
2106         logger('API: api_statuses_destroy: '.$id);
2107
2108         $ret = api_statuses_show($type);
2109
2110         drop_item($id, false);
2111
2112         return $ret;
2113 }
2114
2115 /// @TODO move to top of file or somewhere better
2116 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2117
2118 /**
2119  * @TODO Nothing more than an URL to say?
2120  * http://developer.twitter.com/doc/get/statuses/mentions
2121  */
2122 function api_statuses_mentions($type)
2123 {
2124         $a = get_app();
2125
2126         if (api_user() === false) {
2127                 throw new ForbiddenException();
2128         }
2129
2130         unset($_REQUEST["user_id"]);
2131         unset($_GET["user_id"]);
2132
2133         unset($_REQUEST["screen_name"]);
2134         unset($_GET["screen_name"]);
2135
2136         $user_info = api_get_user($a);
2137         // get last newtork messages
2138
2139
2140         // params
2141         $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2142         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2143         if ($page < 0) {
2144                 $page = 0;
2145         }
2146         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2147         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2148         //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2149
2150         $start = $page * $count;
2151
2152         // Ugly code - should be changed
2153         $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2154         $myurl = substr($myurl, strpos($myurl, '://') + 3);
2155         //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
2156         $myurl = str_replace('www.', '', $myurl);
2157         $diasp_url = str_replace('/profile/', '/u/', $myurl);
2158
2159         if ($max_id > 0) {
2160                 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2161         }
2162
2163         $r = q(
2164                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2165                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2166                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2167                 `contact`.`id` AS `cid`
2168                 FROM `item` FORCE INDEX (`uid_id`)
2169                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2170                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2171                 WHERE `item`.`uid` = %d AND `verb` = '%s'
2172                 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2173                 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2174                 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2175                 $sql_extra
2176                 AND `item`.`id`>%d
2177                 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2178                 intval(api_user()),
2179                 dbesc(ACTIVITY_POST),
2180                 dbesc(protect_sprintf($myurl)),
2181                 dbesc(protect_sprintf($myurl)),
2182                 intval(api_user()),
2183                 intval($since_id),
2184                 intval($start),
2185                 intval($count)
2186         );
2187
2188         $ret = api_format_items($r, $user_info, false, $type);
2189
2190         $data = array('status' => $ret);
2191         switch ($type) {
2192                 case "atom":
2193                 case "rss":
2194                         $data = api_rss_extra($a, $data, $user_info);
2195                         break;
2196         }
2197
2198         return api_format_data("statuses", $type, $data);
2199 }
2200
2201 /// @TODO move to top of file or somewhere better
2202 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2203 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2204
2205 /**
2206  * @brief Returns a user's public timeline
2207  *
2208  * @param string $type Either "json" or "xml"
2209  * @return string|array
2210  * @throws ForbiddenException
2211  */
2212 function api_statuses_user_timeline($type)
2213 {
2214         $a = get_app();
2215
2216         if (api_user() === false) {
2217                 throw new ForbiddenException();
2218         }
2219
2220         $user_info = api_get_user($a);
2221
2222         logger(
2223                 "api_statuses_user_timeline: api_user: ". api_user() .
2224                         "\nuser_info: ".print_r($user_info, true) .
2225                         "\n_REQUEST:  ".print_r($_REQUEST, true),
2226                 LOGGER_DEBUG
2227         );
2228
2229         $since_id        = x($_REQUEST, 'since_id')        ? $_REQUEST['since_id']        : 0;
2230         $max_id          = x($_REQUEST, 'max_id')          ? $_REQUEST['max_id']          : 0;
2231         $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1                            : 0;
2232         $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2233
2234         // pagination
2235         $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2236         $page  = x($_REQUEST, 'page')  ? $_REQUEST['page']  : 1;
2237         if ($page < 1) {
2238                 $page = 1;
2239         }
2240         $start = ($page - 1) * $count;
2241
2242         $sql_extra = '';
2243         if ($user_info['self'] == 1) {
2244                 $sql_extra .= " AND `item`.`wall` = 1 ";
2245         }
2246
2247         if ($exclude_replies > 0) {
2248                 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2249         }
2250
2251         if ($conversation_id > 0) {
2252                 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2253         }
2254
2255         if ($max_id > 0) {
2256                 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2257         }
2258
2259         $r = q(
2260                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2261                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2262                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2263                 `contact`.`id` AS `cid`
2264                 FROM `item` FORCE INDEX (`uid_contactid_id`)
2265                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2266                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2267                 WHERE `item`.`uid` = %d AND `verb` = '%s'
2268                 AND `item`.`contact-id` = %d
2269                 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2270                 $sql_extra
2271                 AND `item`.`id` > %d
2272                 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2273                 intval(api_user()),
2274                 dbesc(ACTIVITY_POST),
2275                 intval($user_info['cid']),
2276                 intval($since_id),
2277                 intval($start),
2278                 intval($count)
2279         );
2280
2281         $ret = api_format_items($r, $user_info, true, $type);
2282
2283         $data = array('status' => $ret);
2284         switch ($type) {
2285                 case "atom":
2286                 case "rss":
2287                         $data = api_rss_extra($a, $data, $user_info);
2288                         break;
2289         }
2290
2291         return api_format_data("statuses", $type, $data);
2292 }
2293
2294 /// @TODO move to top of file or somwhere better
2295 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2296
2297 /**
2298  * Star/unstar an item
2299  * param: id : id of the item
2300  *
2301  * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2302  */
2303 function api_favorites_create_destroy($type)
2304 {
2305         $a = get_app();
2306
2307         if (api_user() === false) {
2308                 throw new ForbiddenException();
2309         }
2310
2311         // for versioned api.
2312         /// @TODO We need a better global soluton
2313         $action_argv_id = 2;
2314         if ($a->argv[1] == "1.1") {
2315                 $action_argv_id = 3;
2316         }
2317
2318         if ($a->argc <= $action_argv_id) {
2319                 throw new BadRequestException("Invalid request.");
2320         }
2321         $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2322         if ($a->argc == $action_argv_id + 2) {
2323                 $itemid = intval($a->argv[$action_argv_id + 1]);
2324         } else {
2325                 ///  @TODO use x() to check if _REQUEST contains 'id'
2326                 $itemid = intval($_REQUEST['id']);
2327         }
2328
2329         $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2330
2331         if (!DBM::is_result($item) || count($item) == 0) {
2332                 throw new BadRequestException("Invalid item.");
2333         }
2334
2335         switch ($action) {
2336                 case "create":
2337                         $item[0]['starred'] = 1;
2338                         break;
2339                 case "destroy":
2340                         $item[0]['starred'] = 0;
2341                         break;
2342                 default:
2343                         throw new BadRequestException("Invalid action ".$action);
2344         }
2345
2346         $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",     $item[0]['starred'], $itemid, api_user());
2347
2348         q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2349
2350         if ($r === false) {
2351                 throw new InternalServerErrorException("DB error");
2352         }
2353
2354
2355         $user_info = api_get_user($a);
2356         $rets = api_format_items($item, $user_info, false, $type);
2357         $ret = $rets[0];
2358
2359         $data = array('status' => $ret);
2360         switch ($type) {
2361                 case "atom":
2362                 case "rss":
2363                         $data = api_rss_extra($a, $data, $user_info);
2364         }
2365
2366         return api_format_data("status", $type, $data);
2367 }
2368
2369 /// @TODO move to top of file or somwhere better
2370 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2371 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2372
2373 function api_favorites($type)
2374 {
2375         global $called_api;
2376
2377         $a = get_app();
2378
2379         if (api_user() === false) {
2380                 throw new ForbiddenException();
2381         }
2382
2383         $called_api = array();
2384
2385         $user_info = api_get_user($a);
2386
2387         // in friendica starred item are private
2388         // return favorites only for self
2389         logger('api_favorites: self:' . $user_info['self']);
2390
2391         if ($user_info['self'] == 0) {
2392                 $ret = array();
2393         } else {
2394                 $sql_extra = "";
2395
2396                 // params
2397                 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2398                 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2399                 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2400                 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2401                 if ($page < 0) {
2402                         $page = 0;
2403                 }
2404
2405                 $start = $page*$count;
2406
2407                 if ($max_id > 0) {
2408                         $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2409                 }
2410
2411                 $r = q(
2412                         "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2413                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2414                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2415                         `contact`.`id` AS `cid`
2416                         FROM `item`, `contact`
2417                         WHERE `item`.`uid` = %d
2418                         AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2419                         AND `item`.`starred` = 1
2420                         AND `contact`.`id` = `item`.`contact-id`
2421                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2422                         $sql_extra
2423                         AND `item`.`id`>%d
2424                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2425                         intval(api_user()),
2426                         intval($since_id),
2427                         intval($start),
2428                         intval($count)
2429                 );
2430
2431                 $ret = api_format_items($r, $user_info, false, $type);
2432         }
2433
2434         $data = array('status' => $ret);
2435         switch ($type) {
2436                 case "atom":
2437                 case "rss":
2438                         $data = api_rss_extra($a, $data, $user_info);
2439         }
2440
2441         return api_format_data("statuses", $type, $data);
2442 }
2443
2444 /// @TODO move to top of file or somwhere better
2445 api_register_func('api/favorites', 'api_favorites', true);
2446
2447 function api_format_messages($item, $recipient, $sender)
2448 {
2449         // standard meta information
2450         $ret = array(
2451                         'id'                    => $item['id'],
2452                         'sender_id'             => $sender['id'] ,
2453                         'text'                  => "",
2454                         'recipient_id'          => $recipient['id'],
2455                         'created_at'            => api_date($item['created']),
2456                         'sender_screen_name'    => $sender['screen_name'],
2457                         'recipient_screen_name' => $recipient['screen_name'],
2458                         'sender'                => $sender,
2459                         'recipient'             => $recipient,
2460                         'title'                 => "",
2461                         'friendica_seen'        => $item['seen'],
2462                         'friendica_parent_uri'  => $item['parent-uri'],
2463         );
2464
2465         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2466         unset($ret["sender"]["uid"]);
2467         unset($ret["sender"]["self"]);
2468         unset($ret["recipient"]["uid"]);
2469         unset($ret["recipient"]["self"]);
2470
2471         //don't send title to regular StatusNET requests to avoid confusing these apps
2472         if (x($_GET, 'getText')) {
2473                 $ret['title'] = $item['title'];
2474                 if ($_GET['getText'] == 'html') {
2475                         $ret['text'] = bbcode($item['body'], false, false);
2476                 } elseif ($_GET['getText'] == 'plain') {
2477                         //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2478                         $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2479                 }
2480         } else {
2481                 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2482         }
2483         if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2484                 unset($ret['sender']);
2485                 unset($ret['recipient']);
2486         }
2487
2488         return $ret;
2489 }
2490
2491 function api_convert_item($item)
2492 {
2493         $body = $item['body'];
2494         $attachments = api_get_attachments($body);
2495
2496         // Workaround for ostatus messages where the title is identically to the body
2497         $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2498         $statusbody = trim(html2plain($html, 0));
2499
2500         // handle data: images
2501         $statusbody = api_format_items_embeded_images($item, $statusbody);
2502
2503         $statustitle = trim($item['title']);
2504
2505         if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2506                 $statustext = trim($statusbody);
2507         } else {
2508                 $statustext = trim($statustitle."\n\n".$statusbody);
2509         }
2510
2511         if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2512                 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2513         }
2514
2515         $statushtml = trim(bbcode($body, false, false));
2516
2517         // Workaround for clients with limited HTML parser functionality
2518         $search = array("<br>", "<blockquote>", "</blockquote>",
2519                         "<h1>", "</h1>", "<h2>", "</h2>",
2520                         "<h3>", "</h3>", "<h4>", "</h4>",
2521                         "<h5>", "</h5>", "<h6>", "</h6>");
2522         $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2523                         "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2524                         "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2525                         "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2526         $statushtml = str_replace($search, $replace, $statushtml);
2527
2528         if ($item['title'] != "") {
2529                 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2530         }
2531
2532         do {
2533                 $oldtext = $statushtml;
2534                 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2535         } while ($oldtext != $statushtml);
2536
2537         if (substr($statushtml, 0, 4) == '<br>') {
2538                 $statushtml = substr($statushtml, 4);
2539         }
2540
2541         if (substr($statushtml, 0, -4) == '<br>') {
2542                 $statushtml = substr($statushtml, -4);
2543         }
2544
2545         // feeds without body should contain the link
2546         if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2547                 $statushtml .= bbcode($item['plink']);
2548         }
2549
2550         $entities = api_get_entitities($statustext, $body);
2551
2552         return array(
2553                 "text" => $statustext,
2554                 "html" => $statushtml,
2555                 "attachments" => $attachments,
2556                 "entities" => $entities
2557         );
2558 }
2559
2560 function api_get_attachments(&$body)
2561 {
2562         $text = $body;
2563         $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2564
2565         $URLSearchString = "^\[\]";
2566         $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2567
2568         if (!$ret) {
2569                 return false;
2570         }
2571
2572         $attachments = array();
2573
2574         foreach ($images[1] as $image) {
2575                 $imagedata = Image::getInfoFromURL($image);
2576
2577                 if ($imagedata) {
2578                         $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2579                 }
2580         }
2581
2582         if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2583                 foreach ($images[0] as $orig) {
2584                         $body = str_replace($orig, "", $body);
2585                 }
2586         }
2587
2588         return $attachments;
2589 }
2590
2591 function api_get_entitities(&$text, $bbcode)
2592 {
2593         /*
2594         To-Do:
2595         * Links at the first character of the post
2596         */
2597
2598         $a = get_app();
2599
2600         $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2601
2602         if ($include_entities != "true") {
2603                 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2604
2605                 foreach ($images[1] as $image) {
2606                         $replace = proxy_url($image);
2607                         $text = str_replace($image, $replace, $text);
2608                 }
2609                 return array();
2610         }
2611
2612         $bbcode = bb_CleanPictureLinks($bbcode);
2613
2614         // Change pure links in text to bbcode uris
2615         $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2616
2617         $entities = array();
2618         $entities["hashtags"] = array();
2619         $entities["symbols"] = array();
2620         $entities["urls"] = array();
2621         $entities["user_mentions"] = array();
2622
2623         $URLSearchString = "^\[\]";
2624
2625         $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2626
2627         $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2628         //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2629         $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2630
2631         $bbcode = preg_replace(
2632                 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2633                 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2634                 $bbcode
2635         );
2636         $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2637
2638         $bbcode = preg_replace(
2639                 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2640                 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2641                 $bbcode
2642         );
2643         $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2644
2645         $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2646
2647         //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2648         preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2649
2650         $ordered_urls = array();
2651         foreach ($urls[1] as $id => $url) {
2652                 //$start = strpos($text, $url, $offset);
2653                 $start = iconv_strpos($text, $url, 0, "UTF-8");
2654                 if (!($start === false)) {
2655                         $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2656                 }
2657         }
2658
2659         ksort($ordered_urls);
2660
2661         $offset = 0;
2662         //foreach ($urls[1] AS $id=>$url) {
2663         foreach ($ordered_urls as $url) {
2664                 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2665                         && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2666                 )
2667                         $display_url = $url["title"];
2668                 else {
2669                         $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2670                         $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2671
2672                         if (strlen($display_url) > 26)
2673                                 $display_url = substr($display_url, 0, 25)."…";
2674                 }
2675
2676                 //$start = strpos($text, $url, $offset);
2677                 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2678                 if (!($start === false)) {
2679                         $entities["urls"][] = array("url" => $url["url"],
2680                                                         "expanded_url" => $url["url"],
2681                                                         "display_url" => $display_url,
2682                                                         "indices" => array($start, $start+strlen($url["url"])));
2683                         $offset = $start + 1;
2684                 }
2685         }
2686
2687         preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2688         $ordered_images = array();
2689         foreach ($images[1] as $image) {
2690                 //$start = strpos($text, $url, $offset);
2691                 $start = iconv_strpos($text, $image, 0, "UTF-8");
2692                 if (!($start === false))
2693                         $ordered_images[$start] = $image;
2694         }
2695         //$entities["media"] = array();
2696         $offset = 0;
2697
2698         foreach ($ordered_images as $url) {
2699                 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2700                 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2701
2702                 if (strlen($display_url) > 26)
2703                         $display_url = substr($display_url, 0, 25)."…";
2704
2705                 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2706                 if (!($start === false)) {
2707                         $image = Image::getInfoFromURL($url);
2708                         if ($image) {
2709                                 // If image cache is activated, then use the following sizes:
2710                                 // thumb  (150), small (340), medium (600) and large (1024)
2711                                 if (!Config::get("system", "proxy_disabled")) {
2712                                         $media_url = proxy_url($url);
2713
2714                                         $sizes = array();
2715                                         $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2716                                         $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2717
2718                                         if (($image[0] > 150) || ($image[1] > 150)) {
2719                                                 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2720                                                 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2721                                         }
2722
2723                                         $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2724                                         $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2725
2726                                         if (($image[0] > 600) || ($image[1] > 600)) {
2727                                                 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2728                                                 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2729                                         }
2730                                 } else {
2731                                         $media_url = $url;
2732                                         $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2733                                 }
2734
2735                                 $entities["media"][] = array(
2736                                                         "id" => $start+1,
2737                                                         "id_str" => (string)$start+1,
2738                                                         "indices" => array($start, $start+strlen($url)),
2739                                                         "media_url" => normalise_link($media_url),
2740                                                         "media_url_https" => $media_url,
2741                                                         "url" => $url,
2742                                                         "display_url" => $display_url,
2743                                                         "expanded_url" => $url,
2744                                                         "type" => "photo",
2745                                                         "sizes" => $sizes);
2746                         }
2747                         $offset = $start + 1;
2748                 }
2749         }
2750
2751         return $entities;
2752 }
2753 function api_format_items_embeded_images(&$item, $text)
2754 {
2755         $text = preg_replace_callback(
2756                 "|data:image/([^;]+)[^=]+=*|m",
2757                 function ($match) use ($item) {
2758                         return System::baseUrl()."/display/".$item['guid'];
2759                 },
2760                 $text
2761         );
2762         return $text;
2763 }
2764
2765
2766 /**
2767  * @brief return <a href='url'>name</a> as array
2768  *
2769  * @param string $txt text
2770  * @return array
2771  *                      name => 'name'
2772  *                      'url => 'url'
2773  */
2774 function api_contactlink_to_array($txt)
2775 {
2776         $match = array();
2777         $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2778         if ($r && count($match)==3) {
2779                 $res = array(
2780                         'name' => $match[2],
2781                         'url' => $match[1]
2782                 );
2783         } else {
2784                 $res = array(
2785                         'name' => $text,
2786                         'url' => ""
2787                 );
2788         }
2789         return $res;
2790 }
2791
2792
2793 /**
2794  * @brief return likes, dislikes and attend status for item
2795  *
2796  * @param array $item array
2797  * @return array
2798  *                      likes => int count
2799  *                      dislikes => int count
2800  */
2801 function api_format_items_activities(&$item, $type = "json")
2802 {
2803         $a = get_app();
2804
2805         $activities = array(
2806                 'like' => array(),
2807                 'dislike' => array(),
2808                 'attendyes' => array(),
2809                 'attendno' => array(),
2810                 'attendmaybe' => array(),
2811         );
2812
2813         $items = q(
2814                 'SELECT * FROM item
2815                         WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2816                 intval($item['uid']),
2817                 dbesc($item['uri'])
2818         );
2819
2820         foreach ($items as $i) {
2821                 // not used as result should be structured like other user data
2822                 //builtin_activity_puller($i, $activities);
2823
2824                 // get user data and add it to the array of the activity
2825                 $user = api_get_user($a, $i['author-link']);
2826                 switch ($i['verb']) {
2827                         case ACTIVITY_LIKE:
2828                                 $activities['like'][] = $user;
2829                                 break;
2830                         case ACTIVITY_DISLIKE:
2831                                 $activities['dislike'][] = $user;
2832                                 break;
2833                         case ACTIVITY_ATTEND:
2834                                 $activities['attendyes'][] = $user;
2835                                 break;
2836                         case ACTIVITY_ATTENDNO:
2837                                 $activities['attendno'][] = $user;
2838                                 break;
2839                         case ACTIVITY_ATTENDMAYBE:
2840                                 $activities['attendmaybe'][] = $user;
2841                                 break;
2842                         default:
2843                                 break;
2844                 }
2845         }
2846
2847         if ($type == "xml") {
2848                 $xml_activities = array();
2849                 foreach ($activities as $k => $v) {
2850                         // change xml element from "like" to "friendica:like"
2851                         $xml_activities["friendica:".$k] = $v;
2852                         // add user data into xml output
2853                         $k_user = 0;
2854                         foreach ($v as $user)
2855                                 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2856                 }
2857                 $activities = $xml_activities;
2858         }
2859
2860         return $activities;
2861 }
2862
2863
2864 /**
2865  * @brief return data from profiles
2866  *
2867  * @param array  $profile array containing data from db table 'profile'
2868  * @param string $type    Known types are 'atom', 'rss', 'xml' and 'json'
2869  * @return array
2870  */
2871 function api_format_items_profiles(&$profile = null, $type = "json")
2872 {
2873         if ($profile != null) {
2874                 $profile = array('profile_id' => $profile['id'],
2875                                                 'profile_name' => $profile['profile-name'],
2876                                                 'is_default' => $profile['is-default'] ? true : false,
2877                                                 'hide_friends'=> $profile['hide-friends'] ? true : false,
2878                                                 'profile_photo' => $profile['photo'],
2879                                                 'profile_thumb' => $profile['thumb'],
2880                                                 'publish' => $profile['publish'] ? true : false,
2881                                                 'net_publish' => $profile['net-publish'] ? true : false,
2882                                                 'description' => $profile['pdesc'],
2883                                                 'date_of_birth' => $profile['dob'],
2884                                                 'address' => $profile['address'],
2885                                                 'city' => $profile['locality'],
2886                                                 'region' => $profile['region'],
2887                                                 'postal_code' => $profile['postal-code'],
2888                                                 'country' => $profile['country-name'],
2889                                                 'hometown' => $profile['hometown'],
2890                                                 'gender' => $profile['gender'],
2891                                                 'marital' => $profile['marital'],
2892                                                 'marital_with' => $profile['with'],
2893                                                 'marital_since' => $profile['howlong'],
2894                                                 'sexual' => $profile['sexual'],
2895                                                 'politic' => $profile['politic'],
2896                                                 'religion' => $profile['religion'],
2897                                                 'public_keywords' => $profile['pub_keywords'],
2898                                                 'private_keywords' => $profile['prv_keywords'],
2899                                                 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2900                                                 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2901                                                 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2902                                                 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2903                                                 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2904                                                 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2905                                                 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2906                                                 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2907                                                 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2908                                                 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2909                                                 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2910                                                 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2911                                                 'homepage' => $profile['homepage'],
2912                                                 'users' => null);
2913                 return $profile;
2914         }
2915 }
2916
2917 /**
2918  * @brief format items to be returned by api
2919  *
2920  * @param array $r array of items
2921  * @param array $user_info
2922  * @param bool $filter_user filter items by $user_info
2923  */
2924 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2925 {
2926         $a = get_app();
2927
2928         $ret = array();
2929
2930         foreach ($r as $item) {
2931                 localize_item($item);
2932                 list($status_user, $owner_user) = api_item_get_user($a, $item);
2933
2934                 // Look if the posts are matching if they should be filtered by user id
2935                 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2936                         continue;
2937                 }
2938
2939                 $in_reply_to = api_in_reply_to($item);
2940
2941                 $converted = api_convert_item($item);
2942
2943                 if ($type == "xml") {
2944                         $geo = "georss:point";
2945                 } else {
2946                         $geo = "geo";
2947                 }
2948
2949                 $status = array(
2950                         'text'          => $converted["text"],
2951                         'truncated' => false,
2952                         'created_at'=> api_date($item['created']),
2953                         'in_reply_to_status_id' => $in_reply_to['status_id'],
2954                         'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2955                         'source'    => (($item['app']) ? $item['app'] : 'web'),
2956                         'id'            => intval($item['id']),
2957                         'id_str'        => (string) intval($item['id']),
2958                         'in_reply_to_user_id' => $in_reply_to['user_id'],
2959                         'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2960                         'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2961                         $geo => null,
2962                         'favorited' => $item['starred'] ? true : false,
2963                         'user' =>  $status_user ,
2964                         'friendica_owner' => $owner_user,
2965                         //'entities' => NULL,
2966                         'statusnet_html' => $converted["html"],
2967                         'statusnet_conversation_id' => $item['parent'],
2968                         'external_url' => System::baseUrl() . "/display/" . $item['guid'],
2969                         'friendica_activities' => api_format_items_activities($item, $type),
2970                 );
2971
2972                 if (count($converted["attachments"]) > 0) {
2973                         $status["attachments"] = $converted["attachments"];
2974                 }
2975
2976                 if (count($converted["entities"]) > 0) {
2977                         $status["entities"] = $converted["entities"];
2978                 }
2979
2980                 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
2981                         $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2982                 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2983                         $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2984                 }
2985
2986
2987                 // Retweets are only valid for top postings
2988                 // It doesn't work reliable with the link if its a feed
2989                 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2990                 //if ($IsRetweet)
2991                 //      $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
2992
2993
2994                 if ($item["id"] == $item["parent"]) {
2995                         $retweeted_item = api_share_as_retweet($item);
2996                         if ($retweeted_item !== false) {
2997                                 $retweeted_status = $status;
2998                                 try {
2999                                         $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
3000                                 } catch (BadRequestException $e) {
3001                                         // user not found. should be found?
3002                                         /// @todo check if the user should be always found
3003                                         $retweeted_status["user"] = array();
3004                                 }
3005
3006                                 $rt_converted = api_convert_item($retweeted_item);
3007
3008                                 $retweeted_status['text'] = $rt_converted["text"];
3009                                 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3010                                 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3011                                 $retweeted_status['created_at'] =  api_date($retweeted_item['created']);
3012                                 $status['retweeted_status'] = $retweeted_status;
3013                         }
3014                 }
3015
3016                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3017                 unset($status["user"]["uid"]);
3018                 unset($status["user"]["self"]);
3019
3020                 if ($item["coord"] != "") {
3021                         $coords = explode(' ', $item["coord"]);
3022                         if (count($coords) == 2) {
3023                                 if ($type == "json")
3024                                         $status["geo"] = array('type' => 'Point',
3025                                                         'coordinates' => array((float) $coords[0],
3026                                                                                 (float) $coords[1]));
3027                                 else // Not sure if this is the official format - if someone founds a documentation we can check
3028                                         $status["georss:point"] = $item["coord"];
3029                         }
3030                 }
3031                 $ret[] = $status;
3032         };
3033         return $ret;
3034 }
3035
3036 function api_account_rate_limit_status($type)
3037 {
3038         if ($type == "xml") {
3039                 $hash = array(
3040                                 'remaining-hits' => '150',
3041                                 '@attributes' => array("type" => "integer"),
3042                                 'hourly-limit' => '150',
3043                                 '@attributes2' => array("type" => "integer"),
3044                                 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
3045                                 '@attributes3' => array("type" => "datetime"),
3046                                 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3047                                 '@attributes4' => array("type" => "integer"),
3048                         );
3049         } else {
3050                 $hash = array(
3051                                 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3052                                 'remaining_hits' => '150',
3053                                 'hourly_limit' => '150',
3054                                 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
3055                         );
3056         }
3057
3058         return api_format_data('hash', $type, array('hash' => $hash));
3059 }
3060
3061 /// @TODO move to top of file or somwhere better
3062 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3063
3064 function api_help_test($type)
3065 {
3066         if ($type == 'xml') {
3067                 $ok = "true";
3068         } else {
3069                 $ok = "ok";
3070         }
3071
3072         return api_format_data('ok', $type, array("ok" => $ok));
3073 }
3074
3075 /// @TODO move to top of file or somwhere better
3076 api_register_func('api/help/test', 'api_help_test', false);
3077
3078 function api_lists($type)
3079 {
3080         $ret = array();
3081         /// @TODO $ret is not filled here?
3082         return api_format_data('lists', $type, array("lists_list" => $ret));
3083 }
3084
3085 /// @TODO move to top of file or somwhere better
3086 api_register_func('api/lists', 'api_lists', true);
3087
3088 function api_lists_list($type)
3089 {
3090         $ret = array();
3091         /// @TODO $ret is not filled here?
3092         return api_format_data('lists', $type, array("lists_list" => $ret));
3093 }
3094
3095 /// @TODO move to top of file or somwhere better
3096 api_register_func('api/lists/list', 'api_lists_list', true);
3097
3098 /**
3099  * @brief Returns either the friends of the follower list
3100  *
3101  * Note: Considers friends and followers lists to be private and won't return
3102  * anything if any user_id parameter is passed.
3103  *
3104  * @param string $qtype Either "friends" or "followers"
3105  * @return boolean|array
3106  * @throws ForbiddenException
3107  */
3108 function api_statuses_f($qtype)
3109 {
3110         $a = get_app();
3111
3112         if (api_user() === false) {
3113                 throw new ForbiddenException();
3114         }
3115
3116         // pagination
3117         $count = x($_GET, 'count') ? $_GET['count'] : 20;
3118         $page = x($_GET, 'page') ? $_GET['page'] : 1;
3119         if ($page < 1) {
3120                 $page = 1;
3121         }
3122         $start = ($page - 1) * $count;
3123
3124         $user_info = api_get_user($a);
3125
3126         if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3127                 /* this is to stop Hotot to load friends multiple times
3128                 *  I'm not sure if I'm missing return something or
3129                 *  is a bug in hotot. Workaround, meantime
3130                 */
3131
3132                 /*$ret=Array();
3133                 return array('$users' => $ret);*/
3134                 return false;
3135         }
3136
3137         if ($qtype == 'friends') {
3138                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3139         }
3140         if ($qtype == 'followers') {
3141                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3142         }
3143
3144         // friends and followers only for self
3145         if ($user_info['self'] == 0) {
3146                 $sql_extra = " AND false ";
3147         }
3148
3149         if ($qtype == 'blocks') {
3150                 $sql_blocked = 'AND `blocked`';
3151         } else {
3152                 $sql_blocked = 'AND NOT `blocked`';
3153         }
3154
3155         $r = q(
3156                 "SELECT `nurl`
3157                 FROM `contact`
3158                 WHERE `uid` = %d
3159                 AND NOT `self`
3160                 $sql_blocked
3161                 AND NOT `pending`
3162                 $sql_extra
3163                 ORDER BY `nick`
3164                 LIMIT %d, %d",
3165                 intval(api_user()),
3166                 intval($start),
3167                 intval($count)
3168         );
3169
3170         $ret = array();
3171         foreach ($r as $cid) {
3172                 $user = api_get_user($a, $cid['nurl']);
3173                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3174                 unset($user["uid"]);
3175                 unset($user["self"]);
3176
3177                 if ($user) {
3178                         $ret[] = $user;
3179                 }
3180         }
3181
3182         return array('user' => $ret);
3183 }
3184
3185
3186 /**
3187  * @brief Returns the list of friends of the provided user
3188  *
3189  * @deprecated By Twitter API in favor of friends/list
3190  *
3191  * @param string $type Either "json" or "xml"
3192  * @return boolean|string|array
3193  */
3194 function api_statuses_friends($type)
3195 {
3196         $data =  api_statuses_f("friends");
3197         if ($data === false) {
3198                 return false;
3199         }
3200         return api_format_data("users", $type, $data);
3201 }
3202
3203 /**
3204  * @brief Returns the list of friends of the provided user
3205  *
3206  * @deprecated By Twitter API in favor of friends/list
3207  *
3208  * @param string $type Either "json" or "xml"
3209  * @return boolean|string|array
3210  */
3211 function api_statuses_followers($type)
3212 {
3213         $data = api_statuses_f("followers");
3214         if ($data === false) {
3215                 return false;
3216         }
3217         return api_format_data("users", $type, $data);
3218 }
3219
3220 /// @TODO move to top of file or somewhere better
3221 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3222 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3223
3224 /**
3225  * Returns the list of blocked users
3226  *
3227  * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3228  *
3229  * @param string $type Either "json" or "xml"
3230  *
3231  * @return boolean|string|array
3232  * @throws UnauthorizedException
3233  */
3234 function api_blocks_list($type)
3235 {
3236         $data =  api_statuses_f('blocks');
3237         if ($data === false) {
3238                 return false;
3239         }
3240         return api_format_data("users", $type, $data);
3241 }
3242
3243 /// @TODO move to top of file or somewhere better
3244 api_register_func('api/blocks/list', 'api_blocks_list', true);
3245
3246 function api_statusnet_config($type)
3247 {
3248         $a = get_app();
3249
3250         $name = $a->config['sitename'];
3251         $server = $a->get_hostname();
3252         $logo = System::baseUrl() . '/images/friendica-64.png';
3253         $email = $a->config['admin_email'];
3254         $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3255         $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3256         $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3257         if ($a->config['api_import_size']) {
3258                 $texlimit = string($a->config['api_import_size']);
3259         }
3260         $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3261         $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3262
3263         $config = array(
3264                 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3265                         'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3266                         'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3267                         'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3268                         'shorturllength' => '30',
3269                         'friendica' => array(
3270                                         'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3271                                         'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3272                                         'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3273                                         'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3274                                         )
3275                 ),
3276         );
3277
3278         return api_format_data('config', $type, array('config' => $config));
3279 }
3280
3281 /// @TODO move to top of file or somewhere better
3282 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3283 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3284
3285 function api_statusnet_version($type)
3286 {
3287         // liar
3288         $fake_statusnet_version = "0.9.7";
3289
3290         return api_format_data('version', $type, array('version' => $fake_statusnet_version));
3291 }
3292
3293 /// @TODO move to top of file or somewhere better
3294 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3295 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3296
3297 /**
3298  * @todo use api_format_data() to return data
3299  */
3300 function api_ff_ids($type,$qtype)
3301 {
3302         $a = get_app();
3303
3304         if (! api_user()) {
3305                 throw new ForbiddenException();
3306         }
3307
3308         $user_info = api_get_user($a);
3309
3310         if ($qtype == 'friends') {
3311                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3312         }
3313         if ($qtype == 'followers') {
3314                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3315         }
3316
3317         if (!$user_info["self"]) {
3318                 $sql_extra = " AND false ";
3319         }
3320
3321         $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3322
3323         $r = q(
3324                 "SELECT `pcontact`.`id` FROM `contact`
3325                         INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3326                         WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3327                 intval(api_user())
3328         );
3329
3330         if (!DBM::is_result($r)) {
3331                 return;
3332         }
3333
3334         $ids = array();
3335         foreach ($r as $rr) {
3336                 if ($stringify_ids) {
3337                         $ids[] = $rr['id'];
3338                 } else {
3339                         $ids[] = intval($rr['id']);
3340                 }
3341         }
3342
3343         return api_format_data("ids", $type, array('id' => $ids));
3344 }
3345
3346 function api_friends_ids($type)
3347 {
3348         return api_ff_ids($type, 'friends');
3349 }
3350
3351 function api_followers_ids($type)
3352 {
3353         return api_ff_ids($type, 'followers');
3354 }
3355
3356 /// @TODO move to top of file or somewhere better
3357 api_register_func('api/friends/ids', 'api_friends_ids', true);
3358 api_register_func('api/followers/ids', 'api_followers_ids', true);
3359
3360 function api_direct_messages_new($type)
3361 {
3362
3363         $a = get_app();
3364
3365         if (api_user() === false) throw new ForbiddenException();
3366
3367         if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) return;
3368
3369         $sender = api_get_user($a);
3370
3371         if ($_POST['screen_name']) {
3372                 $r = q(
3373                         "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3374                         intval(api_user()),
3375                         dbesc($_POST['screen_name'])
3376                 );
3377
3378                 // Selecting the id by priority, friendica first
3379                 api_best_nickname($r);
3380
3381                 $recipient = api_get_user($a, $r[0]['nurl']);
3382         } else {
3383                 $recipient = api_get_user($a, $_POST['user_id']);
3384         }
3385
3386         $replyto = '';
3387         $sub     = '';
3388         if (x($_REQUEST, 'replyto')) {
3389                 $r = q(
3390                         'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3391                         intval(api_user()),
3392                         intval($_REQUEST['replyto'])
3393                 );
3394                 $replyto = $r[0]['parent-uri'];
3395                 $sub     = $r[0]['title'];
3396         } else {
3397                 if (x($_REQUEST, 'title')) {
3398                         $sub = $_REQUEST['title'];
3399                 } else {
3400                         $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3401                 }
3402         }
3403
3404         $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3405
3406         if ($id > -1) {
3407                 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3408                 $ret = api_format_messages($r[0], $recipient, $sender);
3409         } else {
3410                 $ret = array("error"=>$id);
3411         }
3412
3413         $data = array('direct_message'=>$ret);
3414
3415         switch ($type) {
3416                 case "atom":
3417                 case "rss":
3418                         $data = api_rss_extra($a, $data, $user_info);
3419         }
3420
3421         return api_format_data("direct-messages", $type, $data);
3422
3423 }
3424
3425 /// @TODO move to top of file or somewhere better
3426 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3427
3428 /**
3429  * @brief delete a direct_message from mail table through api
3430  *
3431  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3432  * @return string
3433  */
3434 function api_direct_messages_destroy($type)
3435 {
3436         $a = get_app();
3437
3438         if (api_user() === false) {
3439                 throw new ForbiddenException();
3440         }
3441
3442         // params
3443         $user_info = api_get_user($a);
3444         //required
3445         $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3446         // optional
3447         $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3448         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3449         /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3450
3451         $uid = $user_info['uid'];
3452         // error if no id or parenturi specified (for clients posting parent-uri as well)
3453         if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3454                 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3455                 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3456         }
3457
3458         // BadRequestException if no id specified (for clients using Twitter API)
3459         if ($id == 0) {
3460                 throw new BadRequestException('Message id not specified');
3461         }
3462
3463         // add parent-uri to sql command if specified by calling app
3464         $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3465
3466         // get data of the specified message id
3467         $r = q(
3468                 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3469                 intval($uid),
3470                 intval($id)
3471         );
3472
3473         // error message if specified id is not in database
3474         if (!DBM::is_result($r)) {
3475                 if ($verbose == "true") {
3476                         $answer = array('result' => 'error', 'message' => 'message id not in database');
3477                         return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3478                 }
3479                 /// @todo BadRequestException ok for Twitter API clients?
3480                 throw new BadRequestException('message id not in database');
3481         }
3482
3483         // delete message
3484         $result = q(
3485                 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3486                 intval($uid),
3487                 intval($id)
3488         );
3489
3490         if ($verbose == "true") {
3491                 if ($result) {
3492                         // return success
3493                         $answer = array('result' => 'ok', 'message' => 'message deleted');
3494                         return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3495                 } else {
3496                         $answer = array('result' => 'error', 'message' => 'unknown error');
3497                         return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3498                 }
3499         }
3500         /// @todo return JSON data like Twitter API not yet implemented
3501
3502 }
3503
3504 /// @TODO move to top of file or somewhere better
3505 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3506
3507 function api_direct_messages_box($type, $box, $verbose)
3508 {
3509         $a = get_app();
3510
3511         if (api_user() === false) {
3512                 throw new ForbiddenException();
3513         }
3514
3515         // params
3516         $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3517         $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3518         if ($page < 0) {
3519                 $page = 0;
3520         }
3521
3522         $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3523         $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3524
3525         $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3526         $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3527
3528         //  caller user info
3529         unset($_REQUEST["user_id"]);
3530         unset($_GET["user_id"]);
3531
3532         unset($_REQUEST["screen_name"]);
3533         unset($_GET["screen_name"]);
3534
3535         $user_info = api_get_user($a);
3536         $profile_url = $user_info["url"];
3537
3538         // pagination
3539         $start = $page * $count;
3540
3541         // filters
3542         if ($box=="sentbox") {
3543                 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3544         } elseif ($box == "conversation") {
3545                 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"])  . "'";
3546         } elseif ($box == "all") {
3547                 $sql_extra = "true";
3548         } elseif ($box == "inbox") {
3549                 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3550         }
3551
3552         if ($max_id > 0) {
3553                 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3554         }
3555
3556         if ($user_id != "") {
3557                 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3558         } elseif ($screen_name !="") {
3559                 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3560         }
3561
3562         $r = q(
3563                 "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",
3564                 intval(api_user()),
3565                 intval($since_id),
3566                 intval($start),
3567                 intval($count)
3568         );
3569         if ($verbose == "true" && !DBM::is_result($r)) {
3570                 $answer = array('result' => 'error', 'message' => 'no mails available');
3571                 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3572         }
3573
3574         $ret = array();
3575         foreach ($r as $item) {
3576                 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3577                         $recipient = $user_info;
3578                         $sender = api_get_user($a, normalise_link($item['contact-url']));
3579                 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3580                         $recipient = api_get_user($a, normalise_link($item['contact-url']));
3581                         $sender = $user_info;
3582                 }
3583
3584                 $ret[] = api_format_messages($item, $recipient, $sender);
3585         }
3586
3587
3588         $data = array('direct_message' => $ret);
3589         switch ($type) {
3590                 case "atom":
3591                 case "rss":
3592                         $data = api_rss_extra($a, $data, $user_info);
3593         }
3594
3595         return api_format_data("direct-messages", $type, $data);
3596 }
3597
3598 function api_direct_messages_sentbox($type)
3599 {
3600         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3601         return api_direct_messages_box($type, "sentbox", $verbose);
3602 }
3603
3604 function api_direct_messages_inbox($type)
3605 {
3606         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3607         return api_direct_messages_box($type, "inbox", $verbose);
3608 }
3609
3610 function api_direct_messages_all($type)
3611 {
3612         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3613         return api_direct_messages_box($type, "all", $verbose);
3614 }
3615
3616 function api_direct_messages_conversation($type)
3617 {
3618         $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3619         return api_direct_messages_box($type, "conversation", $verbose);
3620 }
3621
3622 /// @TODO move to top of file or somewhere better
3623 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3624 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3625 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3626 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3627
3628 function api_oauth_request_token($type)
3629 {
3630         $oauth1 = new FKOAuth1();
3631         try {
3632                 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3633         } catch (Exception $e) {
3634                 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3635                 killme();
3636         }
3637         echo $r;
3638         killme();
3639 }
3640
3641 function api_oauth_access_token($type)
3642 {
3643         $oauth1 = new FKOAuth1();
3644         try {
3645                 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3646         } catch (Exception $e) {
3647                 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3648                 killme();
3649         }
3650         echo $r;
3651         killme();
3652 }
3653
3654 /// @TODO move to top of file or somewhere better
3655 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3656 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3657
3658
3659 /**
3660  * @brief delete a complete photoalbum with all containing photos from database through api
3661  *
3662  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3663  * @return string
3664  */
3665 function api_fr_photoalbum_delete($type)
3666 {
3667         if (api_user() === false) {
3668                 throw new ForbiddenException();
3669         }
3670         // input params
3671         $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3672
3673         // we do not allow calls without album string
3674         if ($album == "") {
3675                 throw new BadRequestException("no albumname specified");
3676         }
3677         // check if album is existing
3678         $r = q(
3679                 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3680                 intval(api_user()),
3681                 dbesc($album)
3682         );
3683         if (!DBM::is_result($r))
3684                 throw new BadRequestException("album not available");
3685
3686         // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3687         // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3688         foreach ($r as $rr) {
3689                 $photo_item = q(
3690                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3691                         intval(local_user()),
3692                         dbesc($rr['resource-id'])
3693                 );
3694
3695                 if (!DBM::is_result($photo_item)) {
3696                         throw new InternalServerErrorException("problem with deleting items occured");
3697                 }
3698                 drop_item($photo_item[0]['id'], false);
3699         }
3700
3701         // now let's delete all photos from the album
3702         $result = dba::delete('photo', array('uid' => api_user(), 'album' => $album));
3703
3704         // return success of deletion or error message
3705         if ($result) {
3706                 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3707                 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3708         } else {
3709                 throw new InternalServerErrorException("unknown error - deleting from database failed");
3710         }
3711 }
3712
3713 /**
3714  * @brief update the name of the album for all photos of an album
3715  *
3716  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3717  * @return string
3718  */
3719 function api_fr_photoalbum_update($type)
3720 {
3721         if (api_user() === false) {
3722                 throw new ForbiddenException();
3723         }
3724         // input params
3725         $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3726         $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3727
3728         // we do not allow calls without album string
3729         if ($album == "") {
3730                 throw new BadRequestException("no albumname specified");
3731         }
3732         if ($album_new == "") {
3733                 throw new BadRequestException("no new albumname specified");
3734         }
3735         // check if album is existing
3736         $r = q(
3737                 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3738                 intval(api_user()),
3739                 dbesc($album)
3740         );
3741         if (!DBM::is_result($r)) {
3742                 throw new BadRequestException("album not available");
3743         }
3744         // now let's update all photos to the albumname
3745         $result = q(
3746                 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3747                 dbesc($album_new),
3748                 intval(api_user()),
3749                 dbesc($album)
3750         );
3751
3752         // return success of updating or error message
3753         if ($result) {
3754                 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3755                 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3756         } else {
3757                 throw new InternalServerErrorException("unknown error - updating in database failed");
3758         }
3759 }
3760
3761
3762 /**
3763  * @brief list all photos of the authenticated user
3764  *
3765  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3766  * @return string
3767  */
3768 function api_fr_photos_list($type)
3769 {
3770         if (api_user() === false) {
3771                 throw new ForbiddenException();
3772         }
3773         $r = q(
3774                 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3775                 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3776                 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3777                 intval(local_user())
3778         );
3779         $typetoext = array(
3780                 'image/jpeg' => 'jpg',
3781                 'image/png' => 'png',
3782                 'image/gif' => 'gif'
3783         );
3784         $data = array('photo'=>array());
3785         if (DBM::is_result($r)) {
3786                 foreach ($r as $rr) {
3787                         $photo = array();
3788                         $photo['id'] = $rr['resource-id'];
3789                         $photo['album'] = $rr['album'];
3790                         $photo['filename'] = $rr['filename'];
3791                         $photo['type'] = $rr['type'];
3792                         $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3793                         $photo['created'] = $rr['created'];
3794                         $photo['edited'] = $rr['edited'];
3795                         $photo['desc'] = $rr['desc'];
3796
3797                         if ($type == "xml") {
3798                                 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3799                         } else {
3800                                 $photo['thumb'] = $thumb;
3801                                 $data['photo'][] = $photo;
3802                         }
3803                 }
3804         }
3805         return api_format_data("photos", $type, $data);
3806 }
3807
3808 /**
3809  * @brief upload a new photo or change an existing photo
3810  *
3811  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3812  * @return string
3813  */
3814 function api_fr_photo_create_update($type)
3815 {
3816         if (api_user() === false) {
3817                 throw new ForbiddenException();
3818         }
3819         // input params
3820         $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3821         $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3822         $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3823         $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3824         $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3825         $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3826         $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3827         $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3828         $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3829
3830         // do several checks on input parameters
3831         // we do not allow calls without album string
3832         if ($album == null) {
3833                 throw new BadRequestException("no albumname specified");
3834         }
3835         // if photo_id == null --> we are uploading a new photo
3836         if ($photo_id == null) {
3837                 $mode = "create";
3838
3839                 // error if no media posted in create-mode
3840                 if (!x($_FILES, 'media')) {
3841                         // Output error
3842                         throw new BadRequestException("no media data submitted");
3843                 }
3844
3845                 // album_new will be ignored in create-mode
3846                 $album_new = "";
3847         } else {
3848                 $mode = "update";
3849
3850                 // check if photo is existing in database
3851                 $r = q(
3852                         "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3853                         intval(api_user()),
3854                         dbesc($photo_id),
3855                         dbesc($album)
3856                 );
3857                 if (!DBM::is_result($r)) {
3858                         throw new BadRequestException("photo not available");
3859                 }
3860         }
3861
3862         // checks on acl strings provided by clients
3863         $acl_input_error = false;
3864         $acl_input_error |= check_acl_input($allow_cid);
3865         $acl_input_error |= check_acl_input($deny_cid);
3866         $acl_input_error |= check_acl_input($allow_gid);
3867         $acl_input_error |= check_acl_input($deny_gid);
3868         if ($acl_input_error) {
3869                 throw new BadRequestException("acl data invalid");
3870         }
3871         // now let's upload the new media in create-mode
3872         if ($mode == "create") {
3873                 $media = $_FILES['media'];
3874                 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3875
3876                 // return success of updating or error message
3877                 if (!is_null($data)) {
3878                         return api_format_data("photo_create", $type, $data);
3879                 } else {
3880                         throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3881                 }
3882         }
3883
3884         // now let's do the changes in update-mode
3885         if ($mode == "update") {
3886                 $sql_extra = "";
3887
3888                 if (!is_null($desc)) {
3889                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3890                 }
3891
3892                 if (!is_null($album_new)) {
3893                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3894                 }
3895
3896                 if (!is_null($allow_cid)) {
3897                         $allow_cid = trim($allow_cid);
3898                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3899                 }
3900
3901                 if (!is_null($deny_cid)) {
3902                         $deny_cid = trim($deny_cid);
3903                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3904                 }
3905
3906                 if (!is_null($allow_gid)) {
3907                         $allow_gid = trim($allow_gid);
3908                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3909                 }
3910
3911                 if (!is_null($deny_gid)) {
3912                         $deny_gid = trim($deny_gid);
3913                         $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3914                 }
3915
3916                 $result = false;
3917                 if ($sql_extra != "") {
3918                         $nothingtodo = false;
3919                         $result = q(
3920                                 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3921                                 $sql_extra,
3922                                 datetime_convert(),   // update edited timestamp
3923                                 intval(api_user()),
3924                                 dbesc($photo_id),
3925                                 dbesc($album)
3926                         );
3927                 } else {
3928                         $nothingtodo = true;
3929                 }
3930
3931                 if (x($_FILES, 'media')) {
3932                         $nothingtodo = false;
3933                         $media = $_FILES['media'];
3934                         $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3935                         if (!is_null($data)) {
3936                                 return api_format_data("photo_update", $type, $data);
3937                         }
3938                 }
3939
3940                 // return success of updating or error message
3941                 if ($result) {
3942                         $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
3943                         return api_format_data("photo_update", $type, array('$result' => $answer));
3944                 } else {
3945                         if ($nothingtodo) {
3946                                 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
3947                                 return api_format_data("photo_update", $type, array('$result' => $answer));
3948                         }
3949                         throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3950                 }
3951         }
3952         throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3953 }
3954
3955
3956 /**
3957  * @brief delete a single photo from the database through api
3958  *
3959  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3960  * @return string
3961  */
3962 function api_fr_photo_delete($type)
3963 {
3964         if (api_user() === false) {
3965                 throw new ForbiddenException();
3966         }
3967         // input params
3968         $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3969
3970         // do several checks on input parameters
3971         // we do not allow calls without photo id
3972         if ($photo_id == null) {
3973                 throw new BadRequestException("no photo_id specified");
3974         }
3975         // check if photo is existing in database
3976         $r = q(
3977                 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3978                 intval(api_user()),
3979                 dbesc($photo_id)
3980         );
3981         if (!DBM::is_result($r)) {
3982                 throw new BadRequestException("photo not available");
3983         }
3984         // now we can perform on the deletion of the photo
3985         $result = dba::delete('photo', array('uid' => api_user(), 'resource-id' => $photo_id));
3986
3987         // return success of deletion or error message
3988         if ($result) {
3989                 // retrieve the id of the parent element (the photo element)
3990                 $photo_item = q(
3991                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3992                         intval(local_user()),
3993                         dbesc($photo_id)
3994                 );
3995
3996                 if (!DBM::is_result($photo_item)) {
3997                         throw new InternalServerErrorException("problem with deleting items occured");
3998                 }
3999                 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4000                 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4001                 drop_item($photo_item[0]['id'], false);
4002
4003                 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
4004                 return api_format_data("photo_delete", $type, array('$result' => $answer));
4005         } else {
4006                 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4007         }
4008 }
4009
4010
4011 /**
4012  * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4013  *
4014  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4015  * @return string
4016  */
4017 function api_fr_photo_detail($type)
4018 {
4019         if (api_user() === false) {
4020                 throw new ForbiddenException();
4021         }
4022         if (!x($_REQUEST, 'photo_id')) {
4023                 throw new BadRequestException("No photo id.");
4024         }
4025
4026         $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4027         $photo_id = $_REQUEST['photo_id'];
4028
4029         // prepare json/xml output with data from database for the requested photo
4030         $data = prepare_photo_data($type, $scale, $photo_id);
4031
4032         return api_format_data("photo_detail", $type, $data);
4033 }
4034
4035
4036 /**
4037  * @brief updates the profile image for the user (either a specified profile or the default profile)
4038  *
4039  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4040  * @return string
4041  */
4042 function api_account_update_profile_image($type)
4043 {
4044         if (api_user() === false) {
4045                 throw new ForbiddenException();
4046         }
4047         // input params
4048         $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
4049
4050         // error if image data is missing
4051         if (!x($_FILES, 'image')) {
4052                 throw new BadRequestException("no media data submitted");
4053         }
4054
4055         // check if specified profile id is valid
4056         if ($profileid != 0) {
4057                 $r = q(
4058                         "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4059                         intval(api_user()),
4060                         intval($profileid)
4061                 );
4062                 // error message if specified profile id is not in database
4063                 if (!DBM::is_result($r)) {
4064                         throw new BadRequestException("profile_id not available");
4065                 }
4066                 $is_default_profile = $r['profile'];
4067         } else {
4068                 $is_default_profile = 1;
4069         }
4070
4071         // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4072         $media = null;
4073         if (x($_FILES, 'image')) {
4074                 $media = $_FILES['image'];
4075         } elseif (x($_FILES, 'media')) {
4076                 $media = $_FILES['media'];
4077         }
4078         // save new profile image
4079         $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4080
4081         // get filetype
4082         if (is_array($media['type'])) {
4083                 $filetype = $media['type'][0];
4084         } else {
4085                 $filetype = $media['type'];
4086         }
4087         if ($filetype == "image/jpeg") {
4088                 $fileext = "jpg";
4089         } elseif ($filetype == "image/png") {
4090                 $fileext = "png";
4091         }
4092         // change specified profile or all profiles to the new resource-id
4093         if ($is_default_profile) {
4094                 $r = q(
4095                         "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4096                         dbesc($data['photo']['id']),
4097                         intval(local_user())
4098                 );
4099
4100                 $r = q(
4101                         "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s'  WHERE `self` AND `uid` = %d",
4102                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4103                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4104                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4105                         intval(local_user())
4106                 );
4107         } else {
4108                 $r = q(
4109                         "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4110                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4111                         dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4112                         intval($_REQUEST['profile']),
4113                         intval(local_user())
4114                 );
4115         }
4116
4117         // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4118         // so that browsers will do a cache update unconditionally
4119
4120         $r = q(
4121                 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4122                 dbesc(datetime_convert()),
4123                 intval(local_user())
4124         );
4125
4126         // Update global directory in background
4127         //$user = api_get_user(get_app());
4128         $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4129         if ($url && strlen(Config::get('system', 'directory'))) {
4130                 Worker::add(PRIORITY_LOW, "Directory", $url);
4131         }
4132
4133         Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4134
4135         // output for client
4136         if ($data) {
4137                 return api_account_verify_credentials($type);
4138         } else {
4139                 // SaveMediaToDatabase failed for some reason
4140                 throw new InternalServerErrorException("image upload failed");
4141         }
4142 }
4143
4144 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4145 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4146 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4147 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4148 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4149 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4150 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4151 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4152 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4153
4154
4155 function check_acl_input($acl_string)
4156 {
4157         if ($acl_string == null || $acl_string == " ") {
4158                 return false;
4159         }
4160         $contact_not_found = false;
4161
4162         // split <x><y><z> into array of cid's
4163         preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4164
4165         // check for each cid if it is available on server
4166         $cid_array = $array[0];
4167         foreach ($cid_array as $cid) {
4168                 $cid = str_replace("<", "", $cid);
4169                 $cid = str_replace(">", "", $cid);
4170                 $contact = q(
4171                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4172                         intval($cid),
4173                         intval(api_user())
4174                 );
4175                 $contact_not_found |= !DBM::is_result($contact);
4176         }
4177         return $contact_not_found;
4178 }
4179
4180 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)
4181 {
4182         $visitor   = 0;
4183         $src = "";
4184         $filetype = "";
4185         $filename = "";
4186         $filesize = 0;
4187
4188         if (is_array($media)) {
4189                 if (is_array($media['tmp_name'])) {
4190                         $src = $media['tmp_name'][0];
4191                 } else {
4192                         $src = $media['tmp_name'];
4193                 }
4194                 if (is_array($media['name'])) {
4195                         $filename = basename($media['name'][0]);
4196                 } else {
4197                         $filename = basename($media['name']);
4198                 }
4199                 if (is_array($media['size'])) {
4200                         $filesize = intval($media['size'][0]);
4201                 } else {
4202                         $filesize = intval($media['size']);
4203                 }
4204                 if (is_array($media['type'])) {
4205                         $filetype = $media['type'][0];
4206                 } else {
4207                         $filetype = $media['type'];
4208                 }
4209         }
4210
4211         if ($filetype == "") {
4212                 $filetype=Image::guessType($filename);
4213         }
4214         $imagedata = getimagesize($src);
4215         if ($imagedata) {
4216                 $filetype = $imagedata['mime'];
4217         }
4218         logger(
4219                 "File upload src: " . $src . " - filename: " . $filename .
4220                 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG
4221         );
4222
4223         // check if there was a php upload error
4224         if ($filesize == 0 && $media['error'] == 1) {
4225                 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4226         }
4227         // check against max upload size within Friendica instance
4228         $maximagesize = Config::get('system', 'maximagesize');
4229         if (($maximagesize) && ($filesize > $maximagesize)) {
4230                 $formattedBytes = formatBytes($maximagesize);
4231                 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4232         }
4233
4234         // create Photo instance with the data of the image
4235         $imagedata = @file_get_contents($src);
4236         $Image = new Image($imagedata, $filetype);
4237         if (! $Image->isValid()) {
4238                 throw new InternalServerErrorException("unable to process image data");
4239         }
4240
4241         // check orientation of image
4242         $Image->orient($src);
4243         @unlink($src);
4244
4245         // check max length of images on server
4246         $max_length = Config::get('system', 'max_image_length');
4247         if (! $max_length) {
4248                 $max_length = MAX_IMAGE_LENGTH;
4249         }
4250         if ($max_length > 0) {
4251                 $Image->scaleDown($max_length);
4252                 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4253         }
4254         $width = $Image->getWidth();
4255         $height = $Image->getHeight();
4256
4257         // create a new resource-id if not already provided
4258         $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
4259
4260         if ($mediatype == "photo") {
4261                 // upload normal image (scales 0, 1, 2)
4262                 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4263
4264                 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4265                 if (! $r) {
4266                         logger("photo upload: image upload with scale 0 (original size) failed");
4267                 }
4268                 if ($width > 640 || $height > 640) {
4269                         $Image->scaleDown(640);
4270                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4271                         if (! $r) {
4272                                 logger("photo upload: image upload with scale 1 (640x640) failed");
4273                         }
4274                 }
4275
4276                 if ($width > 320 || $height > 320) {
4277                         $Image->scaleDown(320);
4278                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4279                         if (! $r) {
4280                                 logger("photo upload: image upload with scale 2 (320x320) failed");
4281                         }
4282                 }
4283                 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4284         } elseif ($mediatype == "profileimage") {
4285                 // upload profile image (scales 4, 5, 6)
4286                 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4287
4288                 if ($width > 175 || $height > 175) {
4289                         $Image->scaleDown(175);
4290                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4291                         if (! $r) {
4292                                 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4293                         }
4294                 }
4295
4296                 if ($width > 80 || $height > 80) {
4297                         $Image->scaleDown(80);
4298                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4299                         if (! $r) {
4300                                 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4301                         }
4302                 }
4303
4304                 if ($width > 48 || $height > 48) {
4305                         $Image->scaleDown(48);
4306                         $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4307                         if (! $r) {
4308                                 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4309                         }
4310                 }
4311                 $Image->__destruct();
4312                 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4313         }
4314
4315         if ($r) {
4316                 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4317                 if ($photo_id == null && $mediatype == "photo") {
4318                         post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4319                 }
4320                 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4321                 return prepare_photo_data($type, false, $hash);
4322         } else {
4323                 throw new InternalServerErrorException("image upload failed");
4324         }
4325 }
4326
4327 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4328 {
4329         // get data about the api authenticated user
4330         $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4331         $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4332
4333         $arr = array();
4334         $arr['guid']          = get_guid(32);
4335         $arr['uid']           = intval(api_user());
4336         $arr['uri']           = $uri;
4337         $arr['parent-uri']    = $uri;
4338         $arr['type']          = 'photo';
4339         $arr['wall']          = 1;
4340         $arr['resource-id']   = $hash;
4341         $arr['contact-id']    = $owner_record[0]['id'];
4342         $arr['owner-name']    = $owner_record[0]['name'];
4343         $arr['owner-link']    = $owner_record[0]['url'];
4344         $arr['owner-avatar']  = $owner_record[0]['thumb'];
4345         $arr['author-name']   = $owner_record[0]['name'];
4346         $arr['author-link']   = $owner_record[0]['url'];
4347         $arr['author-avatar'] = $owner_record[0]['thumb'];
4348         $arr['title']         = "";
4349         $arr['allow_cid']     = $allow_cid;
4350         $arr['allow_gid']     = $allow_gid;
4351         $arr['deny_cid']      = $deny_cid;
4352         $arr['deny_gid']      = $deny_gid;
4353         $arr['last-child']    = 1;
4354         $arr['visible']       = $visibility;
4355         $arr['origin']        = 1;
4356
4357         $typetoext = array(
4358                         'image/jpeg' => 'jpg',
4359                         'image/png' => 'png',
4360                         'image/gif' => 'gif'
4361                         );
4362
4363         // adds link to the thumbnail scale photo
4364         $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4365                                 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4366                                 . '[/url]';
4367
4368         // do the magic for storing the item in the database and trigger the federation to other contacts
4369         item_store($arr);
4370 }
4371
4372 function prepare_photo_data($type, $scale, $photo_id)
4373 {
4374         $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4375         $data_sql = ($scale === false ? "" : "data, ");
4376
4377         // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4378         // clients needs to convert this in their way for further processing
4379         $r = q(
4380                 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4381                                         `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4382                                         MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4383                         FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4384                 $data_sql,
4385                 intval(local_user()),
4386                 dbesc($photo_id),
4387                 $scale_sql
4388         );
4389
4390         $typetoext = array(
4391                 'image/jpeg' => 'jpg',
4392                 'image/png' => 'png',
4393                 'image/gif' => 'gif'
4394         );
4395
4396         // prepare output data for photo
4397         if (DBM::is_result($r)) {
4398                 $data = array('photo' => $r[0]);
4399                 $data['photo']['id'] = $data['photo']['resource-id'];
4400                 if ($scale !== false) {
4401                         $data['photo']['data'] = base64_encode($data['photo']['data']);
4402                 } else {
4403                         unset($data['photo']['datasize']); //needed only with scale param
4404                 }
4405                 if ($type == "xml") {
4406                         $data['photo']['links'] = array();
4407                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4408                                 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4409                                                                                 "scale" => $k,
4410                                                                                 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4411                         }
4412                 } else {
4413                         $data['photo']['link'] = array();
4414                         // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4415                         $i = 0;
4416                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4417                                 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4418                                 $i++;
4419                         }
4420                 }
4421                 unset($data['photo']['resource-id']);
4422                 unset($data['photo']['minscale']);
4423                 unset($data['photo']['maxscale']);
4424         } else {
4425                 throw new NotFoundException();
4426         }
4427
4428         // retrieve item element for getting activities (like, dislike etc.) related to photo
4429         $item = q(
4430                 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4431                 intval(local_user()),
4432                 dbesc($photo_id)
4433         );
4434         $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4435
4436         // retrieve comments on photo
4437         $r = q(
4438                 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4439                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4440                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4441                 `contact`.`id` AS `cid`
4442                 FROM `item`
4443                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4444                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4445                 WHERE `item`.`parent` = %d AND `item`.`visible`
4446                 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4447                 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4448                 intval($item[0]['parent']),
4449                 intval(api_user()),
4450                 dbesc(ACTIVITY_POST)
4451         );
4452
4453         // prepare output of comments
4454         $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4455         $comments = array();
4456         if ($type == "xml") {
4457                 $k = 0;
4458                 foreach ($commentData as $comment) {
4459                         $comments[$k++ . ":comment"] = $comment;
4460                 }
4461         } else {
4462                 foreach ($commentData as $comment) {
4463                         $comments[] = $comment;
4464                 }
4465         }
4466         $data['photo']['friendica_comments'] = $comments;
4467
4468         // include info if rights on photo and rights on item are mismatching
4469         $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4470                 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4471                 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4472                 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4473         $data['photo']['rights_mismatch'] = $rights_mismatch;
4474
4475         return $data;
4476 }
4477
4478
4479 /**
4480  * Similar as /mod/redir.php
4481  * redirect to 'url' after dfrn auth
4482  *
4483  * Why this when there is mod/redir.php already?
4484  * This use api_user() and api_login()
4485  *
4486  * params
4487  *              c_url: url of remote contact to auth to
4488  *              url: string, url to redirect after auth
4489  */
4490 function api_friendica_remoteauth()
4491 {
4492         $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4493         $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4494
4495         if ($url === '' || $c_url === '') {
4496                 throw new BadRequestException("Wrong parameters.");
4497         }
4498
4499         $c_url = normalise_link($c_url);
4500
4501         // traditional DFRN
4502
4503         $r = q(
4504                 "SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4505                 dbesc($c_url),
4506                 intval(api_user())
4507         );
4508
4509         if ((! DBM::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4510                 throw new BadRequestException("Unknown contact");
4511         }
4512
4513         $cid = $r[0]['id'];
4514
4515         $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4516
4517         if ($r[0]['duplex'] && $r[0]['issued-id']) {
4518                 $orig_id = $r[0]['issued-id'];
4519                 $dfrn_id = '1:' . $orig_id;
4520         }
4521         if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4522                 $orig_id = $r[0]['dfrn-id'];
4523                 $dfrn_id = '0:' . $orig_id;
4524         }
4525
4526         $sec = random_string();
4527
4528         q(
4529                 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4530                 VALUES( %d, %s, '%s', '%s', %d )",
4531                 intval(api_user()),
4532                 intval($cid),
4533                 dbesc($dfrn_id),
4534                 dbesc($sec),
4535                 intval(time() + 45)
4536         );
4537
4538         logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4539         $dest = (($url) ? '&destination_url=' . $url : '');
4540         goaway(
4541                 $r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4542                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4543                 . '&type=profile&sec=' . $sec . $dest . $quiet
4544         );
4545 }
4546 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4547
4548 /**
4549  * @brief Return the item shared, if the item contains only the [share] tag
4550  *
4551  * @param array $item Sharer item
4552  * @return array Shared item or false if not a reshare
4553  */
4554 function api_share_as_retweet(&$item)
4555 {
4556         $body = trim($item["body"]);
4557
4558         if (Diaspora::isReshare($body, false)===false) {
4559                 return false;
4560         }
4561
4562         /// @TODO "$1" should maybe mean '$1' ?
4563         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4564         /*
4565                 * Skip if there is no shared message in there
4566                 * we already checked this in diaspora::isReshare()
4567                 * but better one more than one less...
4568                 */
4569         if ($body == $attributes) {
4570                 return false;
4571         }
4572
4573
4574         // build the fake reshared item
4575         $reshared_item = $item;
4576
4577         $author = "";
4578         preg_match("/author='(.*?)'/ism", $attributes, $matches);
4579         if ($matches[1] != "") {
4580                 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4581         }
4582
4583         preg_match('/author="(.*?)"/ism', $attributes, $matches);
4584         if ($matches[1] != "") {
4585                 $author = $matches[1];
4586         }
4587
4588         $profile = "";
4589         preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4590         if ($matches[1] != "") {
4591                 $profile = $matches[1];
4592         }
4593
4594         preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4595         if ($matches[1] != "") {
4596                 $profile = $matches[1];
4597         }
4598
4599         $avatar = "";
4600         preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4601         if ($matches[1] != "") {
4602                 $avatar = $matches[1];
4603         }
4604
4605         preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4606         if ($matches[1] != "") {
4607                 $avatar = $matches[1];
4608         }
4609
4610         $link = "";
4611         preg_match("/link='(.*?)'/ism", $attributes, $matches);
4612         if ($matches[1] != "") {
4613                 $link = $matches[1];
4614         }
4615
4616         preg_match('/link="(.*?)"/ism', $attributes, $matches);
4617         if ($matches[1] != "") {
4618                 $link = $matches[1];
4619         }
4620
4621         $posted = "";
4622         preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4623         if ($matches[1] != "")
4624                 $posted = $matches[1];
4625
4626         preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4627         if ($matches[1] != "") {
4628                 $posted = $matches[1];
4629         }
4630
4631         $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4632
4633         if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4634                 return false;
4635         }
4636
4637         $reshared_item["body"] = $shared_body;
4638         $reshared_item["author-name"] = $author;
4639         $reshared_item["author-link"] = $profile;
4640         $reshared_item["author-avatar"] = $avatar;
4641         $reshared_item["plink"] = $link;
4642         $reshared_item["created"] = $posted;
4643         $reshared_item["edited"] = $posted;
4644
4645         return $reshared_item;
4646
4647 }
4648
4649 function api_get_nick($profile)
4650 {
4651         /* To-Do:
4652                 - remove trailing junk from profile url
4653                 - pump.io check has to check the website
4654         */
4655
4656         $nick = "";
4657
4658         $r = q(
4659                 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4660                 dbesc(normalise_link($profile))
4661         );
4662
4663         if (DBM::is_result($r)) {
4664                 $nick = $r[0]["nick"];
4665         }
4666
4667         if (!$nick == "") {
4668                 $r = q(
4669                         "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4670                         dbesc(normalise_link($profile))
4671                 );
4672
4673                 if (DBM::is_result($r)) {
4674                         $nick = $r[0]["nick"];
4675                 }
4676         }
4677
4678         if (!$nick == "") {
4679                 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4680                 if ($friendica != $profile) {
4681                         $nick = $friendica;
4682                 }
4683         }
4684
4685         if (!$nick == "") {
4686                 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4687                 if ($diaspora != $profile) {
4688                         $nick = $diaspora;
4689                 }
4690         }
4691
4692         if (!$nick == "") {
4693                 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4694                 if ($twitter != $profile) {
4695                         $nick = $twitter;
4696                 }
4697         }
4698
4699
4700         if (!$nick == "") {
4701                 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4702                 if ($StatusnetHost != $profile) {
4703                         $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4704                         if ($StatusnetUser != $profile) {
4705                                 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4706                                 $user = json_decode($UserData);
4707                                 if ($user) {
4708                                         $nick = $user->screen_name;
4709                                 }
4710                         }
4711                 }
4712         }
4713
4714         // To-Do: look at the page if its really a pumpio site
4715         //if (!$nick == "") {
4716         //      $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4717         //      if ($pumpio != $profile)
4718         //              $nick = $pumpio;
4719                 //      <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4720
4721         //}
4722
4723         if ($nick != "") {
4724                 return $nick;
4725         }
4726
4727         return false;
4728 }
4729
4730 function api_in_reply_to($item)
4731 {
4732         $in_reply_to = array();
4733
4734         $in_reply_to['status_id'] = null;
4735         $in_reply_to['user_id'] = null;
4736         $in_reply_to['status_id_str'] = null;
4737         $in_reply_to['user_id_str'] = null;
4738         $in_reply_to['screen_name'] = null;
4739
4740         if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4741                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4742                         intval($item['uid']),
4743                         dbesc($item['thr-parent']));
4744
4745                 if (DBM::is_result($r)) {
4746                         $in_reply_to['status_id'] = intval($r[0]['id']);
4747                 } else {
4748                         $in_reply_to['status_id'] = intval($item['parent']);
4749                 }
4750
4751                 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4752
4753                 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4754                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4755                         WHERE `item`.`id` = %d LIMIT 1",
4756                         intval($in_reply_to['status_id'])
4757                 );
4758
4759                 if (DBM::is_result($r)) {
4760                         if ($r[0]['nick'] == "") {
4761                                 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4762                         }
4763
4764                         $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4765                         $in_reply_to['user_id'] = intval($r[0]['id']);
4766                         $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4767                 }
4768
4769                 // There seems to be situation, where both fields are identical:
4770                 // https://github.com/friendica/friendica/issues/1010
4771                 // This is a bugfix for that.
4772                 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4773                         logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4774                         $in_reply_to['status_id'] = null;
4775                         $in_reply_to['user_id'] = null;
4776                         $in_reply_to['status_id_str'] = null;
4777                         $in_reply_to['user_id_str'] = null;
4778                         $in_reply_to['screen_name'] = null;
4779                 }
4780         }
4781
4782         return $in_reply_to;
4783 }
4784
4785 function api_clean_plain_items($Text)
4786 {
4787         $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4788
4789         $Text = bb_CleanPictureLinks($Text);
4790         $URLSearchString = "^\[\]";
4791
4792         $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
4793
4794         if ($include_entities == "true") {
4795                 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
4796         }
4797
4798         // Simplify "attachment" element
4799         $Text = api_clean_attachments($Text);
4800
4801         return($Text);
4802 }
4803
4804 /**
4805  * @brief Removes most sharing information for API text export
4806  *
4807  * @param string $body The original body
4808  *
4809  * @return string Cleaned body
4810  */
4811 function api_clean_attachments($body)
4812 {
4813         $data = get_attachment_data($body);
4814
4815         if (!$data)
4816                 return $body;
4817
4818         $body = "";
4819
4820         if (isset($data["text"]))
4821                 $body = $data["text"];
4822
4823         if (($body == "") && (isset($data["title"])))
4824                 $body = $data["title"];
4825
4826         if (isset($data["url"]))
4827                 $body .= "\n".$data["url"];
4828
4829         $body .= $data["after"];
4830
4831         return $body;
4832 }
4833
4834 function api_best_nickname(&$contacts)
4835 {
4836         $best_contact = array();
4837
4838         if (count($contact) == 0)
4839                 return;
4840
4841         foreach ($contacts as $contact)
4842                 if ($contact["network"] == "") {
4843                         $contact["network"] = "dfrn";
4844                         $best_contact = array($contact);
4845                 }
4846
4847         if (sizeof($best_contact) == 0)
4848                 foreach ($contacts as $contact)
4849                         if ($contact["network"] == "dfrn")
4850                                 $best_contact = array($contact);
4851
4852         if (sizeof($best_contact) == 0)
4853                 foreach ($contacts as $contact)
4854                         if ($contact["network"] == "dspr")
4855                                 $best_contact = array($contact);
4856
4857         if (sizeof($best_contact) == 0)
4858                 foreach ($contacts as $contact)
4859                         if ($contact["network"] == "stat")
4860                                 $best_contact = array($contact);
4861
4862         if (sizeof($best_contact) == 0)
4863                 foreach ($contacts as $contact)
4864                         if ($contact["network"] == "pump")
4865                                 $best_contact = array($contact);
4866
4867         if (sizeof($best_contact) == 0)
4868                 foreach ($contacts as $contact)
4869                         if ($contact["network"] == "twit")
4870                                 $best_contact = array($contact);
4871
4872         if (sizeof($best_contact) == 1) {
4873                 $contacts = $best_contact;
4874         } else {
4875                 $contacts = array($contacts[0]);
4876         }
4877 }
4878
4879 // return all or a specified group of the user with the containing contacts
4880 function api_friendica_group_show($type)
4881 {
4882         $a = get_app();
4883
4884         if (api_user() === false) throw new ForbiddenException();
4885
4886         // params
4887         $user_info = api_get_user($a);
4888         $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4889         $uid = $user_info['uid'];
4890
4891         // get data of the specified group id or all groups if not specified
4892         if ($gid != 0) {
4893                 $r = q(
4894                         "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4895                         intval($uid),
4896                         intval($gid)
4897                 );
4898                 // error message if specified gid is not in database
4899                 if (!DBM::is_result($r))
4900                         throw new BadRequestException("gid not available");
4901         } else {
4902                 $r = q(
4903                         "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4904                         intval($uid)
4905                 );
4906         }
4907
4908         // loop through all groups and retrieve all members for adding data in the user array
4909         foreach ($r as $rr) {
4910                 $members = Contact::getByGroupId($rr['id']);
4911                 $users = array();
4912
4913                 if ($type == "xml") {
4914                         $user_element = "users";
4915                         $k = 0;
4916                         foreach ($members as $member) {
4917                                 $user = api_get_user($a, $member['nurl']);
4918                                 $users[$k++.":user"] = $user;
4919                         }
4920                 } else {
4921                         $user_element = "user";
4922                         foreach ($members as $member) {
4923                                 $user = api_get_user($a, $member['nurl']);
4924                                 $users[] = $user;
4925                         }
4926                 }
4927                 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4928         }
4929         return api_format_data("groups", $type, array('group' => $grps));
4930 }
4931 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4932
4933
4934 // delete the specified group of the user
4935 function api_friendica_group_delete($type)
4936 {
4937         $a = get_app();
4938
4939         if (api_user() === false) {
4940                 throw new ForbiddenException();
4941         }
4942
4943         // params
4944         $user_info = api_get_user($a);
4945         $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4946         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4947         $uid = $user_info['uid'];
4948
4949         // error if no gid specified
4950         if ($gid == 0 || $name == "") {
4951                 throw new BadRequestException('gid or name not specified');
4952         }
4953
4954         // get data of the specified group id
4955         $r = q(
4956                 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
4957                 intval($uid),
4958                 intval($gid)
4959         );
4960         // error message if specified gid is not in database
4961         if (!DBM::is_result($r)) {
4962                 throw new BadRequestException('gid not available');
4963         }
4964
4965         // get data of the specified group id and group name
4966         $rname = q(
4967                 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
4968                 intval($uid),
4969                 intval($gid),
4970                 dbesc($name)
4971         );
4972         // error message if specified gid is not in database
4973         if (!DBM::is_result($rname)) {
4974                 throw new BadRequestException('wrong group name');
4975         }
4976
4977         // delete group
4978         $ret = Group::removeByName($uid, $name);
4979         if ($ret) {
4980                 // return success
4981                 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
4982                 return api_format_data("group_delete", $type, array('result' => $success));
4983         } else {
4984                 throw new BadRequestException('other API error');
4985         }
4986 }
4987 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4988
4989
4990 // create the specified group with the posted array of contacts
4991 function api_friendica_group_create($type)
4992 {
4993         $a = get_app();
4994
4995         if (api_user() === false) throw new ForbiddenException();
4996
4997         // params
4998         $user_info = api_get_user($a);
4999         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5000         $uid = $user_info['uid'];
5001         $json = json_decode($_POST['json'], true);
5002         $users = $json['user'];
5003
5004         // error if no name specified
5005         if ($name == "")
5006                 throw new BadRequestException('group name not specified');
5007
5008         // get data of the specified group name
5009         $rname = q(
5010                 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5011                 intval($uid),
5012                 dbesc($name)
5013         );
5014         // error message if specified group name already exists
5015         if (DBM::is_result($rname))
5016                 throw new BadRequestException('group name already exists');
5017
5018         // check if specified group name is a deleted group
5019         $rname = q(
5020                 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5021                 intval($uid),
5022                 dbesc($name)
5023         );
5024         // error message if specified group name already exists
5025         if (DBM::is_result($rname))
5026                 $reactivate_group = true;
5027
5028         // create group
5029         $ret = Group::create($uid, $name);
5030         if ($ret) {
5031                 $gid = Group::getIdByName($uid, $name);
5032         } else {
5033                 throw new BadRequestException('other API error');
5034         }
5035
5036         // add members
5037         $erroraddinguser = false;
5038         $errorusers = array();
5039         foreach ($users as $user) {
5040                 $cid = $user['cid'];
5041                 // check if user really exists as contact
5042                 $contact = q(
5043                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5044                         intval($cid),
5045                         intval($uid)
5046                 );
5047                 if (count($contact))
5048                         $result = Group::addMember($gid, $cid);
5049                 else {
5050                         $erroraddinguser = true;
5051                         $errorusers[] = $cid;
5052                 }
5053         }
5054
5055         // return success message incl. missing users in array
5056         $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
5057         $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
5058         return api_format_data("group_create", $type, array('result' => $success));
5059 }
5060 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5061
5062
5063 // update the specified group with the posted array of contacts
5064 function api_friendica_group_update($type)
5065 {
5066         $a = get_app();
5067
5068         if (api_user() === false) throw new ForbiddenException();
5069
5070         // params
5071         $user_info = api_get_user($a);
5072         $uid = $user_info['uid'];
5073         $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5074         $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5075         $json = json_decode($_POST['json'], true);
5076         $users = $json['user'];
5077
5078         // error if no name specified
5079         if ($name == "")
5080                 throw new BadRequestException('group name not specified');
5081
5082         // error if no gid specified
5083         if ($gid == "")
5084                 throw new BadRequestException('gid not specified');
5085
5086         // remove members
5087         $members = Contact::getByGroupId($gid);
5088         foreach ($members as $member) {
5089                 $cid = $member['id'];
5090                 foreach ($users as $user) {
5091                         $found = ($user['cid'] == $cid ? true : false);
5092                 }
5093                 if (!$found) {
5094                         $ret = Group::removeMemberByName($uid, $name, $cid);
5095                 }
5096         }
5097
5098         // add members
5099         $erroraddinguser = false;
5100         $errorusers = array();
5101         foreach ($users as $user) {
5102                 $cid = $user['cid'];
5103                 // check if user really exists as contact
5104                 $contact = q(
5105                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5106                         intval($cid),
5107                         intval($uid)
5108                 );
5109
5110                 if (count($contact)) {
5111                         $result = Group::addMember($gid, $cid);
5112                 } else {
5113                         $erroraddinguser = true;
5114                         $errorusers[] = $cid;
5115                 }
5116         }
5117
5118         // return success message incl. missing users in array
5119         $status = ($erroraddinguser ? "missing user" : "ok");
5120         $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
5121         return api_format_data("group_update", $type, array('result' => $success));
5122 }
5123
5124 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5125
5126 function api_friendica_activity($type)
5127 {
5128         $a = get_app();
5129
5130         if (api_user() === false) throw new ForbiddenException();
5131         $verb = strtolower($a->argv[3]);
5132         $verb = preg_replace("|\..*$|", "", $verb);
5133
5134         $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5135
5136         $res = do_like($id, $verb);
5137
5138         if ($res) {
5139                 if ($type == "xml") {
5140                         $ok = "true";
5141                 } else {
5142                         $ok = "ok";
5143                 }
5144                 return api_format_data('ok', $type, array('ok' => $ok));
5145         } else {
5146                 throw new BadRequestException('Error adding activity');
5147         }
5148 }
5149
5150 /// @TODO move to top of file or somwhere better
5151 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5152 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5153 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5154 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5155 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5156 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5157 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5158 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5159 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5160 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5161
5162 /**
5163  * @brief Returns notifications
5164  *
5165  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5166  * @return string
5167 */
5168 function api_friendica_notification($type)
5169 {
5170         $a = get_app();
5171
5172         if (api_user() === false) throw new ForbiddenException();
5173         if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
5174         $nm = new NotificationsManager();
5175
5176         $notes = $nm->getAll(array(), "+seen -date", 50);
5177
5178         if ($type == "xml") {
5179                 $xmlnotes = array();
5180                 foreach ($notes as $note)
5181                         $xmlnotes[] = array("@attributes" => $note);
5182
5183                 $notes = $xmlnotes;
5184         }
5185
5186         return api_format_data("notes", $type, array('note' => $notes));
5187 }
5188
5189 /**
5190  * @brief Set notification as seen and returns associated item (if possible)
5191  *
5192  * POST request with 'id' param as notification id
5193  *
5194  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5195  * @return string
5196  */
5197 function api_friendica_notification_seen($type)
5198 {
5199         $a = get_app();
5200
5201         if (api_user() === false) throw new ForbiddenException();
5202         if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
5203
5204         $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5205
5206         $nm = new NotificationsManager();
5207         $note = $nm->getByID($id);
5208         if (is_null($note)) throw new BadRequestException("Invalid argument");
5209
5210         $nm->setSeen($note);
5211         if ($note['otype']=='item') {
5212                 // would be really better with an ItemsManager and $im->getByID() :-P
5213                 $r = q(
5214                         "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5215                         intval($note['iid']),
5216                         intval(local_user())
5217                 );
5218                 if ($r!==false) {
5219                         // we found the item, return it to the user
5220                         $user_info = api_get_user($a);
5221                         $ret = api_format_items($r, $user_info, false, $type);
5222                         $data = array('status' => $ret);
5223                         return api_format_data("status", $type, $data);
5224                 }
5225                 // the item can't be found, but we set the note as seen, so we count this as a success
5226         }
5227         return api_format_data('result', $type, array('result' => "success"));
5228 }
5229
5230 /// @TODO move to top of file or somwhere better
5231 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5232 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5233
5234 /**
5235  * @brief update a direct_message to seen state
5236  *
5237  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5238  * @return string (success result=ok, error result=error with error message)
5239  */
5240 function api_friendica_direct_messages_setseen($type)
5241 {
5242         $a = get_app();
5243         if (api_user() === false) {
5244                 throw new ForbiddenException();
5245         }
5246
5247         // params
5248         $user_info = api_get_user($a);
5249         $uid = $user_info['uid'];
5250         $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5251
5252         // return error if id is zero
5253         if ($id == "") {
5254                 $answer = array('result' => 'error', 'message' => 'message id not specified');
5255                 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5256         }
5257
5258         // get data of the specified message id
5259         $r = q(
5260                 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5261                 intval($id),
5262                 intval($uid)
5263         );
5264
5265         // error message if specified id is not in database
5266         if (!DBM::is_result($r)) {
5267                 $answer = array('result' => 'error', 'message' => 'message id not in database');
5268                 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5269         }
5270
5271         // update seen indicator
5272         $result = q(
5273                 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5274                 intval($id),
5275                 intval($uid)
5276         );
5277
5278         if ($result) {
5279                 // return success
5280                 $answer = array('result' => 'ok', 'message' => 'message set to seen');
5281                 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
5282         } else {
5283                 $answer = array('result' => 'error', 'message' => 'unknown error');
5284                 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5285         }
5286 }
5287
5288 /// @TODO move to top of file or somwhere better
5289 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5290
5291 /**
5292  * @brief search for direct_messages containing a searchstring through api
5293  *
5294  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5295  * @return string (success: success=true if found and search_result contains found messages
5296  *                          success=false if nothing was found, search_result='nothing found',
5297  *                 error: result=error with error message)
5298  */
5299 function api_friendica_direct_messages_search($type)
5300 {
5301         $a = get_app();
5302
5303         if (api_user() === false) {
5304                 throw new ForbiddenException();
5305         }
5306
5307         // params
5308         $user_info = api_get_user($a);
5309         $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5310         $uid = $user_info['uid'];
5311
5312         // error if no searchstring specified
5313         if ($searchstring == "") {
5314                 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
5315                 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
5316         }
5317
5318         // get data for the specified searchstring
5319         $r = q(
5320                 "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",
5321                 intval($uid),
5322                 dbesc('%'.$searchstring.'%')
5323         );
5324
5325         $profile_url = $user_info["url"];
5326
5327         // message if nothing was found
5328         if (!DBM::is_result($r)) {
5329                 $success = array('success' => false, 'search_results' => 'problem with query');
5330         } elseif (count($r) == 0) {
5331                 $success = array('success' => false, 'search_results' => 'nothing found');
5332         } else {
5333                 $ret = array();
5334                 foreach ($r as $item) {
5335                         if ($box == "inbox" || $item['from-url'] != $profile_url) {
5336                                 $recipient = $user_info;
5337                                 $sender = api_get_user($a, normalise_link($item['contact-url']));
5338                         } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5339                                 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5340                                 $sender = $user_info;
5341                         }
5342
5343                         $ret[] = api_format_messages($item, $recipient, $sender);
5344                 }
5345                 $success = array('success' => true, 'search_results' => $ret);
5346         }
5347
5348         return api_format_data("direct_message_search", $type, array('$result' => $success));
5349 }
5350
5351 /// @TODO move to top of file or somwhere better
5352 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5353
5354 /**
5355  * @brief return data of all the profiles a user has to the client
5356  *
5357  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5358  * @return string
5359  */
5360 function api_friendica_profile_show($type)
5361 {
5362         $a = get_app();
5363
5364         if (api_user() === false) {
5365                 throw new ForbiddenException();
5366         }
5367
5368         // input params
5369         $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5370
5371         // retrieve general information about profiles for user
5372         $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5373         $directory = Config::get('system', 'directory');
5374
5375         // get data of the specified profile id or all profiles of the user if not specified
5376         if ($profileid != 0) {
5377                 $r = q(
5378                         "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5379                         intval(api_user()),
5380                         intval($profileid)
5381                 );
5382
5383                 // error message if specified gid is not in database
5384                 if (!DBM::is_result($r)) {
5385                         throw new BadRequestException("profile_id not available");
5386                 }
5387         } else {
5388                 $r = q(
5389                         "SELECT * FROM `profile` WHERE `uid` = %d",
5390                         intval(api_user())
5391                 );
5392         }
5393         // loop through all returned profiles and retrieve data and users
5394         $k = 0;
5395         foreach ($r as $rr) {
5396                 $profile = api_format_items_profiles($rr, $type);
5397
5398                 // select all users from contact table, loop and prepare standard return for user data
5399                 $users = array();
5400                 $r = q(
5401                         "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5402                         intval(api_user()),
5403                         intval($rr['profile_id'])
5404                 );
5405
5406                 foreach ($r as $rr) {
5407                         $user = api_get_user($a, $rr['nurl']);
5408                         ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5409                 }
5410                 $profile['users'] = $users;
5411
5412                 // add prepared profile data to array for final return
5413                 if ($type == "xml") {
5414                         $profiles[$k++ . ":profile"] = $profile;
5415                 } else {
5416                         $profiles[] = $profile;
5417                 }
5418         }
5419
5420         // return settings, authenticated user and profiles data
5421         $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5422
5423         $result = array('multi_profiles' => $multi_profiles ? true : false,
5424                                         'global_dir' => $directory,
5425                                         'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5426                                         'profiles' => $profiles);
5427         return api_format_data("friendica_profiles", $type, array('$result' => $result));
5428 }
5429 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5430
5431 /*
5432 @TODO Maybe open to implement?
5433 To.Do:
5434     [pagename] => api/1.1/statuses/lookup.json
5435     [id] => 605138389168451584
5436     [include_cards] => true
5437     [cards_platform] => Android-12
5438     [include_entities] => true
5439     [include_my_retweet] => 1
5440     [include_rts] => 1
5441     [include_reply_count] => true
5442     [include_descendent_reply_count] => true
5443 (?)
5444
5445
5446 Not implemented by now:
5447 statuses/retweets_of_me
5448 friendships/create
5449 friendships/destroy
5450 friendships/exists
5451 friendships/show
5452 account/update_location
5453 account/update_profile_background_image
5454 blocks/create
5455 blocks/destroy
5456 friendica/profile/update
5457 friendica/profile/create
5458 friendica/profile/delete
5459
5460 Not implemented in status.net:
5461 statuses/retweeted_to_me
5462 statuses/retweeted_by_me
5463 direct_messages/destroy
5464 account/end_session
5465 account/update_delivery_device
5466 notifications/follow
5467 notifications/leave
5468 blocks/exists
5469 blocks/blocking
5470 lists
5471 */