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