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