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