]> git.mxchange.org Git - friendica.git/blob - include/api.php
Merge pull request #1272 from annando/1412-api-attachments
[friendica.git] / include / api.php
1 <?php
2 /* To-Do:
3  - Automatically detect if incoming data is HTML or BBCode
4 */
5         require_once("include/bbcode.php");
6         require_once("include/datetime.php");
7         require_once("include/conversation.php");
8         require_once("include/oauth.php");
9         require_once("include/html2plain.php");
10         /*
11          * Twitter-Like API
12          *
13          */
14
15         $API = Array();
16         $called_api = Null;
17
18         function api_user() {
19                 // It is not sufficient to use local_user() to check whether someone is allowed to use the API,
20                 // because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
21                 // into a page, and visitors will post something without noticing it).
22                 // Instead, use this function.
23                 if ($_SESSION["allow_api"])
24                         return local_user();
25
26                 return false;
27         }
28
29         function api_source() {
30                 if (requestdata('source'))
31                         return (requestdata('source'));
32
33                 // Support for known clients that doesn't send a source name
34                 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
35                         return ("Twidere");
36
37                 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
38
39                 return ("api");
40         }
41
42         function api_date($str){
43                 //Wed May 23 06:01:13 +0000 2007
44                 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
45         }
46
47
48         function api_register_func($path, $func, $auth=false){
49                 global $API;
50                 $API[$path] = array('func'=>$func, 'auth'=>$auth);
51
52                 // Workaround for hotot
53                 $path = str_replace("api/", "api/1.1/", $path);
54                 $API[$path] = array('func'=>$func, 'auth'=>$auth);
55         }
56
57         /**
58          * Simple HTTP Login
59          */
60
61         function api_login(&$a){
62                 // login with oauth
63                 try{
64                         $oauth = new FKOAuth1();
65                         list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
66                         if (!is_null($token)){
67                                 $oauth->loginUser($token->uid);
68                                 call_hooks('logged_in', $a->user);
69                                 return;
70                         }
71                         echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
72                 }catch(Exception $e){
73                         logger(__file__.__line__.__function__."\n".$e);
74                         //die(__file__.__line__.__function__."<pre>".$e); die();
75                 }
76
77
78
79                 // workaround for HTTP-auth in CGI mode
80                 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
81                         $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
82                         if(strlen($userpass)) {
83                                 list($name, $password) = explode(':', $userpass);
84                                 $_SERVER['PHP_AUTH_USER'] = $name;
85                                 $_SERVER['PHP_AUTH_PW'] = $password;
86                         }
87                 }
88
89                 if (!isset($_SERVER['PHP_AUTH_USER'])) {
90                         logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
91                         header('WWW-Authenticate: Basic realm="Friendica"');
92                         header('HTTP/1.0 401 Unauthorized');
93                         die((api_error($a, 'json', "This api requires login")));
94
95                         //die('This api requires login');
96                 }
97
98                 $user = $_SERVER['PHP_AUTH_USER'];
99                 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
100
101
102                 /**
103                  *  next code from mod/auth.php. needs better solution
104                  */
105
106                 // process normal login request
107
108                 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
109                         AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
110                         dbesc(trim($user)),
111                         dbesc(trim($user)),
112                         dbesc($encrypted)
113                 );
114                 if(count($r)){
115                         $record = $r[0];
116                 } else {
117                         logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
118                         header('WWW-Authenticate: Basic realm="Friendica"');
119                         header('HTTP/1.0 401 Unauthorized');
120                         die('This api requires login');
121                 }
122
123                 require_once('include/security.php');
124                 authenticate_success($record); $_SESSION["allow_api"] = true;
125
126                 call_hooks('logged_in', $a->user);
127
128         }
129
130         /**************************
131          *  MAIN API ENTRY POINT  *
132          **************************/
133         function api_call(&$a){
134                 GLOBAL $API, $called_api;
135
136                 // preset
137                 $type="json";
138                 foreach ($API as $p=>$info){
139                         if (strpos($a->query_string, $p)===0){
140                                 $called_api= explode("/",$p);
141                                 //unset($_SERVER['PHP_AUTH_USER']);
142                                 if ($info['auth']===true && api_user()===false) {
143                                                 api_login($a);
144                                 }
145
146                                 load_contact_links(api_user());
147
148                                 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
149                                 logger('API parameters: ' . print_r($_REQUEST,true));
150                                 $type="json";
151                                 if (strpos($a->query_string, ".xml")>0) $type="xml";
152                                 if (strpos($a->query_string, ".json")>0) $type="json";
153                                 if (strpos($a->query_string, ".rss")>0) $type="rss";
154                                 if (strpos($a->query_string, ".atom")>0) $type="atom";
155                                 if (strpos($a->query_string, ".as")>0) $type="as";
156
157                                 $r = call_user_func($info['func'], $a, $type);
158                                 if ($r===false) return;
159
160                                 switch($type){
161                                         case "xml":
162                                                 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
163                                                 header ("Content-Type: text/xml");
164                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
165                                                 break;
166                                         case "json":
167                                                 header ("Content-Type: application/json");
168                                                 foreach($r as $rr)
169                                                         $json = json_encode($rr);
170                                                         if ($_GET['callback'])
171                                                                 $json = $_GET['callback']."(".$json.")";
172                                                         return $json;
173                                                 break;
174                                         case "rss":
175                                                 header ("Content-Type: application/rss+xml");
176                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
177                                                 break;
178                                         case "atom":
179                                                 header ("Content-Type: application/atom+xml");
180                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
181                                                 break;
182                                         case "as":
183                                                 //header ("Content-Type: application/json");
184                                                 //foreach($r as $rr)
185                                                 //      return json_encode($rr);
186                                                 return json_encode($r);
187                                                 break;
188
189                                 }
190                                 //echo "<pre>"; var_dump($r); die();
191                         }
192                 }
193                 header("HTTP/1.1 404 Not Found");
194                 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
195                 return(api_error($a, $type, "not implemented"));
196
197         }
198
199         function api_error(&$a, $type, $error) {
200                 # TODO:  https://dev.twitter.com/overview/api/response-codes
201                 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
202                 switch($type){
203                         case "xml":
204                                 header ("Content-Type: text/xml");
205                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
206                                 break;
207                         case "json":
208                                 header ("Content-Type: application/json");
209                                 return json_encode(array('error' => $error, 'request' => $a->query_string));
210                                 break;
211                         case "rss":
212                                 header ("Content-Type: application/rss+xml");
213                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
214                                 break;
215                         case "atom":
216                                 header ("Content-Type: application/atom+xml");
217                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
218                                 break;
219                 }
220         }
221
222         /**
223          * RSS extra info
224          */
225         function api_rss_extra(&$a, $arr, $user_info){
226                 if (is_null($user_info)) $user_info = api_get_user($a);
227                 $arr['$user'] = $user_info;
228                 $arr['$rss'] = array(
229                         'alternate' => $user_info['url'],
230                         'self' => $a->get_baseurl(). "/". $a->query_string,
231                         'base' => $a->get_baseurl(),
232                         'updated' => api_date(null),
233                         'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
234                         'language' => $user_info['language'],
235                         'logo'  => $a->get_baseurl()."/images/friendica-32.png",
236                 );
237
238                 return $arr;
239         }
240
241
242         /**
243          * Unique contact to contact url.
244          */
245         function api_unique_id_to_url($id){
246                 $r = q("SELECT url FROM unique_contacts WHERE id=%d LIMIT 1",
247                         intval($id));
248                 if ($r)
249                         return ($r[0]["url"]);
250                 else
251                         return false;
252         }
253
254         /**
255          * Returns user info array.
256          */
257         function api_get_user(&$a, $contact_id = Null, $type = "json"){
258                 global $called_api;
259                 $user = null;
260                 $extra_query = "";
261                 $url = "";
262                 $nick = "";
263
264                 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
265
266                 // Searching for contact URL
267                 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
268                         $user = dbesc(normalise_link($contact_id));
269                         $url = $user;
270                         $extra_query = "AND `contact`.`nurl` = '%s' ";
271                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
272                 }
273
274                 // Searching for unique contact id
275                 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
276                         $user = dbesc(api_unique_id_to_url($contact_id));
277
278                         if ($user == "")
279                                 die(api_error($a, $type, t("User not found.")));
280
281                         $url = $user;
282                         $extra_query = "AND `contact`.`nurl` = '%s' ";
283                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
284                 }
285
286                 if(is_null($user) && x($_GET, 'user_id')) {
287                         $user = dbesc(api_unique_id_to_url($_GET['user_id']));
288
289                         if ($user == "")
290                                 die(api_error($a, $type, t("User not found.")));
291
292                         $url = $user;
293                         $extra_query = "AND `contact`.`nurl` = '%s' ";
294                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
295                 }
296                 if(is_null($user) && x($_GET, 'screen_name')) {
297                         $user = dbesc($_GET['screen_name']);
298                         $nick = $user;
299                         $extra_query = "AND `contact`.`nick` = '%s' ";
300                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
301                 }
302
303                 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
304                         $argid = count($called_api);
305                         list($user, $null) = explode(".",$a->argv[$argid]);
306                         if(is_numeric($user)){
307                                 $user = dbesc(api_unique_id_to_url($user));
308
309                                 if ($user == "")
310                                         return false;
311
312                                 $url = $user;
313                                 $extra_query = "AND `contact`.`nurl` = '%s' ";
314                                 if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
315                         } else {
316                                 $user = dbesc($user);
317                                 $nick = $user;
318                                 $extra_query = "AND `contact`.`nick` = '%s' ";
319                                 if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
320                         }
321                 }
322
323                 logger("api_get_user: user ".$user, LOGGER_DEBUG);
324
325                 if (!$user) {
326                         if (api_user()===false) {
327                                 api_login($a); return False;
328                         } else {
329                                 $user = $_SESSION['uid'];
330                                 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
331                         }
332
333                 }
334
335                 logger('api_user: ' . $extra_query . ', user: ' . $user);
336                 // user info
337                 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
338                                 WHERE 1
339                                 $extra_query",
340                                 $user
341                 );
342
343                 // Selecting the id by priority, friendica first
344                 api_best_nickname($uinfo);
345
346                 // if the contact wasn't found, fetch it from the unique contacts
347                 if (count($uinfo)==0) {
348                         $r = array();
349
350                         if ($url != "")
351                                 $r = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1", $url);
352                         elseif ($nick != "")
353                                 $r = q("SELECT * FROM unique_contacts WHERE nick='%s' LIMIT 1", $nick);
354
355                         if ($r) {
356                                 // If no nick where given, extract it from the address
357                                 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
358                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);
359
360                                 $ret = array(
361                                         'id' => $r[0]["id"],
362                                         'id_str' => (string) $r[0]["id"],
363                                         'name' => $r[0]["name"],
364                                         'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
365                                         'location' => NULL,
366                                         'description' => NULL,
367                                         'profile_image_url' => $r[0]["avatar"],
368                                         'profile_image_url_https' => $r[0]["avatar"],
369                                         'url' => $r[0]["url"],
370                                         'protected' => false,
371                                         'followers_count' => 0,
372                                         'friends_count' => 0,
373                                         'created_at' => api_date(0),
374                                         'favourites_count' => 0,
375                                         'utc_offset' => 0,
376                                         'time_zone' => 'UTC',
377                                         'statuses_count' => 0,
378                                         'following' => false,
379                                         'verified' => false,
380                                         'statusnet_blocking' => false,
381                                         'notifications' => false,
382                                         'statusnet_profile_url' => $r[0]["url"],
383                                         'uid' => 0,
384                                         'cid' => 0,
385                                         'self' => 0,
386                                         'network' => '',
387                                 );
388
389                                 return $ret;
390                         } else
391                                 die(api_error($a, $type, t("User not found.")));
392
393                 }
394
395                 if($uinfo[0]['self']) {
396                         $usr = q("select * from user where uid = %d limit 1",
397                                 intval(api_user())
398                         );
399                         $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
400                                 intval(api_user())
401                         );
402
403                         //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
404                         // count public wall messages
405                         $r = q("SELECT count(*) as `count` FROM `item`
406                                         WHERE  `uid` = %d
407                                         AND `type`='wall'",
408                                         intval($uinfo[0]['uid'])
409                         );
410                         $countitms = $r[0]['count'];
411                 }
412                 else {
413                         //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
414                         $r = q("SELECT count(*) as `count` FROM `item`
415                                         WHERE  `contact-id` = %d",
416                                         intval($uinfo[0]['id'])
417                         );
418                         $countitms = $r[0]['count'];
419                 }
420
421                 // count friends
422                 $r = q("SELECT count(*) as `count` FROM `contact`
423                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
424                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
425                                 intval($uinfo[0]['uid']),
426                                 intval(CONTACT_IS_SHARING),
427                                 intval(CONTACT_IS_FRIEND)
428                 );
429                 $countfriends = $r[0]['count'];
430
431                 $r = q("SELECT count(*) as `count` FROM `contact`
432                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
433                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
434                                 intval($uinfo[0]['uid']),
435                                 intval(CONTACT_IS_FOLLOWER),
436                                 intval(CONTACT_IS_FRIEND)
437                 );
438                 $countfollowers = $r[0]['count'];
439
440                 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
441                         intval($uinfo[0]['uid'])
442                 );
443                 $starred = $r[0]['count'];
444
445
446                 if(! $uinfo[0]['self']) {
447                         $countfriends = 0;
448                         $countfollowers = 0;
449                         $starred = 0;
450                 }
451
452                 // Add a nick if it isn't present there
453                 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
454                         $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
455                 }
456
457                 // Fetching unique id
458                 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
459
460                 // If not there, then add it
461                 if (count($r) == 0) {
462                         q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
463                                 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
464
465                         $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
466                 }
467
468                 require_once('include/contact_selectors.php');
469                 $network_name = network_to_name($uinfo[0]['network']);
470
471                 $ret = Array(
472                         'id' => intval($r[0]['id']),
473                         'id_str' => (string) intval($r[0]['id']),
474                         'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
475                         'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
476                         'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
477                         'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
478                         'profile_image_url' => $uinfo[0]['micro'],
479                         'profile_image_url_https' => $uinfo[0]['micro'],
480                         'url' => $uinfo[0]['url'],
481                         'protected' => false,
482                         'followers_count' => intval($countfollowers),
483                         'friends_count' => intval($countfriends),
484                         'created_at' => api_date($uinfo[0]['created']),
485                         'favourites_count' => intval($starred),
486                         'utc_offset' => "0",
487                         'time_zone' => 'UTC',
488                         'statuses_count' => intval($countitms),
489                         'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
490                         'verified' => true,
491                         'statusnet_blocking' => false,
492                         'notifications' => false,
493                         'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
494                         'uid' => intval($uinfo[0]['uid']),
495                         'cid' => intval($uinfo[0]['cid']),
496                         'self' => $uinfo[0]['self'],
497                         'network' => $uinfo[0]['network'],
498                 );
499
500                 return $ret;
501
502         }
503
504         function api_item_get_user(&$a, $item) {
505
506                 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
507                         dbesc(normalise_link($item['author-link'])));
508
509                 if (count($author) == 0) {
510                         q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
511                         dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
512
513                         $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
514                                 dbesc(normalise_link($item['author-link'])));
515                 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
516                         q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
517                         dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
518                 }
519
520                 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
521                         dbesc(normalise_link($item['owner-link'])));
522
523                 if (count($owner) == 0) {
524                         q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
525                         dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
526
527                         $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
528                                 dbesc(normalise_link($item['owner-link'])));
529                 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
530                         q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
531                         dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
532                 }
533
534                 // Comments in threads may appear as wall-to-wall postings.
535                 // So only take the owner at the top posting.
536                 if ($item["id"] == $item["parent"])
537                         $status_user = api_get_user($a,$item["owner-link"]);
538                 else
539                         $status_user = api_get_user($a,$item["author-link"]);
540
541                 $status_user["protected"] = (($item["allow_cid"] != "") OR
542                                                 ($item["allow_gid"] != "") OR
543                                                 ($item["deny_cid"] != "") OR
544                                                 ($item["deny_gid"] != "") OR
545                                                 $item["private"]);
546
547                 return ($status_user);
548         }
549
550
551         /**
552          *  load api $templatename for $type and replace $data array
553          */
554         function api_apply_template($templatename, $type, $data){
555
556                 $a = get_app();
557
558                 switch($type){
559                         case "atom":
560                         case "rss":
561                         case "xml":
562                                 $data = array_xmlify($data);
563                                 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
564                                 if(! $tpl) {
565                                         header ("Content-Type: text/xml");
566                                         echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
567                                         killme();
568                                 }
569                                 $ret = replace_macros($tpl, $data);
570                                 break;
571                         case "json":
572                                 $ret = $data;
573                                 break;
574                 }
575
576                 return $ret;
577         }
578
579         /**
580          ** TWITTER API
581          */
582
583         /**
584          * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
585          * returns a 401 status code and an error message if not.
586          * http://developer.twitter.com/doc/get/account/verify_credentials
587          */
588         function api_account_verify_credentials(&$a, $type){
589                 if (api_user()===false) return false;
590
591                 unset($_REQUEST["user_id"]);
592                 unset($_GET["user_id"]);
593
594                 unset($_REQUEST["screen_name"]);
595                 unset($_GET["screen_name"]);
596
597                 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
598
599                 $user_info = api_get_user($a);
600
601                 // "verified" isn't used here in the standard
602                 unset($user_info["verified"]);
603
604                 // - Adding last status
605                 if (!$skip_status) {
606                         $user_info["status"] = api_status_show($a,"raw");
607                         if (!count($user_info["status"]))
608                                 unset($user_info["status"]);
609                         else
610                                 unset($user_info["status"]["user"]);
611                 }
612
613                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
614                 unset($user_info["uid"]);
615                 unset($user_info["self"]);
616
617                 return api_apply_template("user", $type, array('$user' => $user_info));
618
619         }
620         api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
621
622
623         /**
624          * get data from $_POST or $_GET
625          */
626         function requestdata($k){
627                 if (isset($_POST[$k])){
628                         return $_POST[$k];
629                 }
630                 if (isset($_GET[$k])){
631                         return $_GET[$k];
632                 }
633                 return null;
634         }
635
636 /*Waitman Gobble Mod*/
637         function api_statuses_mediap(&$a, $type) {
638                 if (api_user()===false) {
639                         logger('api_statuses_update: no user');
640                         return false;
641                 }
642                 $user_info = api_get_user($a);
643
644                 $_REQUEST['type'] = 'wall';
645                 $_REQUEST['profile_uid'] = api_user();
646                 $_REQUEST['api_source'] = true;
647                 $txt = requestdata('status');
648                 //$txt = urldecode(requestdata('status'));
649
650                 require_once('library/HTMLPurifier.auto.php');
651                 require_once('include/html2bbcode.php');
652
653                 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
654                         $txt = html2bb_video($txt);
655                         $config = HTMLPurifier_Config::createDefault();
656                         $config->set('Cache.DefinitionImpl', null);
657                         $purifier = new HTMLPurifier($config);
658                         $txt = $purifier->purify($txt);
659                 }
660                 $txt = html2bbcode($txt);
661
662                 $a->argv[1]=$user_info['screen_name']; //should be set to username?
663
664                 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
665                 require_once('mod/wall_upload.php');
666                 $bebop = wall_upload_post($a);
667
668                 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
669                 $_REQUEST['body']=$txt."\n\n".$bebop;
670                 require_once('mod/item.php');
671                 item_post($a);
672
673                 // this should output the last post (the one we just posted).
674                 return api_status_show($a,$type);
675         }
676         api_register_func('api/statuses/mediap','api_statuses_mediap', true);
677 /*Waitman Gobble Mod*/
678
679
680         function api_statuses_update(&$a, $type) {
681                 if (api_user()===false) {
682                         logger('api_statuses_update: no user');
683                         return false;
684                 }
685
686                 $user_info = api_get_user($a);
687
688                 // convert $_POST array items to the form we use for web posts.
689
690                 // logger('api_post: ' . print_r($_POST,true));
691
692                 if(requestdata('htmlstatus')) {
693                         require_once('library/HTMLPurifier.auto.php');
694                         require_once('include/html2bbcode.php');
695
696                         $txt = requestdata('htmlstatus');
697                         if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
698
699                                 $txt = html2bb_video($txt);
700
701                                 $config = HTMLPurifier_Config::createDefault();
702                                 $config->set('Cache.DefinitionImpl', null);
703
704
705                                 $purifier = new HTMLPurifier($config);
706                                 $txt = $purifier->purify($txt);
707
708                                 $_REQUEST['body'] = html2bbcode($txt);
709                         }
710
711                 }
712                 else
713                         $_REQUEST['body'] = requestdata('status');
714
715                 $_REQUEST['title'] = requestdata('title');
716
717                 $parent = requestdata('in_reply_to_status_id');
718                 if(ctype_digit($parent))
719                         $_REQUEST['parent'] = $parent;
720                 else
721                         $_REQUEST['parent_uri'] = $parent;
722
723                 if(requestdata('lat') && requestdata('long'))
724                         $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
725                 $_REQUEST['profile_uid'] = api_user();
726
727                 if($parent)
728                         $_REQUEST['type'] = 'net-comment';
729                 else {
730                         // Check for throttling (maximum posts per day, week and month)
731                         $throttle_day = get_config('system','throttle_limit_day');
732                         if ($throttle_day > 0) {
733                                 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
734
735                                 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
736                                         AND `created` > '%s' AND `id` = `parent`",
737                                         intval(api_user()), dbesc($datefrom));
738
739                                 if ($r)
740                                         $posts_day = $r[0]["posts_day"];
741                                 else
742                                         $posts_day = 0;
743
744                                 if ($posts_day > $throttle_day) {
745                                         logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
746                                         die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
747                                 }
748                         }
749
750                         $throttle_week = get_config('system','throttle_limit_week');
751                         if ($throttle_week > 0) {
752                                 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
753
754                                 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
755                                         AND `created` > '%s' AND `id` = `parent`",
756                                         intval(api_user()), dbesc($datefrom));
757
758                                 if ($r)
759                                         $posts_week = $r[0]["posts_week"];
760                                 else
761                                         $posts_week = 0;
762
763                                 if ($posts_week > $throttle_week) {
764                                         logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
765                                         die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
766                                 }
767                         }
768
769                         $throttle_month = get_config('system','throttle_limit_month');
770                         if ($throttle_month > 0) {
771                                 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
772
773                                 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
774                                         AND `created` > '%s' AND `id` = `parent`",
775                                         intval(api_user()), dbesc($datefrom));
776
777                                 if ($r)
778                                         $posts_month = $r[0]["posts_month"];
779                                 else
780                                         $posts_month = 0;
781
782                                 if ($posts_month > $throttle_month) {
783                                         logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
784                                         die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
785                                 }
786                         }
787
788                         $_REQUEST['type'] = 'wall';
789                         if(x($_FILES,'media')) {
790                                 // upload the image if we have one
791                                 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
792                                 require_once('mod/wall_upload.php');
793                                 $media = wall_upload_post($a);
794                                 if(strlen($media)>0)
795                                         $_REQUEST['body'] .= "\n\n".$media;
796                         }
797                 }
798
799                 // set this so that the item_post() function is quiet and doesn't redirect or emit json
800
801                 $_REQUEST['api_source'] = true;
802
803                 if (!x($_REQUEST, "source"))
804                         $_REQUEST["source"] = api_source();
805
806                 // call out normal post function
807
808                 require_once('mod/item.php');
809                 item_post($a);
810
811                 // this should output the last post (the one we just posted).
812                 return api_status_show($a,$type);
813         }
814         api_register_func('api/statuses/update','api_statuses_update', true);
815         api_register_func('api/statuses/update_with_media','api_statuses_update', true);
816
817
818         function api_status_show(&$a, $type){
819                 $user_info = api_get_user($a);
820
821                 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
822
823                 // get last public wall message
824                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
825                                 FROM `item`, `item` as `i`
826                                 WHERE `item`.`contact-id` = %d
827                                         AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
828                                         AND `i`.`id` = `item`.`parent`
829                                         AND `item`.`type`!='activity'
830                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
831                                 ORDER BY `item`.`created` DESC
832                                 LIMIT 1",
833                                 intval($user_info['cid']),
834                                 dbesc($user_info['url']),
835                                 dbesc(normalise_link($user_info['url'])),
836                                 dbesc($user_info['url']),
837                                 dbesc(normalise_link($user_info['url']))
838                 );
839
840                 if (count($lastwall)>0){
841                         $lastwall = $lastwall[0];
842
843                         $in_reply_to_status_id = NULL;
844                         $in_reply_to_user_id = NULL;
845                         $in_reply_to_status_id_str = NULL;
846                         $in_reply_to_user_id_str = NULL;
847                         $in_reply_to_screen_name = NULL;
848                         if (intval($lastwall['parent']) != intval($lastwall['id'])) {
849                                 $in_reply_to_status_id= intval($lastwall['parent']);
850                                 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
851
852                                 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
853                                 if ($r) {
854                                         if ($r[0]['nick'] == "")
855                                                 $r[0]['nick'] = api_get_nick($r[0]["url"]);
856
857                                         $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
858                                         $in_reply_to_user_id = intval($r[0]['id']);
859                                         $in_reply_to_user_id_str = (string) intval($r[0]['id']);
860                                 }
861                         }
862
863                         // There seems to be situation, where both fields are identical:
864                         // https://github.com/friendica/friendica/issues/1010
865                         // This is a bugfix for that.
866                         if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
867                                 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
868                                 $in_reply_to_status_id = NULL;
869                                 $in_reply_to_user_id = NULL;
870                                 $in_reply_to_status_id_str = NULL;
871                                 $in_reply_to_user_id_str = NULL;
872                                 $in_reply_to_screen_name = NULL;
873                         }
874
875                         $converted = api_convert_item($item);
876
877                         $status_info = array(
878                                 'text' => $converted["text"],
879                                 'truncated' => false,
880                                 'created_at' => api_date($lastwall['created']),
881                                 'in_reply_to_status_id' => $in_reply_to_status_id,
882                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
883                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
884                                 'id' => intval($lastwall['id']),
885                                 'id_str' => (string) $lastwall['id'],
886                                 'in_reply_to_user_id' => $in_reply_to_user_id,
887                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
888                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
889                                 'geo' => NULL,
890                                 'favorited' => $lastwall['starred'] ? true : false,
891                                 'user' => $user_info,
892                                 'statusnet_html'                => $converted["html"],
893                                 'statusnet_conversation_id'     => $lastwall['parent'],
894                         );
895
896                         if (count($converted["attachments"]) > 0)
897                                 $status_info["attachments"] = $converted["attachments"];
898
899                         if (count($converted["entities"]) > 0)
900                                 $status_info["entities"] = $converted["entities"];
901
902                         if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
903                                 $status_info["source"] = network_to_name($lastwall['item_network']);
904                         elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
905                                 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
906
907                         // "uid" and "self" are only needed for some internal stuff, so remove it from here
908                         unset($status_info["user"]["uid"]);
909                         unset($status_info["user"]["self"]);
910                 }
911
912                 if ($type == "raw")
913                         return($status_info);
914
915                 return  api_apply_template("status", $type, array('$status' => $status_info));
916
917         }
918
919
920
921
922
923         /**
924          * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
925          * The author's most recent status will be returned inline.
926          * http://developer.twitter.com/doc/get/users/show
927          */
928         function api_users_show(&$a, $type){
929                 $user_info = api_get_user($a);
930
931                 $lastwall = q("SELECT `item`.*
932                                 FROM `item`, `contact`
933                                 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
934                                         AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
935                                         AND `contact`.`id`=`item`.`contact-id`
936                                         AND `type`!='activity'
937                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
938                                 ORDER BY `created` DESC
939                                 LIMIT 1",
940                                 intval(api_user()),
941                                 dbesc(ACTIVITY_POST),
942                                 intval($user_info['cid']),
943                                 dbesc($user_info['url']),
944                                 dbesc(normalise_link($user_info['url'])),
945                                 dbesc($user_info['url']),
946                                 dbesc(normalise_link($user_info['url']))
947                 );
948                 if (count($lastwall)>0){
949                         $lastwall = $lastwall[0];
950
951                         $in_reply_to_status_id = NULL;
952                         $in_reply_to_user_id = NULL;
953                         $in_reply_to_status_id_str = NULL;
954                         $in_reply_to_user_id_str = NULL;
955                         $in_reply_to_screen_name = NULL;
956                         if ($lastwall['parent']!=$lastwall['id']) {
957                                 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
958                                                 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
959                                 if (count($reply)>0) {
960                                         $in_reply_to_status_id = intval($lastwall['parent']);
961                                         $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
962
963                                         $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
964                                         if ($r) {
965                                                 if ($r[0]['nick'] == "")
966                                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);
967
968                                                 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
969                                                 $in_reply_to_user_id = intval($r[0]['id']);
970                                                 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
971                                         }
972                                 }
973                         }
974
975                         $converted = api_convert_item($item);
976
977                         $user_info['status'] = array(
978                                 'text' => $converted["text"],
979                                 'truncated' => false,
980                                 'created_at' => api_date($lastwall['created']),
981                                 'in_reply_to_status_id' => $in_reply_to_status_id,
982                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
983                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
984                                 'id' => intval($lastwall['contact-id']),
985                                 'id_str' => (string) $lastwall['contact-id'],
986                                 'in_reply_to_user_id' => $in_reply_to_user_id,
987                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
988                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
989                                 'geo' => NULL,
990                                 'favorited' => $lastwall['starred'] ? true : false,
991                                 'statusnet_html'                => $converted["html"],
992                                 'statusnet_conversation_id'     => $lastwall['parent'],
993                         );
994
995                         if (count($converted["attachments"]) > 0)
996                                 $user_info["status"]["attachments"] = $converted["attachments"];
997
998                         if (count($converted["entities"]) > 0)
999                                 $user_info["status"]["entities"] = $converted["entities"];
1000
1001                         if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1002                                 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
1003                         if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
1004                                 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
1005
1006                 }
1007
1008                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1009                 unset($user_info["uid"]);
1010                 unset($user_info["self"]);
1011
1012                 return  api_apply_template("user", $type, array('$user' => $user_info));
1013
1014         }
1015         api_register_func('api/users/show','api_users_show');
1016
1017
1018         function api_users_search(&$a, $type) {
1019                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1020
1021                 $userlist = array();
1022
1023                 if (isset($_GET["q"])) {
1024                         $r = q("SELECT id FROM unique_contacts WHERE name='%s'", dbesc($_GET["q"]));
1025                         if (!count($r))
1026                                 $r = q("SELECT id FROM unique_contacts WHERE nick='%s'", dbesc($_GET["q"]));
1027
1028                         if (count($r)) {
1029                                 foreach ($r AS $user) {
1030                                         $user_info = api_get_user($a, $user["id"]);
1031                                         //echo print_r($user_info, true)."\n";
1032                                         $userdata = api_apply_template("user", $type, array('user' => $user_info));
1033                                         $userlist[] = $userdata["user"];
1034                                 }
1035                                 $userlist = array("users" => $userlist);
1036                         } else
1037                                 die(api_error($a, $type, t("User not found.")));
1038                 } else
1039                         die(api_error($a, $type, t("User not found.")));
1040
1041                 return ($userlist);
1042         }
1043
1044         api_register_func('api/users/search','api_users_search');
1045
1046         /**
1047          *
1048          * http://developer.twitter.com/doc/get/statuses/home_timeline
1049          *
1050          * TODO: Optional parameters
1051          * TODO: Add reply info
1052          */
1053         function api_statuses_home_timeline(&$a, $type){
1054                 if (api_user()===false) return false;
1055
1056                 unset($_REQUEST["user_id"]);
1057                 unset($_GET["user_id"]);
1058
1059                 unset($_REQUEST["screen_name"]);
1060                 unset($_GET["screen_name"]);
1061
1062                 $user_info = api_get_user($a);
1063                 // get last newtork messages
1064
1065
1066                 // params
1067                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1068                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1069                 if ($page<0) $page=0;
1070                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1071                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1072                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1073                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1074                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1075
1076                 $start = $page*$count;
1077
1078                 $sql_extra = '';
1079                 if ($max_id > 0)
1080                         $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1081                 if ($exclude_replies > 0)
1082                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1083                 if ($conversation_id > 0)
1084                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1085
1086                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1087                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1088                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1089                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1090                         FROM `item`, `contact`
1091                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1092                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1093                         AND `contact`.`id` = `item`.`contact-id`
1094                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1095                         $sql_extra
1096                         AND `item`.`id`>%d
1097                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1098                         intval(api_user()),
1099                         dbesc(ACTIVITY_POST),
1100                         intval($since_id),
1101                         intval($start), intval($count)
1102                 );
1103
1104                 $ret = api_format_items($r,$user_info);
1105
1106                 // We aren't going to try to figure out at the item, group, and page
1107                 // level which items you've seen and which you haven't. If you're looking
1108                 // at the network timeline just mark everything seen.
1109
1110                 $r = q("UPDATE `item` SET `unseen` = 0
1111                         WHERE `unseen` = 1 AND `uid` = %d",
1112                         //intval($user_info['uid'])
1113                         intval(api_user())
1114                 );
1115
1116
1117                 $data = array('$statuses' => $ret);
1118                 switch($type){
1119                         case "atom":
1120                         case "rss":
1121                                 $data = api_rss_extra($a, $data, $user_info);
1122                                 break;
1123                         case "as":
1124                                 $as = api_format_as($a, $ret, $user_info);
1125                                 $as['title'] = $a->config['sitename']." Home Timeline";
1126                                 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1127                                 return($as);
1128                                 break;
1129                 }
1130
1131                 return  api_apply_template("timeline", $type, $data);
1132         }
1133         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1134         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1135
1136         function api_statuses_public_timeline(&$a, $type){
1137                 if (api_user()===false) return false;
1138
1139                 $user_info = api_get_user($a);
1140                 // get last newtork messages
1141
1142
1143                 // params
1144                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1145                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1146                 if ($page<0) $page=0;
1147                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1148                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1149                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1150                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1151                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1152
1153                 $start = $page*$count;
1154
1155                 if ($max_id > 0)
1156                         $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1157                 if ($exclude_replies > 0)
1158                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1159                 if ($conversation_id > 0)
1160                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1161
1162                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1163                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1164                         `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1165                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1166                         `user`.`nickname`, `user`.`hidewall`
1167                         FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1168                         STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1169                         WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1170                         AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
1171                         AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
1172                         AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1173                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1174                         $sql_extra
1175                         AND `item`.`id`>%d
1176                         ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1177                         dbesc(ACTIVITY_POST),
1178                         intval($since_id),
1179                         intval($start),
1180                         intval($count));
1181
1182                 $ret = api_format_items($r,$user_info);
1183
1184
1185                 $data = array('$statuses' => $ret);
1186                 switch($type){
1187                         case "atom":
1188                         case "rss":
1189                                 $data = api_rss_extra($a, $data, $user_info);
1190                                 break;
1191                         case "as":
1192                                 $as = api_format_as($a, $ret, $user_info);
1193                                 $as['title'] = $a->config['sitename']." Public Timeline";
1194                                 $as['link']['url'] = $a->get_baseurl()."/";
1195                                 return($as);
1196                                 break;
1197                 }
1198
1199                 return  api_apply_template("timeline", $type, $data);
1200         }
1201         api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1202
1203         /**
1204          *
1205          */
1206         function api_statuses_show(&$a, $type){
1207                 if (api_user()===false) return false;
1208
1209                 $user_info = api_get_user($a);
1210
1211                 // params
1212                 $id = intval($a->argv[3]);
1213
1214                 if ($id == 0)
1215                         $id = intval($_REQUEST["id"]);
1216
1217                 // Hotot workaround
1218                 if ($id == 0)
1219                         $id = intval($a->argv[4]);
1220
1221                 logger('API: api_statuses_show: '.$id);
1222
1223                 $conversation = (x($_REQUEST,'conversation')?1:0);
1224
1225                 $sql_extra = '';
1226                 if ($conversation)
1227                         $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1228                 else
1229                         $sql_extra .= " AND `item`.`id` = %d";
1230
1231                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1232                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1233                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1234                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1235                         FROM `item`, `contact`
1236                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1237                         AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1238                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1239                         $sql_extra",
1240                         intval(api_user()),
1241                         dbesc(ACTIVITY_POST),
1242                         intval($id)
1243                 );
1244
1245                 if (!$r)
1246                         die(api_error($a, $type, t("There is no status with this id.")));
1247
1248                 $ret = api_format_items($r,$user_info);
1249
1250                 if ($conversation) {
1251                         $data = array('$statuses' => $ret);
1252                         return api_apply_template("timeline", $type, $data);
1253                 } else {
1254                         $data = array('$status' => $ret[0]);
1255                         /*switch($type){
1256                                 case "atom":
1257                                 case "rss":
1258                                         $data = api_rss_extra($a, $data, $user_info);
1259                         }*/
1260                         return  api_apply_template("status", $type, $data);
1261                 }
1262         }
1263         api_register_func('api/statuses/show','api_statuses_show', true);
1264
1265
1266         /**
1267          *
1268          */
1269         function api_conversation_show(&$a, $type){
1270                 if (api_user()===false) return false;
1271
1272                 $user_info = api_get_user($a);
1273
1274                 // params
1275                 $id = intval($a->argv[3]);
1276                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1277                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1278                 if ($page<0) $page=0;
1279                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1280                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1281
1282                 $start = $page*$count;
1283
1284                 if ($id == 0)
1285                         $id = intval($_REQUEST["id"]);
1286
1287                 // Hotot workaround
1288                 if ($id == 0)
1289                         $id = intval($a->argv[4]);
1290
1291                 logger('API: api_conversation_show: '.$id);
1292
1293                 $sql_extra = '';
1294
1295                 if ($max_id > 0)
1296                         $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1297
1298                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1299                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1300                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1301                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1302                         FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1303                         ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1304                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1305                         AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1306                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1307                         AND `item`.`id`>%d $sql_extra
1308                         ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1309                         intval($id), intval(api_user()),
1310                         dbesc(ACTIVITY_POST),
1311                         intval($since_id),
1312                         intval($start), intval($count)
1313                 );
1314
1315                 if (!$r)
1316                         die(api_error($a, $type, t("There is no conversation with this id.")));
1317
1318                 $ret = api_format_items($r,$user_info);
1319
1320                 $data = array('$statuses' => $ret);
1321                 return api_apply_template("timeline", $type, $data);
1322         }
1323         api_register_func('api/conversation/show','api_conversation_show', true);
1324
1325
1326         /**
1327          *
1328          */
1329         function api_statuses_repeat(&$a, $type){
1330                 global $called_api;
1331
1332                 if (api_user()===false) return false;
1333
1334                 $user_info = api_get_user($a);
1335
1336                 // params
1337                 $id = intval($a->argv[3]);
1338
1339                 if ($id == 0)
1340                         $id = intval($_REQUEST["id"]);
1341
1342                 // Hotot workaround
1343                 if ($id == 0)
1344                         $id = intval($a->argv[4]);
1345
1346                 logger('API: api_statuses_repeat: '.$id);
1347
1348                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1349                         `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1350                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1351                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1352                         FROM `item`, `contact`
1353                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1354                         AND `contact`.`id` = `item`.`contact-id`
1355                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1356                         $sql_extra
1357                         AND `item`.`id`=%d",
1358                         intval($id)
1359                 );
1360
1361                 if ($r[0]['body'] != "") {
1362                         if (!intval(get_config('system','old_share'))) {
1363                                 if (strpos($r[0]['body'], "[/share]") !== false) {
1364                                         $pos = strpos($r[0]['body'], "[share");
1365                                         $post = substr($r[0]['body'], $pos);
1366                                 } else {
1367                                         $post = "[share author='".str_replace("'", "&#039;", $r[0]['author-name']).
1368                                                         "' profile='".$r[0]['author-link'].
1369                                                         "' avatar='".$r[0]['author-avatar'].
1370                                                         "' link='".$r[0]['plink']."']";
1371                                         $post .= $r[0]['body'];
1372                                         $post .= "[/share]";
1373                                 }
1374                                 $_REQUEST['body'] = $post;
1375                         } else
1376                                 $_REQUEST['body'] = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1377
1378                         $_REQUEST['profile_uid'] = api_user();
1379                         $_REQUEST['type'] = 'wall';
1380                         $_REQUEST['api_source'] = true;
1381
1382                         if (!x($_REQUEST, "source"))
1383                                 $_REQUEST["source"] = api_source();
1384
1385                         require_once('mod/item.php');
1386                         item_post($a);
1387                 }
1388
1389                 // this should output the last post (the one we just posted).
1390                 $called_api = null;
1391                 return(api_status_show($a,$type));
1392         }
1393         api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1394
1395         /**
1396          *
1397          */
1398         function api_statuses_destroy(&$a, $type){
1399                 if (api_user()===false) return false;
1400
1401                 $user_info = api_get_user($a);
1402
1403                 // params
1404                 $id = intval($a->argv[3]);
1405
1406                 if ($id == 0)
1407                         $id = intval($_REQUEST["id"]);
1408
1409                 // Hotot workaround
1410                 if ($id == 0)
1411                         $id = intval($a->argv[4]);
1412
1413                 logger('API: api_statuses_destroy: '.$id);
1414
1415                 $ret = api_statuses_show($a, $type);
1416
1417                 require_once('include/items.php');
1418                 drop_item($id, false);
1419
1420                 return($ret);
1421         }
1422         api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1423
1424         /**
1425          *
1426          * http://developer.twitter.com/doc/get/statuses/mentions
1427          *
1428          */
1429         function api_statuses_mentions(&$a, $type){
1430                 if (api_user()===false) return false;
1431
1432                 unset($_REQUEST["user_id"]);
1433                 unset($_GET["user_id"]);
1434
1435                 unset($_REQUEST["screen_name"]);
1436                 unset($_GET["screen_name"]);
1437
1438                 $user_info = api_get_user($a);
1439                 // get last newtork messages
1440
1441
1442                 // params
1443                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1444                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1445                 if ($page<0) $page=0;
1446                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1447                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1448                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1449
1450                 $start = $page*$count;
1451
1452                 // Ugly code - should be changed
1453                 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1454                 $myurl = substr($myurl,strpos($myurl,'://')+3);
1455                 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1456                 $myurl = str_replace('www.','',$myurl);
1457                 $diasp_url = str_replace('/profile/','/u/',$myurl);
1458
1459                 if ($max_id > 0)
1460                         $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1461
1462                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1463                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1464                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1465                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1466                         FROM `item`, `contact`
1467                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1468                         AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1469                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1470                         AND `contact`.`id` = `item`.`contact-id`
1471                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1472                         AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1473                         $sql_extra
1474                         AND `item`.`id`>%d
1475                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1476                         intval(api_user()),
1477                         dbesc(ACTIVITY_POST),
1478                         dbesc(protect_sprintf($myurl)),
1479                         dbesc(protect_sprintf($myurl)),
1480                         intval(api_user()),
1481                         intval($since_id),
1482                         intval($start), intval($count)
1483                 );
1484
1485                 $ret = api_format_items($r,$user_info);
1486
1487
1488                 $data = array('$statuses' => $ret);
1489                 switch($type){
1490                         case "atom":
1491                         case "rss":
1492                                 $data = api_rss_extra($a, $data, $user_info);
1493                                 break;
1494                         case "as":
1495                                 $as = api_format_as($a, $ret, $user_info);
1496                                 $as["title"] = $a->config['sitename']." Mentions";
1497                                 $as['link']['url'] = $a->get_baseurl()."/";
1498                                 return($as);
1499                                 break;
1500                 }
1501
1502                 return  api_apply_template("timeline", $type, $data);
1503         }
1504         api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1505         api_register_func('api/statuses/replies','api_statuses_mentions', true);
1506
1507
1508         function api_statuses_user_timeline(&$a, $type){
1509                 if (api_user()===false) return false;
1510
1511                 $user_info = api_get_user($a);
1512                 // get last network messages
1513
1514                 logger("api_statuses_user_timeline: api_user: ". api_user() .
1515                            "\nuser_info: ".print_r($user_info, true) .
1516                            "\n_REQUEST:  ".print_r($_REQUEST, true),
1517                            LOGGER_DEBUG);
1518
1519                 // params
1520                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1521                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1522                 if ($page<0) $page=0;
1523                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1524                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1525                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1526                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1527
1528                 $start = $page*$count;
1529
1530                 $sql_extra = '';
1531                 if ($user_info['self']==1)
1532                         $sql_extra .= " AND `item`.`wall` = 1 ";
1533
1534                 if ($exclude_replies > 0)
1535                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1536                 if ($conversation_id > 0)
1537                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1538
1539                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1540                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1541                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1542                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1543                         FROM `item`, `contact`
1544                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1545                         AND `item`.`contact-id` = %d
1546                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1547                         AND `contact`.`id` = `item`.`contact-id`
1548                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1549                         $sql_extra
1550                         AND `item`.`id`>%d
1551                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1552                         intval(api_user()),
1553                         dbesc(ACTIVITY_POST),
1554                         intval($user_info['cid']),
1555                         intval($since_id),
1556                         intval($start), intval($count)
1557                 );
1558
1559                 $ret = api_format_items($r,$user_info, true);
1560
1561                 $data = array('$statuses' => $ret);
1562                 switch($type){
1563                         case "atom":
1564                         case "rss":
1565                                 $data = api_rss_extra($a, $data, $user_info);
1566                 }
1567
1568                 return  api_apply_template("timeline", $type, $data);
1569         }
1570
1571         api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1572
1573
1574         /**
1575          * Star/unstar an item
1576          * param: id : id of the item
1577          *
1578          * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1579          */
1580         function api_favorites_create_destroy(&$a, $type){
1581                 if (api_user()===false) return false;
1582
1583                 # for versioned api.
1584                 # TODO: we need a better global soluton
1585                 $action_argv_id=2;
1586                 if ($a->argv[1]=="1.1") $action_argv_id=3;
1587
1588                 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1589                 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1590                 if ($a->argc==$action_argv_id+2) {
1591                         $itemid = intval($a->argv[$action_argv_id+1]);
1592                 } else {
1593                         $itemid = intval($_REQUEST['id']);
1594                 }
1595                 if ($action!="create" && $action!="destroy") die(api_error($a, $type, t("Invalid action. ".$action)));
1596
1597                 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1598                                 $itemid, api_user());
1599
1600                 if ($item===false || count($item)==0) die(api_error($a, $type, t("Invalid item.")));
1601
1602                 switch($action){
1603                         case "create":
1604                                 $r = q("UPDATE item SET starred=1 WHERE id=%d AND uid=%d",
1605                                                 $itemid, api_user());
1606                                 $item[0]['starred']=1;
1607                                 break;
1608                         case "destroy":
1609                                 $r = q("UPDATE item SET starred=0 WHERE id=%d AND uid=%d",
1610                                                 $itemid, api_user());
1611                                 $item[0]['starred']=0;
1612                                 break;
1613                 }
1614
1615                 if ($r===false) die(api_error($a, $type, t("DB error")));
1616
1617
1618                 $user_info = api_get_user($a);
1619                 $ret = api_format_items($item,$user_info)[0];
1620
1621                 $data = array('$status' => $ret);
1622                 switch($type){
1623                         case "atom":
1624                         case "rss":
1625                                 $data = api_rss_extra($a, $data, $user_info);
1626                 }
1627
1628                 return  api_apply_template("status", $type, $data);
1629         }
1630
1631         api_register_func('api/favorites/create', 'api_favorites_create_destroy', true);
1632         api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true);
1633
1634         function api_favorites(&$a, $type){
1635                 global $called_api;
1636
1637                 if (api_user()===false) return false;
1638
1639                 $called_api= array();
1640
1641                 $user_info = api_get_user($a);
1642
1643                 // in friendica starred item are private
1644                 // return favorites only for self
1645                 logger('api_favorites: self:' . $user_info['self']);
1646
1647                 if ($user_info['self']==0) {
1648                         $ret = array();
1649                 } else {
1650                         $sql_extra = "";
1651
1652                         // params
1653                         $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1654                         $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1655                         $count = (x($_GET,'count')?$_GET['count']:20);
1656                         $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1657                         if ($page<0) $page=0;
1658
1659                         $start = $page*$count;
1660
1661                         if ($max_id > 0)
1662                                 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1663
1664                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1665                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1666                                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1667                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1668                                 FROM `item`, `contact`
1669                                 WHERE `item`.`uid` = %d
1670                                 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1671                                 AND `item`.`starred` = 1
1672                                 AND `contact`.`id` = `item`.`contact-id`
1673                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1674                                 $sql_extra
1675                                 AND `item`.`id`>%d
1676                                 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1677                                 intval(api_user()),
1678                                 intval($since_id),
1679                                 intval($start), intval($count)
1680                         );
1681
1682                         $ret = api_format_items($r,$user_info);
1683
1684                 }
1685
1686                 $data = array('$statuses' => $ret);
1687                 switch($type){
1688                         case "atom":
1689                         case "rss":
1690                                 $data = api_rss_extra($a, $data, $user_info);
1691                 }
1692
1693                 return  api_apply_template("timeline", $type, $data);
1694         }
1695
1696         api_register_func('api/favorites','api_favorites', true);
1697
1698
1699
1700
1701         function api_format_as($a, $ret, $user_info) {
1702
1703                 $as = array();
1704                 $as['title'] = $a->config['sitename']." Public Timeline";
1705                 $items = array();
1706                 foreach ($ret as $item) {
1707                         $singleitem["actor"]["displayName"] = $item["user"]["name"];
1708                         $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1709                         $avatar[0]["url"] = $item["user"]["profile_image_url"];
1710                         $avatar[0]["rel"] = "avatar";
1711                         $avatar[0]["type"] = "";
1712                         $avatar[0]["width"] = 96;
1713                         $avatar[0]["height"] = 96;
1714                         $avatar[1]["url"] = $item["user"]["profile_image_url"];
1715                         $avatar[1]["rel"] = "avatar";
1716                         $avatar[1]["type"] = "";
1717                         $avatar[1]["width"] = 48;
1718                         $avatar[1]["height"] = 48;
1719                         $avatar[2]["url"] = $item["user"]["profile_image_url"];
1720                         $avatar[2]["rel"] = "avatar";
1721                         $avatar[2]["type"] = "";
1722                         $avatar[2]["width"] = 24;
1723                         $avatar[2]["height"] = 24;
1724                         $singleitem["actor"]["avatarLinks"] = $avatar;
1725
1726                         $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1727                         $singleitem["actor"]["image"]["rel"] = "avatar";
1728                         $singleitem["actor"]["image"]["type"] = "";
1729                         $singleitem["actor"]["image"]["width"] = 96;
1730                         $singleitem["actor"]["image"]["height"] = 96;
1731                         $singleitem["actor"]["type"] = "person";
1732                         $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1733                         $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1734                         $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1735                         $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1736                         $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1737                         $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1738                         $singleitem["actor"]["contact"]["addresses"] = "";
1739
1740                         $singleitem["body"] = $item["text"];
1741                         $singleitem["object"]["displayName"] = $item["text"];
1742                         $singleitem["object"]["id"] = $item["url"];
1743                         $singleitem["object"]["type"] = "note";
1744                         $singleitem["object"]["url"] = $item["url"];
1745                         //$singleitem["context"] =;
1746                         $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1747                         $singleitem["provider"]["objectType"] = "service";
1748                         $singleitem["provider"]["displayName"] = "Test";
1749                         $singleitem["provider"]["url"] = "http://test.tld";
1750                         $singleitem["title"] = $item["text"];
1751                         $singleitem["verb"] = "post";
1752                         $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1753                         $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1754                         $singleitem["statusnet:notice_info"]["favorite"] = "false";
1755                         $singleitem["statusnet:notice_info"]["repeated"] = "false";
1756                         //$singleitem["original"] = $item;
1757                         $items[] = $singleitem;
1758                 }
1759                 $as['items'] = $items;
1760                 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1761                 $as['link']['rel'] = "alternate";
1762                 $as['link']['type'] = "text/html";
1763                 return($as);
1764         }
1765
1766         function api_format_messages($item, $recipient, $sender) {
1767                 // standard meta information
1768                 $ret=Array(
1769                                 'id'                    => $item['id'],
1770                                 'sender_id'             => $sender['id'] ,
1771                                 'text'                  => "",
1772                                 'recipient_id'          => $recipient['id'],
1773                                 'created_at'            => api_date($item['created']),
1774                                 'sender_screen_name'    => $sender['screen_name'],
1775                                 'recipient_screen_name' => $recipient['screen_name'],
1776                                 'sender'                => $sender,
1777                                 'recipient'             => $recipient,
1778                 );
1779
1780                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1781                 unset($ret["sender"]["uid"]);
1782                 unset($ret["sender"]["self"]);
1783                 unset($ret["recipient"]["uid"]);
1784                 unset($ret["recipient"]["self"]);
1785
1786                 //don't send title to regular StatusNET requests to avoid confusing these apps
1787                 if (x($_GET, 'getText')) {
1788                         $ret['title'] = $item['title'] ;
1789                         if ($_GET["getText"] == "html") {
1790                                 $ret['text'] = bbcode($item['body'], false, false);
1791                         }
1792                         elseif ($_GET["getText"] == "plain") {
1793                                 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1794                                 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1795                         }
1796                 }
1797                 else {
1798                         $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1799                 }
1800                 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1801                         unset($ret['sender']);
1802                         unset($ret['recipient']);
1803                 }
1804
1805                 return $ret;
1806         }
1807
1808         function api_convert_item($item) {
1809
1810                 $body = $item['body'];
1811                 $attachments = api_get_attachments($body);
1812
1813                 // Workaround for ostatus messages where the title is identically to the body
1814                 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
1815                 $statusbody = trim(html2plain($html, 0));
1816
1817                 // handle data: images
1818                 $statusbody = api_format_items_embeded_images($item,$statusbody);
1819
1820                 $statustitle = trim($item['title']);
1821
1822                 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1823                         $statustext = trim($statusbody);
1824                 else
1825                         $statustext = trim($statustitle."\n\n".$statusbody);
1826
1827                 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1828                         $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1829
1830                 $statushtml = trim(bbcode($body, false, false));
1831
1832                 if ($item['title'] != "")
1833                         $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
1834
1835                 $entities = api_get_entitities($statustext, $body);
1836
1837                 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
1838         }
1839
1840         function api_get_attachments(&$body) {
1841
1842                 $text = $body;
1843                 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1844
1845                 $URLSearchString = "^\[\]";
1846                 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
1847
1848                 if (!$ret)
1849                         return false;
1850
1851                 require_once("include/Photo.php");
1852
1853                 $attachments = array();
1854
1855                 foreach ($images[1] AS $image) {
1856                         $imagedata = get_photo_info($image);
1857
1858                         if ($imagedata)
1859                                 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
1860                 }
1861
1862                 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
1863                         foreach ($images[0] AS $orig)
1864                                 $body = str_replace($orig, "", $body);
1865
1866                 return $attachments;
1867         }
1868
1869         function api_get_entitities(&$text, $bbcode) {
1870                 /*
1871                 To-Do:
1872                 * Links at the first character of the post
1873                 */
1874
1875                 $a = get_app();
1876
1877                 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1878
1879                 if ($include_entities != "true") {
1880                         require_once("mod/proxy.php");
1881
1882                         preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1883
1884                         foreach ($images[1] AS $image) {
1885                                 $replace = proxy_url($image);
1886                                 $text = str_replace($image, $replace, $text);
1887                         }
1888                         return array();
1889                 }
1890
1891                 $bbcode = bb_CleanPictureLinks($bbcode);
1892
1893                 // Change pure links in text to bbcode uris
1894                 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1895
1896                 $entities = array();
1897                 $entities["hashtags"] = array();
1898                 $entities["symbols"] = array();
1899                 $entities["urls"] = array();
1900                 $entities["user_mentions"] = array();
1901
1902                 $URLSearchString = "^\[\]";
1903
1904                 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
1905
1906                 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
1907                 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
1908                 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
1909
1910                 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1911                                         '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
1912                 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
1913
1914                 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1915                                         '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
1916                 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
1917
1918                 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1919
1920                 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
1921                 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
1922
1923                 $ordered_urls = array();
1924                 foreach ($urls[1] AS $id=>$url) {
1925                         //$start = strpos($text, $url, $offset);
1926                         $start = iconv_strpos($text, $url, 0, "UTF-8");
1927                         if (!($start === false))
1928                                 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
1929                 }
1930
1931                 ksort($ordered_urls);
1932
1933                 $offset = 0;
1934                 //foreach ($urls[1] AS $id=>$url) {
1935                 foreach ($ordered_urls AS $url) {
1936                         if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
1937                                 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
1938                                 $display_url = $url["title"];
1939                         else {
1940                                 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
1941                                 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1942
1943                                 if (strlen($display_url) > 26)
1944                                         $display_url = substr($display_url, 0, 25)."…";
1945                         }
1946
1947                         //$start = strpos($text, $url, $offset);
1948                         $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
1949                         if (!($start === false)) {
1950                                 $entities["urls"][] = array("url" => $url["url"],
1951                                                                 "expanded_url" => $url["url"],
1952                                                                 "display_url" => $display_url,
1953                                                                 "indices" => array($start, $start+strlen($url["url"])));
1954                                 $offset = $start + 1;
1955                         }
1956                 }
1957
1958                 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1959                 $ordered_images = array();
1960                 foreach ($images[1] AS $image) {
1961                         //$start = strpos($text, $url, $offset);
1962                         $start = iconv_strpos($text, $image, 0, "UTF-8");
1963                         if (!($start === false))
1964                                 $ordered_images[$start] = $image;
1965                 }
1966                 //$entities["media"] = array();
1967                 $offset = 0;
1968
1969                 foreach ($ordered_images AS $url) {
1970                         $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
1971                         $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1972
1973                         if (strlen($display_url) > 26)
1974                                 $display_url = substr($display_url, 0, 25)."…";
1975
1976                         $start = iconv_strpos($text, $url, $offset, "UTF-8");
1977                         if (!($start === false)) {
1978                                 require_once("include/Photo.php");
1979                                 $image = get_photo_info($url);
1980                                 if ($image) {
1981                                         // If image cache is activated, then use the following sizes:
1982                                         // thumb  (150), small (340), medium (600) and large (1024)
1983                                         if (!get_config("system", "proxy_disabled")) {
1984                                                 require_once("mod/proxy.php");
1985                                                 $media_url = proxy_url($url);
1986
1987                                                 $sizes = array();
1988                                                 $scale = scale_image($image[0], $image[1], 150);
1989                                                 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1990
1991                                                 if (($image[0] > 150) OR ($image[1] > 150)) {
1992                                                         $scale = scale_image($image[0], $image[1], 340);
1993                                                         $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1994                                                 }
1995
1996                                                 $scale = scale_image($image[0], $image[1], 600);
1997                                                 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1998
1999                                                 if (($image[0] > 600) OR ($image[1] > 600)) {
2000                                                         $scale = scale_image($image[0], $image[1], 1024);
2001                                                         $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2002                                                 }
2003                                         } else {
2004                                                 $media_url = $url;
2005                                                 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2006                                         }
2007
2008                                         $entities["media"][] = array(
2009                                                                 "id" => $start+1,
2010                                                                 "id_str" => (string)$start+1,
2011                                                                 "indices" => array($start, $start+strlen($url)),
2012                                                                 "media_url" => normalise_link($media_url),
2013                                                                 "media_url_https" => $media_url,
2014                                                                 "url" => $url,
2015                                                                 "display_url" => $display_url,
2016                                                                 "expanded_url" => $url,
2017                                                                 "type" => "photo",
2018                                                                 "sizes" => $sizes);
2019                                 }
2020                                 $offset = $start + 1;
2021                         }
2022                 }
2023
2024                 return($entities);
2025         }
2026         function api_format_items_embeded_images($item, $text){
2027                 $a = get_app();
2028                 $text = preg_replace_callback(
2029                                 "|data:image/([^;]+)[^=]+=*|m",
2030                                 function($match) use ($a, $item) {
2031                                         return $a->get_baseurl()."/display/".$item['guid'];
2032                                 },
2033                                 $text);
2034                 return $text;
2035         }
2036
2037         function api_format_items($r,$user_info, $filter_user = false) {
2038
2039                 $a = get_app();
2040                 $ret = Array();
2041
2042                 foreach($r as $item) {
2043                         api_share_as_retweet($a, api_user(), $item);
2044
2045                         localize_item($item);
2046                         $status_user = api_item_get_user($a,$item);
2047
2048                         // Look if the posts are matching if they should be filtered by user id
2049                         if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2050                                 continue;
2051
2052                         if ($item['thr-parent'] != $item['uri']) {
2053                                 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2054                                         intval(api_user()),
2055                                         dbesc($item['thr-parent']));
2056                                 if ($r)
2057                                         $in_reply_to_status_id = intval($r[0]['id']);
2058                                 else
2059                                         $in_reply_to_status_id = intval($item['parent']);
2060
2061                                 $in_reply_to_status_id_str = (string) intval($item['parent']);
2062
2063                                 $in_reply_to_screen_name = NULL;
2064                                 $in_reply_to_user_id = NULL;
2065                                 $in_reply_to_user_id_str = NULL;
2066
2067                                 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2068                                         intval(api_user()),
2069                                         intval($in_reply_to_status_id));
2070                                 if ($r) {
2071                                         $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2072
2073                                         if ($r) {
2074                                                 if ($r[0]['nick'] == "")
2075                                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);
2076
2077                                                 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2078                                                 $in_reply_to_user_id = intval($r[0]['id']);
2079                                                 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2080                                         }
2081                                 }
2082                         } else {
2083                                 $in_reply_to_screen_name = NULL;
2084                                 $in_reply_to_user_id = NULL;
2085                                 $in_reply_to_status_id = NULL;
2086                                 $in_reply_to_user_id_str = NULL;
2087                                 $in_reply_to_status_id_str = NULL;
2088                         }
2089
2090                         $converted = api_convert_item($item);
2091
2092                         $status = array(
2093                                 'text'          => $converted["text"],
2094                                 'truncated' => False,
2095                                 'created_at'=> api_date($item['created']),
2096                                 'in_reply_to_status_id' => $in_reply_to_status_id,
2097                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2098                                 'source'    => (($item['app']) ? $item['app'] : 'web'),
2099                                 'id'            => intval($item['id']),
2100                                 'id_str'        => (string) intval($item['id']),
2101                                 'in_reply_to_user_id' => $in_reply_to_user_id,
2102                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2103                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2104                                 'geo' => NULL,
2105                                 'favorited' => $item['starred'] ? true : false,
2106                                 'user' =>  $status_user ,
2107                                 //'entities' => NULL,
2108                                 'statusnet_html'                => $converted["html"],
2109                                 'statusnet_conversation_id'     => $item['parent'],
2110                         );
2111
2112                         if (count($converted["attachments"]) > 0)
2113                                 $status["attachments"] = $converted["attachments"];
2114
2115                         if (count($converted["entities"]) > 0)
2116                                 $status["entities"] = $converted["entities"];
2117
2118                         if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2119                                 $status["source"] = network_to_name($item['item_network']);
2120                         else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
2121                                 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
2122
2123
2124                         // Retweets are only valid for top postings
2125                         // It doesn't work reliable with the link if its a feed
2126                         $IsRetweet = ($item['owner-link'] != $item['author-link']);
2127                         if ($IsRetweet)
2128                                 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2129
2130                         if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2131                                 $retweeted_status = $status;
2132                                 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2133
2134                                 $status["retweeted_status"] = $retweeted_status;
2135                         }
2136
2137                         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2138                         unset($status["user"]["uid"]);
2139                         unset($status["user"]["self"]);
2140
2141                         // 'geo' => array('type' => 'Point',
2142                         //                   'coordinates' => array((float) $notice->lat,
2143                         //                                          (float) $notice->lon));
2144
2145                         $ret[] = $status;
2146                 };
2147                 return $ret;
2148         }
2149
2150
2151         function api_account_rate_limit_status(&$a,$type) {
2152
2153                 $hash = array(
2154                           'reset_time_in_seconds' => strtotime('now + 1 hour'),
2155                           'remaining_hits' => (string) 150,
2156                           'hourly_limit' => (string) 150,
2157                           'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2158                 );
2159                 if ($type == "xml")
2160                         $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2161
2162                 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2163
2164         }
2165         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2166
2167         function api_help_test(&$a,$type) {
2168
2169                 if ($type == 'xml')
2170                         $ok = "true";
2171                 else
2172                         $ok = "ok";
2173
2174                 return api_apply_template('test', $type, array("$ok" => $ok));
2175
2176         }
2177         api_register_func('api/help/test','api_help_test',false);
2178
2179         function api_lists(&$a,$type) {
2180
2181                 $ret = array();
2182                 return array($ret);
2183         }
2184         api_register_func('api/lists','api_lists',true);
2185
2186         function api_lists_list(&$a,$type) {
2187
2188                 $ret = array();
2189                 return array($ret);
2190         }
2191         api_register_func('api/lists/list','api_lists_list',true);
2192
2193         /**
2194          *  https://dev.twitter.com/docs/api/1/get/statuses/friends
2195          *  This function is deprecated by Twitter
2196          *  returns: json, xml
2197          **/
2198         function api_statuses_f(&$a, $type, $qtype) {
2199                 if (api_user()===false) return false;
2200                 $user_info = api_get_user($a);
2201
2202                 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2203                         /* this is to stop Hotot to load friends multiple times
2204                         *  I'm not sure if I'm missing return something or
2205                         *  is a bug in hotot. Workaround, meantime
2206                         */
2207
2208                         /*$ret=Array();
2209                         return array('$users' => $ret);*/
2210                         return false;
2211                 }
2212
2213                 if($qtype == 'friends')
2214                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2215                 if($qtype == 'followers')
2216                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2217
2218                 // friends and followers only for self
2219                 if ($user_info['self'] == 0)
2220                         $sql_extra = " AND false ";
2221
2222                 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2223                         intval(api_user())
2224                 );
2225
2226                 $ret = array();
2227                 foreach($r as $cid){
2228                         $user = api_get_user($a, $cid['nurl']);
2229                         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2230                         unset($user["uid"]);
2231                         unset($user["self"]);
2232
2233                         if ($user)
2234                                 $ret[] = $user;
2235                 }
2236
2237                 return array('$users' => $ret);
2238
2239         }
2240         function api_statuses_friends(&$a, $type){
2241                 $data =  api_statuses_f($a,$type,"friends");
2242                 if ($data===false) return false;
2243                 return  api_apply_template("friends", $type, $data);
2244         }
2245         function api_statuses_followers(&$a, $type){
2246                 $data = api_statuses_f($a,$type,"followers");
2247                 if ($data===false) return false;
2248                 return  api_apply_template("friends", $type, $data);
2249         }
2250         api_register_func('api/statuses/friends','api_statuses_friends',true);
2251         api_register_func('api/statuses/followers','api_statuses_followers',true);
2252
2253
2254
2255
2256
2257
2258         function api_statusnet_config(&$a,$type) {
2259                 $name = $a->config['sitename'];
2260                 $server = $a->get_hostname();
2261                 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2262                 $email = $a->config['admin_email'];
2263                 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2264                 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2265                 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2266                 if($a->config['api_import_size'])
2267                         $texlimit = string($a->config['api_import_size']);
2268                 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2269                 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2270
2271                 $config = array(
2272                         'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2273                                 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2274                                 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2275                                 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2276                                 'shorturllength' => '30',
2277                                 'friendica' => array(
2278                                                 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2279                                                 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2280                                                 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2281                                                 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2282                                                 )
2283                         ),
2284                 );
2285
2286                 return api_apply_template('config', $type, array('$config' => $config));
2287
2288         }
2289         api_register_func('api/statusnet/config','api_statusnet_config',false);
2290
2291         function api_statusnet_version(&$a,$type) {
2292
2293                 // liar
2294
2295                 if($type === 'xml') {
2296                         header("Content-type: application/xml");
2297                         echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2298                         killme();
2299                 }
2300                 elseif($type === 'json') {
2301                         header("Content-type: application/json");
2302                         echo '"0.9.7"';
2303                         killme();
2304                 }
2305         }
2306         api_register_func('api/statusnet/version','api_statusnet_version',false);
2307
2308
2309         function api_ff_ids(&$a,$type,$qtype) {
2310                 if(! api_user())
2311                         return false;
2312
2313                 $user_info = api_get_user($a);
2314
2315                 if($qtype == 'friends')
2316                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2317                 if($qtype == 'followers')
2318                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2319
2320                 if (!$user_info["self"])
2321                         $sql_extra = " AND false ";
2322
2323                 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2324
2325                 $r = q("SELECT unique_contacts.id FROM contact, unique_contacts WHERE contact.nurl = unique_contacts.url AND `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2326                         intval(api_user())
2327                 );
2328
2329                 if(is_array($r)) {
2330
2331                         if($type === 'xml') {
2332                                 header("Content-type: application/xml");
2333                                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2334                                 foreach($r as $rr)
2335                                         echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2336                                 echo '</ids>' . "\r\n";
2337                                 killme();
2338                         }
2339                         elseif($type === 'json') {
2340                                 $ret = array();
2341                                 header("Content-type: application/json");
2342                                 foreach($r as $rr)
2343                                         if ($stringify_ids)
2344                                                 $ret[] = $rr['id'];
2345                                         else
2346                                                 $ret[] = intval($rr['id']);
2347
2348                                 echo json_encode($ret);
2349                                 killme();
2350                         }
2351                 }
2352         }
2353
2354         function api_friends_ids(&$a,$type) {
2355                 api_ff_ids($a,$type,'friends');
2356         }
2357         function api_followers_ids(&$a,$type) {
2358                 api_ff_ids($a,$type,'followers');
2359         }
2360         api_register_func('api/friends/ids','api_friends_ids',true);
2361         api_register_func('api/followers/ids','api_followers_ids',true);
2362
2363
2364         function api_direct_messages_new(&$a, $type) {
2365                 if (api_user()===false) return false;
2366
2367                 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2368
2369                 $sender = api_get_user($a);
2370
2371                 require_once("include/message.php");
2372
2373                 if ($_POST['screen_name']) {
2374                         $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2375                                         intval(api_user()),
2376                                         dbesc($_POST['screen_name']));
2377
2378                         // Selecting the id by priority, friendica first
2379                         api_best_nickname($r);
2380
2381                         $recipient = api_get_user($a, $r[0]['nurl']);
2382                 } else
2383                         $recipient = api_get_user($a, $_POST['user_id']);
2384
2385                 $replyto = '';
2386                 $sub     = '';
2387                 if (x($_REQUEST,'replyto')) {
2388                         $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2389                                         intval(api_user()),
2390                                         intval($_REQUEST['replyto']));
2391                         $replyto = $r[0]['parent-uri'];
2392                         $sub     = $r[0]['title'];
2393                 }
2394                 else {
2395                         if (x($_REQUEST,'title')) {
2396                                 $sub = $_REQUEST['title'];
2397                         }
2398                         else {
2399                                 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2400                         }
2401                 }
2402
2403                 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2404
2405                 if ($id>-1) {
2406                         $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2407                         $ret = api_format_messages($r[0], $recipient, $sender);
2408
2409                 } else {
2410                         $ret = array("error"=>$id);
2411                 }
2412
2413                 $data = Array('$messages'=>$ret);
2414
2415                 switch($type){
2416                         case "atom":
2417                         case "rss":
2418                                 $data = api_rss_extra($a, $data, $user_info);
2419                 }
2420
2421                 return  api_apply_template("direct_messages", $type, $data);
2422
2423         }
2424         api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2425
2426         function api_direct_messages_box(&$a, $type, $box) {
2427                 if (api_user()===false) return false;
2428
2429
2430                 // params
2431                 $count = (x($_GET,'count')?$_GET['count']:20);
2432                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2433                 if ($page<0) $page=0;
2434
2435                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2436                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2437
2438                 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2439                 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2440
2441                 //  caller user info
2442                 unset($_REQUEST["user_id"]);
2443                 unset($_GET["user_id"]);
2444
2445                 unset($_REQUEST["screen_name"]);
2446                 unset($_GET["screen_name"]);
2447
2448                 $user_info = api_get_user($a);
2449                 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2450                 $profile_url = $user_info["url"];
2451
2452
2453                 // pagination
2454                 $start = $page*$count;
2455
2456                 // filters
2457                 if ($box=="sentbox") {
2458                         $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2459                 }
2460                 elseif ($box=="conversation") {
2461                         $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] )  ."'";
2462                 }
2463                 elseif ($box=="all") {
2464                         $sql_extra = "true";
2465                 }
2466                 elseif ($box=="inbox") {
2467                         $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2468                 }
2469
2470                 if ($max_id > 0)
2471                         $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2472
2473                 if ($user_id !="") {
2474                         $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2475                 }
2476                 elseif($screen_name !=""){
2477                         $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2478                 }
2479
2480                 $r = q("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",
2481                                 intval(api_user()),
2482                                 intval($since_id),
2483                                 intval($start), intval($count)
2484                 );
2485
2486
2487                 $ret = Array();
2488                 foreach($r as $item) {
2489                         if ($box == "inbox" || $item['from-url'] != $profile_url){
2490                                 $recipient = $user_info;
2491                                 $sender = api_get_user($a,normalise_link($item['contact-url']));
2492                         }
2493                         elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2494                                 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2495                                 $sender = $user_info;
2496
2497                         }
2498                         $ret[]=api_format_messages($item, $recipient, $sender);
2499                 }
2500
2501
2502                 $data = array('$messages' => $ret);
2503                 switch($type){
2504                         case "atom":
2505                         case "rss":
2506                                 $data = api_rss_extra($a, $data, $user_info);
2507                 }
2508
2509                 return  api_apply_template("direct_messages", $type, $data);
2510
2511         }
2512
2513         function api_direct_messages_sentbox(&$a, $type){
2514                 return api_direct_messages_box($a, $type, "sentbox");
2515         }
2516         function api_direct_messages_inbox(&$a, $type){
2517                 return api_direct_messages_box($a, $type, "inbox");
2518         }
2519         function api_direct_messages_all(&$a, $type){
2520                 return api_direct_messages_box($a, $type, "all");
2521         }
2522         function api_direct_messages_conversation(&$a, $type){
2523                 return api_direct_messages_box($a, $type, "conversation");
2524         }
2525         api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2526         api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2527         api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2528         api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2529
2530
2531
2532         function api_oauth_request_token(&$a, $type){
2533                 try{
2534                         $oauth = new FKOAuth1();
2535                         $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2536                 }catch(Exception $e){
2537                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2538                 }
2539                 echo $r;
2540                 killme();
2541         }
2542         function api_oauth_access_token(&$a, $type){
2543                 try{
2544                         $oauth = new FKOAuth1();
2545                         $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2546                 }catch(Exception $e){
2547                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2548                 }
2549                 echo $r;
2550                 killme();
2551         }
2552
2553         api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2554         api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2555
2556
2557         function api_fr_photos_list(&$a,$type) {
2558                 if (api_user()===false) return false;
2559                 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2560                         intval(local_user())
2561                 );
2562                 if($r) {
2563                         $ret = array();
2564                         foreach($r as $rr)
2565                                 $ret[] = $rr['resource-id'];
2566                         header("Content-type: application/json");
2567                         echo json_encode($ret);
2568                 }
2569                 killme();
2570         }
2571
2572         function api_fr_photo_detail(&$a,$type) {
2573                 if (api_user()===false) return false;
2574                 if(! $_REQUEST['photo_id']) return false;
2575                 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2576                 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2577                         intval(local_user()),
2578                         dbesc($_REQUEST['photo_id']),
2579                         intval($scale)
2580                 );
2581                 if($r) {
2582                         header("Content-type: application/json");
2583                         $r[0]['data'] = base64_encode($r[0]['data']);
2584                         echo json_encode($r[0]);
2585                 }
2586
2587                 killme();
2588         }
2589
2590         api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2591         api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2592
2593
2594
2595 function api_share_as_retweet($a, $uid, &$item) {
2596         $body = trim($item["body"]);
2597
2598         // Skip if it isn't a pure repeated messages
2599         // Does it start with a share?
2600         if (strpos($body, "[share") > 0)
2601                 return(false);
2602
2603         // Does it end with a share?
2604         if (strlen($body) > (strrpos($body, "[/share]") + 8))
2605                 return(false);
2606
2607         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2608         // Skip if there is no shared message in there
2609         if ($body == $attributes)
2610                 return(false);
2611
2612         $author = "";
2613         preg_match("/author='(.*?)'/ism", $attributes, $matches);
2614         if ($matches[1] != "")
2615                 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2616
2617         preg_match('/author="(.*?)"/ism', $attributes, $matches);
2618         if ($matches[1] != "")
2619                 $author = $matches[1];
2620
2621         $profile = "";
2622         preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2623         if ($matches[1] != "")
2624                 $profile = $matches[1];
2625
2626         preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2627         if ($matches[1] != "")
2628                 $profile = $matches[1];
2629
2630         $avatar = "";
2631         preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2632         if ($matches[1] != "")
2633                 $avatar = $matches[1];
2634
2635         preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2636         if ($matches[1] != "")
2637                 $avatar = $matches[1];
2638
2639         $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2640
2641         if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2642                 return(false);
2643
2644         $item["body"] = $shared_body;
2645         $item["author-name"] = $author;
2646         $item["author-link"] = $profile;
2647         $item["author-avatar"] = $avatar;
2648
2649         return(true);
2650
2651 }
2652
2653 function api_get_nick($profile) {
2654 /* To-Do:
2655  - remove trailing jung from profile url
2656  - pump.io check has to check the website
2657 */
2658
2659         $nick = "";
2660
2661         $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2662         if ($friendica != $profile)
2663                 $nick = $friendica;
2664
2665         if (!$nick == "") {
2666                 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2667                 if ($diaspora != $profile)
2668                         $nick = $diaspora;
2669         }
2670
2671         if (!$nick == "") {
2672                 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2673                 if ($twitter != $profile)
2674                         $nick = $twitter;
2675         }
2676
2677
2678         if (!$nick == "") {
2679                 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2680                 if ($StatusnetHost != $profile) {
2681                         $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2682                         if ($StatusnetUser != $profile) {
2683                                 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2684                                 $user = json_decode($UserData);
2685                                 if ($user)
2686                                         $nick = $user->screen_name;
2687                         }
2688                 }
2689         }
2690
2691         // To-Do: look at the page if its really a pumpio site
2692         //if (!$nick == "") {
2693         //      $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2694         //      if ($pumpio != $profile)
2695         //              $nick = $pumpio;
2696                 //      <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2697
2698         //}
2699
2700         if ($nick != "") {
2701                 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2702                         dbesc($nick), dbesc(normalise_link($profile)));
2703                 return($nick);
2704         }
2705
2706         return(false);
2707 }
2708
2709 function api_clean_plain_items($Text) {
2710         $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2711
2712         $Text = bb_CleanPictureLinks($Text);
2713
2714         $URLSearchString = "^\[\]";
2715
2716         $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2717
2718         if ($include_entities == "true") {
2719                 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2720         }
2721
2722         $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2723         return($Text);
2724 }
2725
2726 function api_cleanup_share($shared) {
2727         if ($shared[2] != "type-link")
2728                 return($shared[0]);
2729
2730         if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2731                 return($shared[0]);
2732
2733         $title = "";
2734         $link = "";
2735
2736         if (isset($bookmark[2][0]))
2737                 $title = $bookmark[2][0];
2738
2739         if (isset($bookmark[1][0]))
2740                 $link = $bookmark[1][0];
2741
2742         if (strpos($shared[1],$title) !== false)
2743                 $title = "";
2744
2745         if (strpos($shared[1],$link) !== false)
2746                 $link = "";
2747
2748         $text = trim($shared[1]);
2749
2750         //if (strlen($text) < strlen($title))
2751         if (($text == "") AND ($title != ""))
2752                 $text .= "\n\n".trim($title);
2753
2754         if ($link != "")
2755                 $text .= "\n".trim($link);
2756
2757         return(trim($text));
2758 }
2759
2760 function api_best_nickname(&$contacts) {
2761         $best_contact = array();
2762
2763         if (count($contact) == 0)
2764                 return;
2765
2766         foreach ($contacts AS $contact)
2767                 if ($contact["network"] == "") {
2768                         $contact["network"] = "dfrn";
2769                         $best_contact = array($contact);
2770                 }
2771
2772         if (sizeof($best_contact) == 0)
2773                 foreach ($contacts AS $contact)
2774                         if ($contact["network"] == "dfrn")
2775                                 $best_contact = array($contact);
2776
2777         if (sizeof($best_contact) == 0)
2778                 foreach ($contacts AS $contact)
2779                         if ($contact["network"] == "dspr")
2780                                 $best_contact = array($contact);
2781
2782         if (sizeof($best_contact) == 0)
2783                 foreach ($contacts AS $contact)
2784                         if ($contact["network"] == "stat")
2785                                 $best_contact = array($contact);
2786
2787         if (sizeof($best_contact) == 0)
2788                 foreach ($contacts AS $contact)
2789                         if ($contact["network"] == "pump")
2790                                 $best_contact = array($contact);
2791
2792         if (sizeof($best_contact) == 0)
2793                 foreach ($contacts AS $contact)
2794                         if ($contact["network"] == "twit")
2795                                 $best_contact = array($contact);
2796
2797         if (sizeof($best_contact) == 1)
2798                 $contacts = $best_contact;
2799         else
2800                 $contacts = array($contacts[0]);
2801 }
2802
2803 /*
2804 Not implemented by now:
2805 statuses/retweets_of_me
2806 friendships/create
2807 friendships/destroy
2808 friendships/exists
2809 friendships/show
2810 account/update_location
2811 account/update_profile_background_image
2812 account/update_profile_image
2813 blocks/create
2814 blocks/destroy
2815
2816 Not implemented in status.net:
2817 statuses/retweeted_to_me
2818 statuses/retweeted_by_me
2819 direct_messages/destroy
2820 account/end_session
2821 account/update_delivery_device
2822 notifications/follow
2823 notifications/leave
2824 blocks/exists
2825 blocks/blocking
2826 lists
2827 */