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