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