]> git.mxchange.org Git - friendica.git/blob - include/api.php
Merge pull request #1269 from fabrixxm/api/favorites
[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                         $status_info = array(
876                                 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
877                                 'truncated' => false,
878                                 'created_at' => api_date($lastwall['created']),
879                                 'in_reply_to_status_id' => $in_reply_to_status_id,
880                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
881                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
882                                 'id' => intval($lastwall['id']),
883                                 'id_str' => (string) $lastwall['id'],
884                                 'in_reply_to_user_id' => $in_reply_to_user_id,
885                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
886                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
887                                 'geo' => NULL,
888                                 'favorited' => $lastwall['starred'] ? true : false,
889                                 // attachments
890                                 'user' => $user_info,
891                                 'statusnet_html'                => trim(bbcode($lastwall['body'], false, false)),
892                                 'statusnet_conversation_id'     => $lastwall['parent'],
893                         );
894
895                         if ($lastwall['title'] != "")
896                                 $status_info['statusnet_html'] = "<h4>".bbcode($lastwall['title'])."</h4>\n".$status_info['statusnet_html'];
897
898                         $entities = api_get_entitities($status_info['text'], $lastwall['body']);
899                         if (count($entities) > 0)
900                                 $status_info['entities'] = $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                         $user_info['status'] = array(
975                                 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
976                                 'truncated' => false,
977                                 'created_at' => api_date($lastwall['created']),
978                                 'in_reply_to_status_id' => $in_reply_to_status_id,
979                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
980                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
981                                 'id' => intval($lastwall['contact-id']),
982                                 'id_str' => (string) $lastwall['contact-id'],
983                                 'in_reply_to_user_id' => $in_reply_to_user_id,
984                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
985                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
986                                 'geo' => NULL,
987                                 'favorited' => $lastwall['starred'] ? true : false,
988                                 'statusnet_html'                => trim(bbcode($lastwall['body'], false, false)),
989                                 'statusnet_conversation_id'     => $lastwall['parent'],
990                         );
991
992                         if ($lastwall['title'] != "")
993                                 $user_info['statusnet_html'] = "<h4>".bbcode($lastwall['title'])."</h4>\n".$user_info['statusnet_html'];
994
995                         $entities = api_get_entitities($user_info['text'], $lastwall['body']);
996                         if (count($entities) > 0)
997                                 $user_info['entities'] = $entities;
998
999                         if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1000                                 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
1001                         if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
1002                                 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
1003
1004                 }
1005
1006                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1007                 unset($user_info["uid"]);
1008                 unset($user_info["self"]);
1009
1010                 return  api_apply_template("user", $type, array('$user' => $user_info));
1011
1012         }
1013         api_register_func('api/users/show','api_users_show');
1014
1015
1016         function api_users_search(&$a, $type) {
1017                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1018
1019                 $userlist = array();
1020
1021                 if (isset($_GET["q"])) {
1022                         $r = q("SELECT id FROM unique_contacts WHERE name='%s'", dbesc($_GET["q"]));
1023                         if (!count($r))
1024                                 $r = q("SELECT id FROM unique_contacts WHERE nick='%s'", dbesc($_GET["q"]));
1025
1026                         if (count($r)) {
1027                                 foreach ($r AS $user) {
1028                                         $user_info = api_get_user($a, $user["id"]);
1029                                         //echo print_r($user_info, true)."\n";
1030                                         $userdata = api_apply_template("user", $type, array('user' => $user_info));
1031                                         $userlist[] = $userdata["user"];
1032                                 }
1033                                 $userlist = array("users" => $userlist);
1034                         } else
1035                                 die(api_error($a, $type, t("User not found.")));
1036                 } else
1037                         die(api_error($a, $type, t("User not found.")));
1038
1039                 return ($userlist);
1040         }
1041
1042         api_register_func('api/users/search','api_users_search');
1043
1044         /**
1045          *
1046          * http://developer.twitter.com/doc/get/statuses/home_timeline
1047          *
1048          * TODO: Optional parameters
1049          * TODO: Add reply info
1050          */
1051         function api_statuses_home_timeline(&$a, $type){
1052                 if (api_user()===false) return false;
1053
1054                 unset($_REQUEST["user_id"]);
1055                 unset($_GET["user_id"]);
1056
1057                 unset($_REQUEST["screen_name"]);
1058                 unset($_GET["screen_name"]);
1059
1060                 $user_info = api_get_user($a);
1061                 // get last newtork messages
1062
1063
1064                 // params
1065                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1066                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1067                 if ($page<0) $page=0;
1068                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1069                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1070                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1071                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1072                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1073
1074                 $start = $page*$count;
1075
1076                 $sql_extra = '';
1077                 if ($max_id > 0)
1078                         $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1079                 if ($exclude_replies > 0)
1080                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1081                 if ($conversation_id > 0)
1082                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1083
1084                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1085                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1086                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1087                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1088                         FROM `item`, `contact`
1089                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1090                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1091                         AND `contact`.`id` = `item`.`contact-id`
1092                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1093                         $sql_extra
1094                         AND `item`.`id`>%d
1095                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1096                         intval(api_user()),
1097                         dbesc(ACTIVITY_POST),
1098                         intval($since_id),
1099                         intval($start), intval($count)
1100                 );
1101
1102                 $ret = api_format_items($r,$user_info);
1103
1104                 // We aren't going to try to figure out at the item, group, and page
1105                 // level which items you've seen and which you haven't. If you're looking
1106                 // at the network timeline just mark everything seen.
1107
1108                 $r = q("UPDATE `item` SET `unseen` = 0
1109                         WHERE `unseen` = 1 AND `uid` = %d",
1110                         //intval($user_info['uid'])
1111                         intval(api_user())
1112                 );
1113
1114
1115                 $data = array('$statuses' => $ret);
1116                 switch($type){
1117                         case "atom":
1118                         case "rss":
1119                                 $data = api_rss_extra($a, $data, $user_info);
1120                                 break;
1121                         case "as":
1122                                 $as = api_format_as($a, $ret, $user_info);
1123                                 $as['title'] = $a->config['sitename']." Home Timeline";
1124                                 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1125                                 return($as);
1126                                 break;
1127                 }
1128
1129                 return  api_apply_template("timeline", $type, $data);
1130         }
1131         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1132         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1133
1134         function api_statuses_public_timeline(&$a, $type){
1135                 if (api_user()===false) return false;
1136
1137                 $user_info = api_get_user($a);
1138                 // get last newtork messages
1139
1140
1141                 // params
1142                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1143                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1144                 if ($page<0) $page=0;
1145                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1146                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1147                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1148                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1149                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1150
1151                 $start = $page*$count;
1152
1153                 if ($max_id > 0)
1154                         $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1155                 if ($exclude_replies > 0)
1156                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1157                 if ($conversation_id > 0)
1158                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1159
1160                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1161                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1162                         `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1163                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1164                         `user`.`nickname`, `user`.`hidewall`
1165                         FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1166                         STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1167                         WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1168                         AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
1169                         AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
1170                         AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1171                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1172                         $sql_extra
1173                         AND `item`.`id`>%d
1174                         ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1175                         dbesc(ACTIVITY_POST),
1176                         intval($since_id),
1177                         intval($start),
1178                         intval($count));
1179
1180                 $ret = api_format_items($r,$user_info);
1181
1182
1183                 $data = array('$statuses' => $ret);
1184                 switch($type){
1185                         case "atom":
1186                         case "rss":
1187                                 $data = api_rss_extra($a, $data, $user_info);
1188                                 break;
1189                         case "as":
1190                                 $as = api_format_as($a, $ret, $user_info);
1191                                 $as['title'] = $a->config['sitename']." Public Timeline";
1192                                 $as['link']['url'] = $a->get_baseurl()."/";
1193                                 return($as);
1194                                 break;
1195                 }
1196
1197                 return  api_apply_template("timeline", $type, $data);
1198         }
1199         api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1200
1201         /**
1202          *
1203          */
1204         function api_statuses_show(&$a, $type){
1205                 if (api_user()===false) return false;
1206
1207                 $user_info = api_get_user($a);
1208
1209                 // params
1210                 $id = intval($a->argv[3]);
1211
1212                 if ($id == 0)
1213                         $id = intval($_REQUEST["id"]);
1214
1215                 // Hotot workaround
1216                 if ($id == 0)
1217                         $id = intval($a->argv[4]);
1218
1219                 logger('API: api_statuses_show: '.$id);
1220
1221                 $conversation = (x($_REQUEST,'conversation')?1:0);
1222
1223                 $sql_extra = '';
1224                 if ($conversation)
1225                         $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1226                 else
1227                         $sql_extra .= " AND `item`.`id` = %d";
1228
1229                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1230                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1231                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1232                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1233                         FROM `item`, `contact`
1234                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1235                         AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1236                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1237                         $sql_extra",
1238                         intval(api_user()),
1239                         dbesc(ACTIVITY_POST),
1240                         intval($id)
1241                 );
1242
1243                 if (!$r)
1244                         die(api_error($a, $type, t("There is no status with this id.")));
1245
1246                 $ret = api_format_items($r,$user_info);
1247
1248                 if ($conversation) {
1249                         $data = array('$statuses' => $ret);
1250                         return api_apply_template("timeline", $type, $data);
1251                 } else {
1252                         $data = array('$status' => $ret[0]);
1253                         /*switch($type){
1254                                 case "atom":
1255                                 case "rss":
1256                                         $data = api_rss_extra($a, $data, $user_info);
1257                         }*/
1258                         return  api_apply_template("status", $type, $data);
1259                 }
1260         }
1261         api_register_func('api/statuses/show','api_statuses_show', true);
1262
1263
1264         /**
1265          *
1266          */
1267         function api_conversation_show(&$a, $type){
1268                 if (api_user()===false) return false;
1269
1270                 $user_info = api_get_user($a);
1271
1272                 // params
1273                 $id = intval($a->argv[3]);
1274                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1275                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1276                 if ($page<0) $page=0;
1277                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1278                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1279
1280                 $start = $page*$count;
1281
1282                 if ($id == 0)
1283                         $id = intval($_REQUEST["id"]);
1284
1285                 // Hotot workaround
1286                 if ($id == 0)
1287                         $id = intval($a->argv[4]);
1288
1289                 logger('API: api_conversation_show: '.$id);
1290
1291                 $sql_extra = '';
1292
1293                 if ($max_id > 0)
1294                         $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1295
1296                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1297                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1298                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1299                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1300                         FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1301                         ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1302                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1303                         AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1304                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1305                         AND `item`.`id`>%d $sql_extra
1306                         ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1307                         intval($id), intval(api_user()),
1308                         dbesc(ACTIVITY_POST),
1309                         intval($since_id),
1310                         intval($start), intval($count)
1311                 );
1312
1313                 if (!$r)
1314                         die(api_error($a, $type, t("There is no conversation with this id.")));
1315
1316                 $ret = api_format_items($r,$user_info);
1317
1318                 $data = array('$statuses' => $ret);
1319                 return api_apply_template("timeline", $type, $data);
1320         }
1321         api_register_func('api/conversation/show','api_conversation_show', true);
1322
1323
1324         /**
1325          *
1326          */
1327         function api_statuses_repeat(&$a, $type){
1328                 global $called_api;
1329
1330                 if (api_user()===false) return false;
1331
1332                 $user_info = api_get_user($a);
1333
1334                 // params
1335                 $id = intval($a->argv[3]);
1336
1337                 if ($id == 0)
1338                         $id = intval($_REQUEST["id"]);
1339
1340                 // Hotot workaround
1341                 if ($id == 0)
1342                         $id = intval($a->argv[4]);
1343
1344                 logger('API: api_statuses_repeat: '.$id);
1345
1346                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1347                         `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1348                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1349                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1350                         FROM `item`, `contact`
1351                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1352                         AND `contact`.`id` = `item`.`contact-id`
1353                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1354                         $sql_extra
1355                         AND `item`.`id`=%d",
1356                         intval($id)
1357                 );
1358
1359                 if ($r[0]['body'] != "") {
1360                         if (!intval(get_config('system','old_share'))) {
1361                                 if (strpos($r[0]['body'], "[/share]") !== false) {
1362                                         $pos = strpos($r[0]['body'], "[share");
1363                                         $post = substr($r[0]['body'], $pos);
1364                                 } else {
1365                                         $post = "[share author='".str_replace("'", "&#039;", $r[0]['author-name']).
1366                                                         "' profile='".$r[0]['author-link'].
1367                                                         "' avatar='".$r[0]['author-avatar'].
1368                                                         "' link='".$r[0]['plink']."']";
1369                                         $post .= $r[0]['body'];
1370                                         $post .= "[/share]";
1371                                 }
1372                                 $_REQUEST['body'] = $post;
1373                         } else
1374                                 $_REQUEST['body'] = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1375
1376                         $_REQUEST['profile_uid'] = api_user();
1377                         $_REQUEST['type'] = 'wall';
1378                         $_REQUEST['api_source'] = true;
1379
1380                         if (!x($_REQUEST, "source"))
1381                                 $_REQUEST["source"] = api_source();
1382
1383                         require_once('mod/item.php');
1384                         item_post($a);
1385                 }
1386
1387                 // this should output the last post (the one we just posted).
1388                 $called_api = null;
1389                 return(api_status_show($a,$type));
1390         }
1391         api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1392
1393         /**
1394          *
1395          */
1396         function api_statuses_destroy(&$a, $type){
1397                 if (api_user()===false) return false;
1398
1399                 $user_info = api_get_user($a);
1400
1401                 // params
1402                 $id = intval($a->argv[3]);
1403
1404                 if ($id == 0)
1405                         $id = intval($_REQUEST["id"]);
1406
1407                 // Hotot workaround
1408                 if ($id == 0)
1409                         $id = intval($a->argv[4]);
1410
1411                 logger('API: api_statuses_destroy: '.$id);
1412
1413                 $ret = api_statuses_show($a, $type);
1414
1415                 require_once('include/items.php');
1416                 drop_item($id, false);
1417
1418                 return($ret);
1419         }
1420         api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1421
1422         /**
1423          *
1424          * http://developer.twitter.com/doc/get/statuses/mentions
1425          *
1426          */
1427         function api_statuses_mentions(&$a, $type){
1428                 if (api_user()===false) return false;
1429
1430                 unset($_REQUEST["user_id"]);
1431                 unset($_GET["user_id"]);
1432
1433                 unset($_REQUEST["screen_name"]);
1434                 unset($_GET["screen_name"]);
1435
1436                 $user_info = api_get_user($a);
1437                 // get last newtork messages
1438
1439
1440                 // params
1441                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1442                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1443                 if ($page<0) $page=0;
1444                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1445                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1446                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1447
1448                 $start = $page*$count;
1449
1450                 // Ugly code - should be changed
1451                 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1452                 $myurl = substr($myurl,strpos($myurl,'://')+3);
1453                 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1454                 $myurl = str_replace('www.','',$myurl);
1455                 $diasp_url = str_replace('/profile/','/u/',$myurl);
1456
1457                 if ($max_id > 0)
1458                         $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1459
1460                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1461                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1462                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1463                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1464                         FROM `item`, `contact`
1465                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1466                         AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1467                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1468                         AND `contact`.`id` = `item`.`contact-id`
1469                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1470                         AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1471                         $sql_extra
1472                         AND `item`.`id`>%d
1473                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1474                         intval(api_user()),
1475                         dbesc(ACTIVITY_POST),
1476                         dbesc(protect_sprintf($myurl)),
1477                         dbesc(protect_sprintf($myurl)),
1478                         intval(api_user()),
1479                         intval($since_id),
1480                         intval($start), intval($count)
1481                 );
1482
1483                 $ret = api_format_items($r,$user_info);
1484
1485
1486                 $data = array('$statuses' => $ret);
1487                 switch($type){
1488                         case "atom":
1489                         case "rss":
1490                                 $data = api_rss_extra($a, $data, $user_info);
1491                                 break;
1492                         case "as":
1493                                 $as = api_format_as($a, $ret, $user_info);
1494                                 $as["title"] = $a->config['sitename']." Mentions";
1495                                 $as['link']['url'] = $a->get_baseurl()."/";
1496                                 return($as);
1497                                 break;
1498                 }
1499
1500                 return  api_apply_template("timeline", $type, $data);
1501         }
1502         api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1503         api_register_func('api/statuses/replies','api_statuses_mentions', true);
1504
1505
1506         function api_statuses_user_timeline(&$a, $type){
1507                 if (api_user()===false) return false;
1508
1509                 $user_info = api_get_user($a);
1510                 // get last network messages
1511
1512                 logger("api_statuses_user_timeline: api_user: ". api_user() .
1513                            "\nuser_info: ".print_r($user_info, true) .
1514                            "\n_REQUEST:  ".print_r($_REQUEST, true),
1515                            LOGGER_DEBUG);
1516
1517                 // params
1518                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1519                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1520                 if ($page<0) $page=0;
1521                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1522                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1523                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1524                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1525
1526                 $start = $page*$count;
1527
1528                 $sql_extra = '';
1529                 if ($user_info['self']==1)
1530                         $sql_extra .= " AND `item`.`wall` = 1 ";
1531
1532                 if ($exclude_replies > 0)
1533                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1534                 if ($conversation_id > 0)
1535                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1536
1537                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1538                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1539                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1540                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1541                         FROM `item`, `contact`
1542                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1543                         AND `item`.`contact-id` = %d
1544                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1545                         AND `contact`.`id` = `item`.`contact-id`
1546                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1547                         $sql_extra
1548                         AND `item`.`id`>%d
1549                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1550                         intval(api_user()),
1551                         dbesc(ACTIVITY_POST),
1552                         intval($user_info['cid']),
1553                         intval($since_id),
1554                         intval($start), intval($count)
1555                 );
1556
1557                 $ret = api_format_items($r,$user_info, true);
1558
1559                 $data = array('$statuses' => $ret);
1560                 switch($type){
1561                         case "atom":
1562                         case "rss":
1563                                 $data = api_rss_extra($a, $data, $user_info);
1564                 }
1565
1566                 return  api_apply_template("timeline", $type, $data);
1567         }
1568
1569         api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1570
1571
1572         /**
1573          * Star/unstar an item
1574          * param: id : id of the item
1575          *
1576          * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1577          */
1578         function api_favorites_create_destroy(&$a, $type){
1579                 if (api_user()===false) return false;
1580
1581                 # for versioned api.
1582                 # TODO: we need a better global soluton
1583                 $action_argv_id=2;
1584                 if ($a->argv[1]=="1.1") $action_argv_id=3;
1585
1586                 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1587                 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1588                 if ($a->argc==$action_argv_id+2) {
1589                         $itemid = intval($a->argv[$action_argv_id+1]);
1590                 } else {
1591                         $itemid = intval($_REQUEST['id']);
1592                 }
1593                 if ($action!="create" && $action!="destroy") die(api_error($a, $type, t("Invalid action. ".$action)));
1594
1595                 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1596                                 $itemid, api_user());
1597
1598                 if ($item===false || count($item)==0) die(api_error($a, $type, t("Invalid item.")));
1599
1600                 switch($action){
1601                         case "create":
1602                                 $r = q("UPDATE item SET starred=1 WHERE id=%d AND uid=%d",
1603                                                 $itemid, api_user());
1604                                 $item[0]['starred']=1;
1605                                 break;
1606                         case "destroy":
1607                                 $r = q("UPDATE item SET starred=0 WHERE id=%d AND uid=%d",
1608                                                 $itemid, api_user());
1609                                 $item[0]['starred']=0;
1610                                 break;
1611                 }
1612
1613                 if ($r===false) die(api_error($a, $type, t("DB error")));
1614
1615
1616                 $user_info = api_get_user($a);
1617                 $ret = api_format_items($item,$user_info)[0];
1618
1619                 $data = array('$status' => $ret);
1620                 switch($type){
1621                         case "atom":
1622                         case "rss":
1623                                 $data = api_rss_extra($a, $data, $user_info);
1624                 }
1625
1626                 return  api_apply_template("status", $type, $data);
1627         }
1628
1629         api_register_func('api/favorites/create', 'api_favorites_create_destroy', true);
1630         api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true);
1631
1632         function api_favorites(&$a, $type){
1633                 global $called_api;
1634
1635                 if (api_user()===false) return false;
1636
1637                 $called_api= array();
1638
1639                 $user_info = api_get_user($a);
1640
1641                 // in friendica starred item are private
1642                 // return favorites only for self
1643                 logger('api_favorites: self:' . $user_info['self']);
1644
1645                 if ($user_info['self']==0) {
1646                         $ret = array();
1647                 } else {
1648                         $sql_extra = "";
1649
1650                         // params
1651                         $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1652                         $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1653                         $count = (x($_GET,'count')?$_GET['count']:20);
1654                         $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1655                         if ($page<0) $page=0;
1656
1657                         $start = $page*$count;
1658
1659                         if ($max_id > 0)
1660                                 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1661
1662                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1663                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1664                                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1665                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1666                                 FROM `item`, `contact`
1667                                 WHERE `item`.`uid` = %d
1668                                 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1669                                 AND `item`.`starred` = 1
1670                                 AND `contact`.`id` = `item`.`contact-id`
1671                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1672                                 $sql_extra
1673                                 AND `item`.`id`>%d
1674                                 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1675                                 intval(api_user()),
1676                                 intval($since_id),
1677                                 intval($start), intval($count)
1678                         );
1679
1680                         $ret = api_format_items($r,$user_info);
1681
1682                 }
1683
1684                 $data = array('$statuses' => $ret);
1685                 switch($type){
1686                         case "atom":
1687                         case "rss":
1688                                 $data = api_rss_extra($a, $data, $user_info);
1689                 }
1690
1691                 return  api_apply_template("timeline", $type, $data);
1692         }
1693
1694         api_register_func('api/favorites','api_favorites', true);
1695
1696
1697
1698
1699         function api_format_as($a, $ret, $user_info) {
1700
1701                 $as = array();
1702                 $as['title'] = $a->config['sitename']." Public Timeline";
1703                 $items = array();
1704                 foreach ($ret as $item) {
1705                         $singleitem["actor"]["displayName"] = $item["user"]["name"];
1706                         $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1707                         $avatar[0]["url"] = $item["user"]["profile_image_url"];
1708                         $avatar[0]["rel"] = "avatar";
1709                         $avatar[0]["type"] = "";
1710                         $avatar[0]["width"] = 96;
1711                         $avatar[0]["height"] = 96;
1712                         $avatar[1]["url"] = $item["user"]["profile_image_url"];
1713                         $avatar[1]["rel"] = "avatar";
1714                         $avatar[1]["type"] = "";
1715                         $avatar[1]["width"] = 48;
1716                         $avatar[1]["height"] = 48;
1717                         $avatar[2]["url"] = $item["user"]["profile_image_url"];
1718                         $avatar[2]["rel"] = "avatar";
1719                         $avatar[2]["type"] = "";
1720                         $avatar[2]["width"] = 24;
1721                         $avatar[2]["height"] = 24;
1722                         $singleitem["actor"]["avatarLinks"] = $avatar;
1723
1724                         $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1725                         $singleitem["actor"]["image"]["rel"] = "avatar";
1726                         $singleitem["actor"]["image"]["type"] = "";
1727                         $singleitem["actor"]["image"]["width"] = 96;
1728                         $singleitem["actor"]["image"]["height"] = 96;
1729                         $singleitem["actor"]["type"] = "person";
1730                         $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1731                         $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1732                         $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1733                         $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1734                         $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1735                         $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1736                         $singleitem["actor"]["contact"]["addresses"] = "";
1737
1738                         $singleitem["body"] = $item["text"];
1739                         $singleitem["object"]["displayName"] = $item["text"];
1740                         $singleitem["object"]["id"] = $item["url"];
1741                         $singleitem["object"]["type"] = "note";
1742                         $singleitem["object"]["url"] = $item["url"];
1743                         //$singleitem["context"] =;
1744                         $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1745                         $singleitem["provider"]["objectType"] = "service";
1746                         $singleitem["provider"]["displayName"] = "Test";
1747                         $singleitem["provider"]["url"] = "http://test.tld";
1748                         $singleitem["title"] = $item["text"];
1749                         $singleitem["verb"] = "post";
1750                         $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1751                         $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1752                         $singleitem["statusnet:notice_info"]["favorite"] = "false";
1753                         $singleitem["statusnet:notice_info"]["repeated"] = "false";
1754                         //$singleitem["original"] = $item;
1755                         $items[] = $singleitem;
1756                 }
1757                 $as['items'] = $items;
1758                 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1759                 $as['link']['rel'] = "alternate";
1760                 $as['link']['type'] = "text/html";
1761                 return($as);
1762         }
1763
1764         function api_format_messages($item, $recipient, $sender) {
1765                 // standard meta information
1766                 $ret=Array(
1767                                 'id'                    => $item['id'],
1768                                 'sender_id'             => $sender['id'] ,
1769                                 'text'                  => "",
1770                                 'recipient_id'          => $recipient['id'],
1771                                 'created_at'            => api_date($item['created']),
1772                                 'sender_screen_name'    => $sender['screen_name'],
1773                                 'recipient_screen_name' => $recipient['screen_name'],
1774                                 'sender'                => $sender,
1775                                 'recipient'             => $recipient,
1776                 );
1777
1778                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1779                 unset($ret["sender"]["uid"]);
1780                 unset($ret["sender"]["self"]);
1781                 unset($ret["recipient"]["uid"]);
1782                 unset($ret["recipient"]["self"]);
1783
1784                 //don't send title to regular StatusNET requests to avoid confusing these apps
1785                 if (x($_GET, 'getText')) {
1786                         $ret['title'] = $item['title'] ;
1787                         if ($_GET["getText"] == "html") {
1788                                 $ret['text'] = bbcode($item['body'], false, false);
1789                         }
1790                         elseif ($_GET["getText"] == "plain") {
1791                                 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1792                                 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1793                         }
1794                 }
1795                 else {
1796                         $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1797                 }
1798                 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1799                         unset($ret['sender']);
1800                         unset($ret['recipient']);
1801                 }
1802
1803                 return $ret;
1804         }
1805
1806         function api_get_entitities(&$text, $bbcode) {
1807                 /*
1808                 To-Do:
1809                 * Links at the first character of the post
1810                 */
1811
1812                 $a = get_app();
1813
1814                 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1815
1816                 if ($include_entities != "true") {
1817                         require_once("mod/proxy.php");
1818
1819                         preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1820
1821                         foreach ($images[1] AS $image) {
1822                                 $replace = proxy_url($image);
1823                                 $text = str_replace($image, $replace, $text);
1824                         }
1825                         return array();
1826                 }
1827
1828                 $bbcode = bb_CleanPictureLinks($bbcode);
1829
1830                 // Change pure links in text to bbcode uris
1831                 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1832
1833                 $entities = array();
1834                 $entities["hashtags"] = array();
1835                 $entities["symbols"] = array();
1836                 $entities["urls"] = array();
1837                 $entities["user_mentions"] = array();
1838
1839                 $URLSearchString = "^\[\]";
1840
1841                 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
1842
1843                 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
1844                 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
1845                 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
1846
1847                 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1848                                         '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
1849                 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
1850
1851                 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1852                                         '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
1853                 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
1854
1855                 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1856
1857                 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
1858                 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
1859
1860                 $ordered_urls = array();
1861                 foreach ($urls[1] AS $id=>$url) {
1862                         //$start = strpos($text, $url, $offset);
1863                         $start = iconv_strpos($text, $url, 0, "UTF-8");
1864                         if (!($start === false))
1865                                 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
1866                 }
1867
1868                 ksort($ordered_urls);
1869
1870                 $offset = 0;
1871                 //foreach ($urls[1] AS $id=>$url) {
1872                 foreach ($ordered_urls AS $url) {
1873                         if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
1874                                 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
1875                                 $display_url = $url["title"];
1876                         else {
1877                                 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
1878                                 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1879
1880                                 if (strlen($display_url) > 26)
1881                                         $display_url = substr($display_url, 0, 25)."…";
1882                         }
1883
1884                         //$start = strpos($text, $url, $offset);
1885                         $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
1886                         if (!($start === false)) {
1887                                 $entities["urls"][] = array("url" => $url["url"],
1888                                                                 "expanded_url" => $url["url"],
1889                                                                 "display_url" => $display_url,
1890                                                                 "indices" => array($start, $start+strlen($url["url"])));
1891                                 $offset = $start + 1;
1892                         }
1893                 }
1894
1895                 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1896                 $ordered_images = array();
1897                 foreach ($images[1] AS $image) {
1898                         //$start = strpos($text, $url, $offset);
1899                         $start = iconv_strpos($text, $image, 0, "UTF-8");
1900                         if (!($start === false))
1901                                 $ordered_images[$start] = $image;
1902                 }
1903                 //$entities["media"] = array();
1904                 $offset = 0;
1905
1906                 foreach ($ordered_images AS $url) {
1907                         $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
1908                         $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1909
1910                         if (strlen($display_url) > 26)
1911                                 $display_url = substr($display_url, 0, 25)."…";
1912
1913                         $start = iconv_strpos($text, $url, $offset, "UTF-8");
1914                         if (!($start === false)) {
1915                                 require_once("include/Photo.php");
1916                                 $image = get_photo_info($url);
1917                                 if ($image) {
1918                                         // If image cache is activated, then use the following sizes:
1919                                         // thumb  (150), small (340), medium (600) and large (1024)
1920                                         if (!get_config("system", "proxy_disabled")) {
1921                                                 require_once("mod/proxy.php");
1922                                                 $media_url = proxy_url($url);
1923
1924                                                 $sizes = array();
1925                                                 $scale = scale_image($image[0], $image[1], 150);
1926                                                 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1927
1928                                                 if (($image[0] > 150) OR ($image[1] > 150)) {
1929                                                         $scale = scale_image($image[0], $image[1], 340);
1930                                                         $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1931                                                 }
1932
1933                                                 $scale = scale_image($image[0], $image[1], 600);
1934                                                 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1935
1936                                                 if (($image[0] > 600) OR ($image[1] > 600)) {
1937                                                         $scale = scale_image($image[0], $image[1], 1024);
1938                                                         $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1939                                                 }
1940                                         } else {
1941                                                 $media_url = $url;
1942                                                 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
1943                                         }
1944
1945                                         $entities["media"][] = array(
1946                                                                 "id" => $start+1,
1947                                                                 "id_str" => (string)$start+1,
1948                                                                 "indices" => array($start, $start+strlen($url)),
1949                                                                 "media_url" => normalise_link($media_url),
1950                                                                 "media_url_https" => $media_url,
1951                                                                 "url" => $url,
1952                                                                 "display_url" => $display_url,
1953                                                                 "expanded_url" => $url,
1954                                                                 "type" => "photo",
1955                                                                 "sizes" => $sizes);
1956                                 }
1957                                 $offset = $start + 1;
1958                         }
1959                 }
1960
1961                 return($entities);
1962         }
1963         function api_format_items_embeded_images($item, $text){
1964                 $a = get_app();
1965                 $text = preg_replace_callback(
1966                                 "|data:image/([^;]+)[^=]+=*|m",
1967                                 function($match) use ($a, $item) {
1968                                         return $a->get_baseurl()."/display/".$item['guid'];
1969                                 },
1970                                 $text);
1971                 return $text;
1972         }
1973
1974         function api_format_items($r,$user_info, $filter_user = false) {
1975
1976                 $a = get_app();
1977                 $ret = Array();
1978
1979                 foreach($r as $item) {
1980                         api_share_as_retweet($a, api_user(), $item);
1981
1982                         localize_item($item);
1983                         $status_user = api_item_get_user($a,$item);
1984
1985                         // Look if the posts are matching if they should be filtered by user id
1986                         if ($filter_user AND ($status_user["id"] != $user_info["id"]))
1987                                 continue;
1988
1989                         if ($item['thr-parent'] != $item['uri']) {
1990                                 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
1991                                         intval(api_user()),
1992                                         dbesc($item['thr-parent']));
1993                                 if ($r)
1994                                         $in_reply_to_status_id = intval($r[0]['id']);
1995                                 else
1996                                         $in_reply_to_status_id = intval($item['parent']);
1997
1998                                 $in_reply_to_status_id_str = (string) intval($item['parent']);
1999
2000                                 $in_reply_to_screen_name = NULL;
2001                                 $in_reply_to_user_id = NULL;
2002                                 $in_reply_to_user_id_str = NULL;
2003
2004                                 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2005                                         intval(api_user()),
2006                                         intval($in_reply_to_status_id));
2007                                 if ($r) {
2008                                         $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2009
2010                                         if ($r) {
2011                                                 if ($r[0]['nick'] == "")
2012                                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);
2013
2014                                                 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2015                                                 $in_reply_to_user_id = intval($r[0]['id']);
2016                                                 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2017                                         }
2018                                 }
2019                         } else {
2020                                 $in_reply_to_screen_name = NULL;
2021                                 $in_reply_to_user_id = NULL;
2022                                 $in_reply_to_status_id = NULL;
2023                                 $in_reply_to_user_id_str = NULL;
2024                                 $in_reply_to_status_id_str = NULL;
2025                         }
2026
2027                         // Workaround for ostatus messages where the title is identically to the body
2028                         //$statusbody = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 5, true), 0));
2029                         $html = bbcode(api_clean_plain_items($item['body']), false, false, 2, true);
2030                         $statusbody = trim(html2plain($html, 0));
2031
2032                         // handle data: images
2033                         $statusbody = api_format_items_embeded_images($item,$statusbody);
2034
2035                         $statustitle = trim($item['title']);
2036
2037                         if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2038                                 $statustext = trim($statusbody);
2039                         else
2040                                 $statustext = trim($statustitle."\n\n".$statusbody);
2041
2042                         if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2043                                 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2044
2045                         $statushtml = trim(bbcode($item['body'], false, false));
2046
2047
2048                         $status = array(
2049                                 'text'          => $statustext,
2050                                 'truncated' => False,
2051                                 'created_at'=> api_date($item['created']),
2052                                 'in_reply_to_status_id' => $in_reply_to_status_id,
2053                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2054                                 'source'    => (($item['app']) ? $item['app'] : 'web'),
2055                                 'id'            => intval($item['id']),
2056                                 'id_str'        => (string) intval($item['id']),
2057                                 'in_reply_to_user_id' => $in_reply_to_user_id,
2058                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2059                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2060                                 'geo' => NULL,
2061                                 'favorited' => $item['starred'] ? true : false,
2062                                 //'attachments' => array(),
2063                                 'user' =>  $status_user ,
2064                                 //'entities' => NULL,
2065                                 'statusnet_html'                => $statushtml,
2066                                 'statusnet_conversation_id'     => $item['parent'],
2067                         );
2068
2069                         if ($item['title'] != "")
2070                                 $status['statusnet_html'] = "<h4>".bbcode($item['title'])."</h4>\n".$status['statusnet_html'];
2071
2072                         $entities = api_get_entitities($status['text'], $item['body']);
2073                         if (count($entities) > 0)
2074                                 $status['entities'] = $entities;
2075
2076                         if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2077                                 $status["source"] = network_to_name($item['item_network']);
2078                         else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
2079                                 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
2080
2081
2082                         // Retweets are only valid for top postings
2083                         // It doesn't work reliable with the link if its a feed
2084                         $IsRetweet = ($item['owner-link'] != $item['author-link']);
2085                         if ($IsRetweet)
2086                                 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2087
2088                         if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2089                                 $retweeted_status = $status;
2090                                 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2091
2092                                 $status["retweeted_status"] = $retweeted_status;
2093                         }
2094
2095                         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2096                         unset($status["user"]["uid"]);
2097                         unset($status["user"]["self"]);
2098
2099                         // 'geo' => array('type' => 'Point',
2100                         //                   'coordinates' => array((float) $notice->lat,
2101                         //                                          (float) $notice->lon));
2102
2103                         $ret[] = $status;
2104                 };
2105                 return $ret;
2106         }
2107
2108
2109         function api_account_rate_limit_status(&$a,$type) {
2110
2111                 $hash = array(
2112                           'reset_time_in_seconds' => strtotime('now + 1 hour'),
2113                           'remaining_hits' => (string) 150,
2114                           'hourly_limit' => (string) 150,
2115                           'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2116                 );
2117                 if ($type == "xml")
2118                         $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2119
2120                 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2121
2122         }
2123         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2124
2125         function api_help_test(&$a,$type) {
2126
2127                 if ($type == 'xml')
2128                         $ok = "true";
2129                 else
2130                         $ok = "ok";
2131
2132                 return api_apply_template('test', $type, array("$ok" => $ok));
2133
2134         }
2135         api_register_func('api/help/test','api_help_test',false);
2136
2137         function api_lists(&$a,$type) {
2138
2139                 $ret = array();
2140                 return array($ret);
2141         }
2142         api_register_func('api/lists','api_lists',true);
2143
2144         function api_lists_list(&$a,$type) {
2145
2146                 $ret = array();
2147                 return array($ret);
2148         }
2149         api_register_func('api/lists/list','api_lists_list',true);
2150
2151         /**
2152          *  https://dev.twitter.com/docs/api/1/get/statuses/friends
2153          *  This function is deprecated by Twitter
2154          *  returns: json, xml
2155          **/
2156         function api_statuses_f(&$a, $type, $qtype) {
2157                 if (api_user()===false) return false;
2158                 $user_info = api_get_user($a);
2159
2160                 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2161                         /* this is to stop Hotot to load friends multiple times
2162                         *  I'm not sure if I'm missing return something or
2163                         *  is a bug in hotot. Workaround, meantime
2164                         */
2165
2166                         /*$ret=Array();
2167                         return array('$users' => $ret);*/
2168                         return false;
2169                 }
2170
2171                 if($qtype == 'friends')
2172                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2173                 if($qtype == 'followers')
2174                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2175
2176                 // friends and followers only for self
2177                 if ($user_info['self'] == 0)
2178                         $sql_extra = " AND false ";
2179
2180                 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2181                         intval(api_user())
2182                 );
2183
2184                 $ret = array();
2185                 foreach($r as $cid){
2186                         $user = api_get_user($a, $cid['nurl']);
2187                         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2188                         unset($user["uid"]);
2189                         unset($user["self"]);
2190
2191                         if ($user)
2192                                 $ret[] = $user;
2193                 }
2194
2195                 return array('$users' => $ret);
2196
2197         }
2198         function api_statuses_friends(&$a, $type){
2199                 $data =  api_statuses_f($a,$type,"friends");
2200                 if ($data===false) return false;
2201                 return  api_apply_template("friends", $type, $data);
2202         }
2203         function api_statuses_followers(&$a, $type){
2204                 $data = api_statuses_f($a,$type,"followers");
2205                 if ($data===false) return false;
2206                 return  api_apply_template("friends", $type, $data);
2207         }
2208         api_register_func('api/statuses/friends','api_statuses_friends',true);
2209         api_register_func('api/statuses/followers','api_statuses_followers',true);
2210
2211
2212
2213
2214
2215
2216         function api_statusnet_config(&$a,$type) {
2217                 $name = $a->config['sitename'];
2218                 $server = $a->get_hostname();
2219                 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2220                 $email = $a->config['admin_email'];
2221                 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2222                 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2223                 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2224                 if($a->config['api_import_size'])
2225                         $texlimit = string($a->config['api_import_size']);
2226                 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2227                 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2228
2229                 $config = array(
2230                         'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2231                                 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2232                                 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2233                                 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2234                                 'shorturllength' => '30',
2235                                 'friendica' => array(
2236                                                 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2237                                                 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2238                                                 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2239                                                 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2240                                                 )
2241                         ),
2242                 );
2243
2244                 return api_apply_template('config', $type, array('$config' => $config));
2245
2246         }
2247         api_register_func('api/statusnet/config','api_statusnet_config',false);
2248
2249         function api_statusnet_version(&$a,$type) {
2250
2251                 // liar
2252
2253                 if($type === 'xml') {
2254                         header("Content-type: application/xml");
2255                         echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2256                         killme();
2257                 }
2258                 elseif($type === 'json') {
2259                         header("Content-type: application/json");
2260                         echo '"0.9.7"';
2261                         killme();
2262                 }
2263         }
2264         api_register_func('api/statusnet/version','api_statusnet_version',false);
2265
2266
2267         function api_ff_ids(&$a,$type,$qtype) {
2268                 if(! api_user())
2269                         return false;
2270
2271                 $user_info = api_get_user($a);
2272
2273                 if($qtype == 'friends')
2274                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2275                 if($qtype == 'followers')
2276                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2277
2278                 if (!$user_info["self"])
2279                         $sql_extra = " AND false ";
2280
2281                 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2282
2283                 $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",
2284                         intval(api_user())
2285                 );
2286
2287                 if(is_array($r)) {
2288
2289                         if($type === 'xml') {
2290                                 header("Content-type: application/xml");
2291                                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2292                                 foreach($r as $rr)
2293                                         echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2294                                 echo '</ids>' . "\r\n";
2295                                 killme();
2296                         }
2297                         elseif($type === 'json') {
2298                                 $ret = array();
2299                                 header("Content-type: application/json");
2300                                 foreach($r as $rr)
2301                                         if ($stringify_ids)
2302                                                 $ret[] = $rr['id'];
2303                                         else
2304                                                 $ret[] = intval($rr['id']);
2305
2306                                 echo json_encode($ret);
2307                                 killme();
2308                         }
2309                 }
2310         }
2311
2312         function api_friends_ids(&$a,$type) {
2313                 api_ff_ids($a,$type,'friends');
2314         }
2315         function api_followers_ids(&$a,$type) {
2316                 api_ff_ids($a,$type,'followers');
2317         }
2318         api_register_func('api/friends/ids','api_friends_ids',true);
2319         api_register_func('api/followers/ids','api_followers_ids',true);
2320
2321
2322         function api_direct_messages_new(&$a, $type) {
2323                 if (api_user()===false) return false;
2324
2325                 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2326
2327                 $sender = api_get_user($a);
2328
2329                 require_once("include/message.php");
2330
2331                 if ($_POST['screen_name']) {
2332                         $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2333                                         intval(api_user()),
2334                                         dbesc($_POST['screen_name']));
2335
2336                         // Selecting the id by priority, friendica first
2337                         api_best_nickname($r);
2338
2339                         $recipient = api_get_user($a, $r[0]['nurl']);
2340                 } else
2341                         $recipient = api_get_user($a, $_POST['user_id']);
2342
2343                 $replyto = '';
2344                 $sub     = '';
2345                 if (x($_REQUEST,'replyto')) {
2346                         $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2347                                         intval(api_user()),
2348                                         intval($_REQUEST['replyto']));
2349                         $replyto = $r[0]['parent-uri'];
2350                         $sub     = $r[0]['title'];
2351                 }
2352                 else {
2353                         if (x($_REQUEST,'title')) {
2354                                 $sub = $_REQUEST['title'];
2355                         }
2356                         else {
2357                                 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2358                         }
2359                 }
2360
2361                 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2362
2363                 if ($id>-1) {
2364                         $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2365                         $ret = api_format_messages($r[0], $recipient, $sender);
2366
2367                 } else {
2368                         $ret = array("error"=>$id);
2369                 }
2370
2371                 $data = Array('$messages'=>$ret);
2372
2373                 switch($type){
2374                         case "atom":
2375                         case "rss":
2376                                 $data = api_rss_extra($a, $data, $user_info);
2377                 }
2378
2379                 return  api_apply_template("direct_messages", $type, $data);
2380
2381         }
2382         api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2383
2384         function api_direct_messages_box(&$a, $type, $box) {
2385                 if (api_user()===false) return false;
2386
2387
2388                 // params
2389                 $count = (x($_GET,'count')?$_GET['count']:20);
2390                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2391                 if ($page<0) $page=0;
2392
2393                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2394                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2395
2396                 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2397                 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2398
2399                 //  caller user info
2400                 unset($_REQUEST["user_id"]);
2401                 unset($_GET["user_id"]);
2402
2403                 unset($_REQUEST["screen_name"]);
2404                 unset($_GET["screen_name"]);
2405
2406                 $user_info = api_get_user($a);
2407                 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2408                 $profile_url = $user_info["url"];
2409
2410
2411                 // pagination
2412                 $start = $page*$count;
2413
2414                 // filters
2415                 if ($box=="sentbox") {
2416                         $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2417                 }
2418                 elseif ($box=="conversation") {
2419                         $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] )  ."'";
2420                 }
2421                 elseif ($box=="all") {
2422                         $sql_extra = "true";
2423                 }
2424                 elseif ($box=="inbox") {
2425                         $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2426                 }
2427
2428                 if ($max_id > 0)
2429                         $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2430
2431                 if ($user_id !="") {
2432                         $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2433                 }
2434                 elseif($screen_name !=""){
2435                         $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2436                 }
2437
2438                 $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",
2439                                 intval(api_user()),
2440                                 intval($since_id),
2441                                 intval($start), intval($count)
2442                 );
2443
2444
2445                 $ret = Array();
2446                 foreach($r as $item) {
2447                         if ($box == "inbox" || $item['from-url'] != $profile_url){
2448                                 $recipient = $user_info;
2449                                 $sender = api_get_user($a,normalise_link($item['contact-url']));
2450                         }
2451                         elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2452                                 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2453                                 $sender = $user_info;
2454
2455                         }
2456                         $ret[]=api_format_messages($item, $recipient, $sender);
2457                 }
2458
2459
2460                 $data = array('$messages' => $ret);
2461                 switch($type){
2462                         case "atom":
2463                         case "rss":
2464                                 $data = api_rss_extra($a, $data, $user_info);
2465                 }
2466
2467                 return  api_apply_template("direct_messages", $type, $data);
2468
2469         }
2470
2471         function api_direct_messages_sentbox(&$a, $type){
2472                 return api_direct_messages_box($a, $type, "sentbox");
2473         }
2474         function api_direct_messages_inbox(&$a, $type){
2475                 return api_direct_messages_box($a, $type, "inbox");
2476         }
2477         function api_direct_messages_all(&$a, $type){
2478                 return api_direct_messages_box($a, $type, "all");
2479         }
2480         function api_direct_messages_conversation(&$a, $type){
2481                 return api_direct_messages_box($a, $type, "conversation");
2482         }
2483         api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2484         api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2485         api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2486         api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2487
2488
2489
2490         function api_oauth_request_token(&$a, $type){
2491                 try{
2492                         $oauth = new FKOAuth1();
2493                         $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2494                 }catch(Exception $e){
2495                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2496                 }
2497                 echo $r;
2498                 killme();
2499         }
2500         function api_oauth_access_token(&$a, $type){
2501                 try{
2502                         $oauth = new FKOAuth1();
2503                         $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2504                 }catch(Exception $e){
2505                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2506                 }
2507                 echo $r;
2508                 killme();
2509         }
2510
2511         api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2512         api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2513
2514
2515         function api_fr_photos_list(&$a,$type) {
2516                 if (api_user()===false) return false;
2517                 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2518                         intval(local_user())
2519                 );
2520                 if($r) {
2521                         $ret = array();
2522                         foreach($r as $rr)
2523                                 $ret[] = $rr['resource-id'];
2524                         header("Content-type: application/json");
2525                         echo json_encode($ret);
2526                 }
2527                 killme();
2528         }
2529
2530         function api_fr_photo_detail(&$a,$type) {
2531                 if (api_user()===false) return false;
2532                 if(! $_REQUEST['photo_id']) return false;
2533                 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2534                 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2535                         intval(local_user()),
2536                         dbesc($_REQUEST['photo_id']),
2537                         intval($scale)
2538                 );
2539                 if($r) {
2540                         header("Content-type: application/json");
2541                         $r[0]['data'] = base64_encode($r[0]['data']);
2542                         echo json_encode($r[0]);
2543                 }
2544
2545                 killme();
2546         }
2547
2548         api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2549         api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2550
2551
2552
2553 function api_share_as_retweet($a, $uid, &$item) {
2554         $body = trim($item["body"]);
2555
2556         // Skip if it isn't a pure repeated messages
2557         // Does it start with a share?
2558         if (strpos($body, "[share") > 0)
2559                 return(false);
2560
2561         // Does it end with a share?
2562         if (strlen($body) > (strrpos($body, "[/share]") + 8))
2563                 return(false);
2564
2565         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2566         // Skip if there is no shared message in there
2567         if ($body == $attributes)
2568                 return(false);
2569
2570         $author = "";
2571         preg_match("/author='(.*?)'/ism", $attributes, $matches);
2572         if ($matches[1] != "")
2573                 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2574
2575         preg_match('/author="(.*?)"/ism', $attributes, $matches);
2576         if ($matches[1] != "")
2577                 $author = $matches[1];
2578
2579         $profile = "";
2580         preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2581         if ($matches[1] != "")
2582                 $profile = $matches[1];
2583
2584         preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2585         if ($matches[1] != "")
2586                 $profile = $matches[1];
2587
2588         $avatar = "";
2589         preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2590         if ($matches[1] != "")
2591                 $avatar = $matches[1];
2592
2593         preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2594         if ($matches[1] != "")
2595                 $avatar = $matches[1];
2596
2597         $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2598
2599         if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2600                 return(false);
2601
2602         $item["body"] = $shared_body;
2603         $item["author-name"] = $author;
2604         $item["author-link"] = $profile;
2605         $item["author-avatar"] = $avatar;
2606
2607         return(true);
2608
2609 }
2610
2611 function api_get_nick($profile) {
2612 /* To-Do:
2613  - remove trailing jung from profile url
2614  - pump.io check has to check the website
2615 */
2616
2617         $nick = "";
2618
2619         $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2620         if ($friendica != $profile)
2621                 $nick = $friendica;
2622
2623         if (!$nick == "") {
2624                 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2625                 if ($diaspora != $profile)
2626                         $nick = $diaspora;
2627         }
2628
2629         if (!$nick == "") {
2630                 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2631                 if ($twitter != $profile)
2632                         $nick = $twitter;
2633         }
2634
2635
2636         if (!$nick == "") {
2637                 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2638                 if ($StatusnetHost != $profile) {
2639                         $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2640                         if ($StatusnetUser != $profile) {
2641                                 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2642                                 $user = json_decode($UserData);
2643                                 if ($user)
2644                                         $nick = $user->screen_name;
2645                         }
2646                 }
2647         }
2648
2649         // To-Do: look at the page if its really a pumpio site
2650         //if (!$nick == "") {
2651         //      $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2652         //      if ($pumpio != $profile)
2653         //              $nick = $pumpio;
2654                 //      <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2655
2656         //}
2657
2658         if ($nick != "") {
2659                 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2660                         dbesc($nick), dbesc(normalise_link($profile)));
2661                 return($nick);
2662         }
2663
2664         return(false);
2665 }
2666
2667 function api_clean_plain_items($Text) {
2668         $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2669
2670         $Text = bb_CleanPictureLinks($Text);
2671
2672         $URLSearchString = "^\[\]";
2673
2674         $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2675
2676         if ($include_entities == "true") {
2677                 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2678         }
2679
2680         $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2681         return($Text);
2682 }
2683
2684 function api_cleanup_share($shared) {
2685         if ($shared[2] != "type-link")
2686                 return($shared[0]);
2687
2688         if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2689                 return($shared[0]);
2690
2691         $title = "";
2692         $link = "";
2693
2694         if (isset($bookmark[2][0]))
2695                 $title = $bookmark[2][0];
2696
2697         if (isset($bookmark[1][0]))
2698                 $link = $bookmark[1][0];
2699
2700         if (strpos($shared[1],$title) !== false)
2701                 $title = "";
2702
2703         if (strpos($shared[1],$link) !== false)
2704                 $link = "";
2705
2706         $text = trim($shared[1]);
2707
2708         //if (strlen($text) < strlen($title))
2709         if (($text == "") AND ($title != ""))
2710                 $text .= "\n\n".trim($title);
2711
2712         if ($link != "")
2713                 $text .= "\n".trim($link);
2714
2715         return(trim($text));
2716 }
2717
2718 function api_best_nickname(&$contacts) {
2719         $best_contact = array();
2720
2721         if (count($contact) == 0)
2722                 return;
2723
2724         foreach ($contacts AS $contact)
2725                 if ($contact["network"] == "") {
2726                         $contact["network"] = "dfrn";
2727                         $best_contact = array($contact);
2728                 }
2729
2730         if (sizeof($best_contact) == 0)
2731                 foreach ($contacts AS $contact)
2732                         if ($contact["network"] == "dfrn")
2733                                 $best_contact = array($contact);
2734
2735         if (sizeof($best_contact) == 0)
2736                 foreach ($contacts AS $contact)
2737                         if ($contact["network"] == "dspr")
2738                                 $best_contact = array($contact);
2739
2740         if (sizeof($best_contact) == 0)
2741                 foreach ($contacts AS $contact)
2742                         if ($contact["network"] == "stat")
2743                                 $best_contact = array($contact);
2744
2745         if (sizeof($best_contact) == 0)
2746                 foreach ($contacts AS $contact)
2747                         if ($contact["network"] == "pump")
2748                                 $best_contact = array($contact);
2749
2750         if (sizeof($best_contact) == 0)
2751                 foreach ($contacts AS $contact)
2752                         if ($contact["network"] == "twit")
2753                                 $best_contact = array($contact);
2754
2755         if (sizeof($best_contact) == 1)
2756                 $contacts = $best_contact;
2757         else
2758                 $contacts = array($contacts[0]);
2759 }
2760
2761 /*
2762 Not implemented by now:
2763 statuses/retweets_of_me
2764 friendships/create
2765 friendships/destroy
2766 friendships/exists
2767 friendships/show
2768 account/update_location
2769 account/update_profile_background_image
2770 account/update_profile_image
2771 blocks/create
2772 blocks/destroy
2773
2774 Not implemented in status.net:
2775 statuses/retweeted_to_me
2776 statuses/retweeted_by_me
2777 direct_messages/destroy
2778 account/end_session
2779 account/update_delivery_device
2780 notifications/follow
2781 notifications/leave
2782 blocks/exists
2783 blocks/blocking
2784 lists
2785 */