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