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