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