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