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