]> git.mxchange.org Git - friendica.git/blob - include/api.php
Merge remote-tracking branch 'upstream/develop' into 1512-ostatus-comment
[friendica.git] / include / api.php
1 <?php
2 /* To-Do:
3  - Automatically detect if incoming data is HTML or BBCode
4 */
5
6 /* Contact details:
7         Gerhard Seeber          Mail: gerhard@seeber.at         Friendica: http://mozartweg.dyndns.org/friendica/gerhard
8
9  */
10
11
12 /*
13  * Change history:
14         Gerhard Seeber          2015-NOV-25     Add API call /friendica/group_show to return all or a single group
15                                                 with the containing contacts (necessary for Windows 10 Universal app)
16         Gerhard Seeber          2015-NOV-27     Add API call /friendica/group_delete to delete the specified group id
17                                                 (necessary for Windows 10 Universal app)
18         Gerhard Seeber          2015-DEC-01     Add API call /friendica/group_create to create a group with the specified 
19                                                 name and the given list of contacts (necessary for Windows 10 Universal
20                                                 app)
21         Gerhard Seeber          2015-DEC-07     Add API call /friendica/group_update to update a group with the given 
22                                                 list of contacts (necessary for Windows 10 Universal app)
23  *
24  */
25
26         require_once("include/bbcode.php");
27         require_once("include/datetime.php");
28         require_once("include/conversation.php");
29         require_once("include/oauth.php");
30         require_once("include/html2plain.php");
31         require_once("mod/share.php");
32         require_once("include/Photo.php");
33         require_once("mod/item.php");
34         require_once('include/security.php');
35         require_once('include/contact_selectors.php');
36         require_once('include/html2bbcode.php');
37         require_once('mod/wall_upload.php');
38         require_once("mod/proxy.php");
39         require_once("include/message.php");
40         require_once("include/group.php");
41
42
43         /*
44          * Twitter-Like API
45          *
46          */
47
48         $API = Array();
49         $called_api = Null;
50
51         function api_user() {
52                 // It is not sufficient to use local_user() to check whether someone is allowed to use the API,
53                 // because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
54                 // into a page, and visitors will post something without noticing it).
55                 // Instead, use this function.
56                 if ($_SESSION["allow_api"])
57                         return local_user();
58
59                 return false;
60         }
61
62         function api_source() {
63                 if (requestdata('source'))
64                         return (requestdata('source'));
65
66                 // Support for known clients that doesn't send a source name
67                 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
68                         return ("Twidere");
69
70                 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
71
72                 return ("api");
73         }
74
75         function api_date($str){
76                 //Wed May 23 06:01:13 +0000 2007
77                 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
78         }
79
80
81         function api_register_func($path, $func, $auth=false){
82                 global $API;
83                 $API[$path] = array('func'=>$func, 'auth'=>$auth);
84
85                 // Workaround for hotot
86                 $path = str_replace("api/", "api/1.1/", $path);
87                 $API[$path] = array('func'=>$func, 'auth'=>$auth);
88         }
89
90         /**
91          * Simple HTTP Login
92          */
93
94         function api_login(&$a){
95                 // login with oauth
96                 try{
97                         $oauth = new FKOAuth1();
98                         list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
99                         if (!is_null($token)){
100                                 $oauth->loginUser($token->uid);
101                                 call_hooks('logged_in', $a->user);
102                                 return;
103                         }
104                         echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
105                 }catch(Exception $e){
106                         logger(__file__.__line__.__function__."\n".$e);
107                         //die(__file__.__line__.__function__."<pre>".$e); die();
108                 }
109
110
111
112                 // workaround for HTTP-auth in CGI mode
113                 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
114                         $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
115                         if(strlen($userpass)) {
116                                 list($name, $password) = explode(':', $userpass);
117                                 $_SERVER['PHP_AUTH_USER'] = $name;
118                                 $_SERVER['PHP_AUTH_PW'] = $password;
119                         }
120                 }
121
122                 if (!isset($_SERVER['PHP_AUTH_USER'])) {
123                         logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
124                         header('WWW-Authenticate: Basic realm="Friendica"');
125                         header('HTTP/1.0 401 Unauthorized');
126                         die((api_error($a, 'json', "This api requires login")));
127
128                         //die('This api requires login');
129                 }
130
131                 $user = $_SERVER['PHP_AUTH_USER'];
132                 $password = $_SERVER['PHP_AUTH_PW'];
133                 $encrypted = hash('whirlpool',trim($password));
134
135                 // allow "user@server" login (but ignore 'server' part)
136                 $at=strstr($user, "@", true);
137                 if ( $at ) $user=$at;
138
139                 /**
140                  *  next code from mod/auth.php. needs better solution
141                  */
142                 $record = null;
143
144                 $addon_auth = array(
145                         'username' => trim($user),
146                         'password' => trim($password),
147                         'authenticated' => 0,
148                         'user_record' => null
149                 );
150
151                 /**
152                  *
153                  * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
154                  * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
155                  * and later plugins should not interfere with an earlier one that succeeded.
156                  *
157                  */
158
159                 call_hooks('authenticate', $addon_auth);
160
161                 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
162                         $record = $addon_auth['user_record'];
163                 }
164                 else {
165                         // process normal login request
166
167                         $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
168                                 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
169                                 dbesc(trim($user)),
170                                 dbesc(trim($user)),
171                                 dbesc($encrypted)
172                         );
173                         if(count($r))
174                                 $record = $r[0];
175                 }
176
177                 if((! $record) || (! count($record))) {
178                         logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
179                         header('WWW-Authenticate: Basic realm="Friendica"');
180                         header('HTTP/1.0 401 Unauthorized');
181                         die('This api requires login');
182                 }
183
184                 authenticate_success($record); $_SESSION["allow_api"] = true;
185
186                 call_hooks('logged_in', $a->user);
187
188         }
189
190         /**************************
191          *  MAIN API ENTRY POINT  *
192          **************************/
193         function api_call(&$a){
194                 GLOBAL $API, $called_api;
195
196                 // preset
197                 $type="json";
198                 foreach ($API as $p=>$info){
199                         if (strpos($a->query_string, $p)===0){
200                                 $called_api= explode("/",$p);
201                                 //unset($_SERVER['PHP_AUTH_USER']);
202                                 if ($info['auth']===true && api_user()===false) {
203                                                 api_login($a);
204                                 }
205
206                                 load_contact_links(api_user());
207
208                                 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
209                                 logger('API parameters: ' . print_r($_REQUEST,true));
210                                 $type="json";
211                                 if (strpos($a->query_string, ".xml")>0) $type="xml";
212                                 if (strpos($a->query_string, ".json")>0) $type="json";
213                                 if (strpos($a->query_string, ".rss")>0) $type="rss";
214                                 if (strpos($a->query_string, ".atom")>0) $type="atom";
215                                 if (strpos($a->query_string, ".as")>0) $type="as";
216
217                                 $stamp =  microtime(true);
218                                 $r = call_user_func($info['func'], $a, $type);
219                                 $duration = (float)(microtime(true)-$stamp);
220                                 logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
221
222                                 if ($r===false) return;
223
224                                 switch($type){
225                                         case "xml":
226                                                 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
227                                                 header ("Content-Type: text/xml");
228                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
229                                                 break;
230                                         case "json":
231                                                 header ("Content-Type: application/json");
232                                                 foreach($r as $rr)
233                                                         $json = json_encode($rr);
234                                                         if ($_GET['callback'])
235                                                                 $json = $_GET['callback']."(".$json.")";
236                                                         return $json;
237                                                 break;
238                                         case "rss":
239                                                 header ("Content-Type: application/rss+xml");
240                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
241                                                 break;
242                                         case "atom":
243                                                 header ("Content-Type: application/atom+xml");
244                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
245                                                 break;
246                                         case "as":
247                                                 //header ("Content-Type: application/json");
248                                                 //foreach($r as $rr)
249                                                 //      return json_encode($rr);
250                                                 return json_encode($r);
251                                                 break;
252
253                                 }
254                                 //echo "<pre>"; var_dump($r); die();
255                         }
256                 }
257                 header("HTTP/1.1 404 Not Found");
258                 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
259                 return(api_error($a, $type, "not implemented"));
260
261         }
262
263         function api_error(&$a, $type, $error) {
264                 # TODO:  https://dev.twitter.com/overview/api/response-codes
265                 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
266                 switch($type){
267                         case "xml":
268                                 header ("Content-Type: text/xml");
269                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
270                                 break;
271                         case "json":
272                                 header ("Content-Type: application/json");
273                                 return json_encode(array('error' => $error, 'request' => $a->query_string));
274                                 break;
275                         case "rss":
276                                 header ("Content-Type: application/rss+xml");
277                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
278                                 break;
279                         case "atom":
280                                 header ("Content-Type: application/atom+xml");
281                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
282                                 break;
283                 }
284         }
285
286         /**
287          * RSS extra info
288          */
289         function api_rss_extra(&$a, $arr, $user_info){
290                 if (is_null($user_info)) $user_info = api_get_user($a);
291                 $arr['$user'] = $user_info;
292                 $arr['$rss'] = array(
293                         'alternate' => $user_info['url'],
294                         'self' => $a->get_baseurl(). "/". $a->query_string,
295                         'base' => $a->get_baseurl(),
296                         'updated' => api_date(null),
297                         'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
298                         'language' => $user_info['language'],
299                         'logo'  => $a->get_baseurl()."/images/friendica-32.png",
300                 );
301
302                 return $arr;
303         }
304
305
306         /**
307          * Unique contact to contact url.
308          */
309         function api_unique_id_to_url($id){
310                 $r = q("SELECT `url` FROM `unique_contacts` WHERE `id`=%d LIMIT 1",
311                         intval($id));
312                 if ($r)
313                         return ($r[0]["url"]);
314                 else
315                         return false;
316         }
317
318         /**
319          * Returns user info array.
320          */
321         function api_get_user(&$a, $contact_id = Null, $type = "json"){
322                 global $called_api;
323                 $user = null;
324                 $extra_query = "";
325                 $url = "";
326                 $nick = "";
327
328                 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
329
330                 // Searching for contact URL
331                 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
332                         $user = dbesc(normalise_link($contact_id));
333                         $url = $user;
334                         $extra_query = "AND `contact`.`nurl` = '%s' ";
335                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
336                 }
337
338                 // Searching for unique contact id
339                 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
340                         $user = dbesc(api_unique_id_to_url($contact_id));
341
342                         if ($user == "")
343                                 die(api_error($a, $type, t("User not found.")));
344
345                         $url = $user;
346                         $extra_query = "AND `contact`.`nurl` = '%s' ";
347                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
348                 }
349
350                 if(is_null($user) && x($_GET, 'user_id')) {
351                         $user = dbesc(api_unique_id_to_url($_GET['user_id']));
352
353                         if ($user == "")
354                                 die(api_error($a, $type, t("User not found.")));
355
356                         $url = $user;
357                         $extra_query = "AND `contact`.`nurl` = '%s' ";
358                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
359                 }
360                 if(is_null($user) && x($_GET, 'screen_name')) {
361                         $user = dbesc($_GET['screen_name']);
362                         $nick = $user;
363                         $extra_query = "AND `contact`.`nick` = '%s' ";
364                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
365                 }
366
367                 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
368                         $argid = count($called_api);
369                         list($user, $null) = explode(".",$a->argv[$argid]);
370                         if(is_numeric($user)){
371                                 $user = dbesc(api_unique_id_to_url($user));
372
373                                 if ($user == "")
374                                         return false;
375
376                                 $url = $user;
377                                 $extra_query = "AND `contact`.`nurl` = '%s' ";
378                                 if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
379                         } else {
380                                 $user = dbesc($user);
381                                 $nick = $user;
382                                 $extra_query = "AND `contact`.`nick` = '%s' ";
383                                 if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
384                         }
385                 }
386
387                 logger("api_get_user: user ".$user, LOGGER_DEBUG);
388
389                 if (!$user) {
390                         if (api_user()===false) {
391                                 api_login($a); return False;
392                         } else {
393                                 $user = $_SESSION['uid'];
394                                 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
395                         }
396
397                 }
398
399                 logger('api_user: ' . $extra_query . ', user: ' . $user);
400                 // user info
401                 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
402                                 WHERE 1
403                                 $extra_query",
404                                 $user
405                 );
406
407                 // Selecting the id by priority, friendica first
408                 api_best_nickname($uinfo);
409
410                 // if the contact wasn't found, fetch it from the unique contacts
411                 if (count($uinfo)==0) {
412                         $r = array();
413
414                         if ($url != "")
415                                 $r = q("SELECT * FROM `unique_contacts` WHERE `url`='%s' LIMIT 1", $url);
416                         elseif ($nick != "")
417                                 $r = q("SELECT * FROM `unique_contacts` WHERE `nick`='%s' LIMIT 1", $nick);
418
419                         if ($r) {
420                                 // If no nick where given, extract it from the address
421                                 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
422                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);
423
424                                 $ret = array(
425                                         'id' => $r[0]["id"],
426                                         'id_str' => (string) $r[0]["id"],
427                                         'name' => $r[0]["name"],
428                                         'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
429                                         'location' => NULL,
430                                         'description' => NULL,
431                                         'url' => $r[0]["url"],
432                                         'protected' => false,
433                                         'followers_count' => 0,
434                                         'friends_count' => 0,
435                                         'listed_count' => 0,
436                                         'created_at' => api_date(0),
437                                         'favourites_count' => 0,
438                                         'utc_offset' => 0,
439                                         'time_zone' => 'UTC',
440                                         'geo_enabled' => false,
441                                         'verified' => false,
442                                         'statuses_count' => 0,
443                                         'lang' => '',
444                                         'contributors_enabled' => false,
445                                         'is_translator' => false,
446                                         'is_translation_enabled' => false,
447                                         'profile_image_url' => $r[0]["avatar"],
448                                         'profile_image_url_https' => $r[0]["avatar"],
449                                         'following' => false,
450                                         'follow_request_sent' => false,
451                                         'notifications' => false,
452                                         'statusnet_blocking' => false,
453                                         'notifications' => false,
454                                         'statusnet_profile_url' => $r[0]["url"],
455                                         'uid' => 0,
456                                         'cid' => 0,
457                                         'self' => 0,
458                                         'network' => '',
459                                 );
460
461                                 return $ret;
462                         } else
463                                 die(api_error($a, $type, t("User not found.")));
464
465                 }
466
467                 if($uinfo[0]['self']) {
468                         $usr = q("select * from user where uid = %d limit 1",
469                                 intval(api_user())
470                         );
471                         $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
472                                 intval(api_user())
473                         );
474
475                         //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
476                         // count public wall messages
477                         $r = q("SELECT count(*) as `count` FROM `item`
478                                         WHERE  `uid` = %d
479                                         AND `type`='wall'",
480                                         intval($uinfo[0]['uid'])
481                         );
482                         $countitms = $r[0]['count'];
483                 }
484                 else {
485                         //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
486                         $r = q("SELECT count(*) as `count` FROM `item`
487                                         WHERE  `contact-id` = %d",
488                                         intval($uinfo[0]['id'])
489                         );
490                         $countitms = $r[0]['count'];
491                 }
492
493                 // count friends
494                 $r = q("SELECT count(*) as `count` FROM `contact`
495                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
496                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
497                                 intval($uinfo[0]['uid']),
498                                 intval(CONTACT_IS_SHARING),
499                                 intval(CONTACT_IS_FRIEND)
500                 );
501                 $countfriends = $r[0]['count'];
502
503                 $r = q("SELECT count(*) as `count` FROM `contact`
504                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
505                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
506                                 intval($uinfo[0]['uid']),
507                                 intval(CONTACT_IS_FOLLOWER),
508                                 intval(CONTACT_IS_FRIEND)
509                 );
510                 $countfollowers = $r[0]['count'];
511
512                 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
513                         intval($uinfo[0]['uid'])
514                 );
515                 $starred = $r[0]['count'];
516
517
518                 if(! $uinfo[0]['self']) {
519                         $countfriends = 0;
520                         $countfollowers = 0;
521                         $starred = 0;
522                 }
523
524                 // Add a nick if it isn't present there
525                 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
526                         $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
527                 }
528
529                 // Fetching unique id
530                 $r = q("SELECT id FROM `unique_contacts` WHERE `url`='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
531
532                 // If not there, then add it
533                 if (count($r) == 0) {
534                         q("INSERT INTO `unique_contacts` (`url`, `name`, `nick`, `avatar`) VALUES ('%s', '%s', '%s', '%s')",
535                                 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
536
537                         $r = q("SELECT `id` FROM `unique_contacts` WHERE `url`='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
538                 }
539
540                 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
541
542                 $ret = Array(
543                         'id' => intval($r[0]['id']),
544                         'id_str' => (string) intval($r[0]['id']),
545                         'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
546                         'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
547                         'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
548                         'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
549                         'profile_image_url' => $uinfo[0]['micro'],
550                         'profile_image_url_https' => $uinfo[0]['micro'],
551                         'url' => $uinfo[0]['url'],
552                         'protected' => false,
553                         'followers_count' => intval($countfollowers),
554                         'friends_count' => intval($countfriends),
555                         'created_at' => api_date($uinfo[0]['created']),
556                         'favourites_count' => intval($starred),
557                         'utc_offset' => "0",
558                         'time_zone' => 'UTC',
559                         'statuses_count' => intval($countitms),
560                         'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
561                         'verified' => true,
562                         'statusnet_blocking' => false,
563                         'notifications' => false,
564                         //'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
565                         'statusnet_profile_url' => $uinfo[0]['url'],
566                         'uid' => intval($uinfo[0]['uid']),
567                         'cid' => intval($uinfo[0]['cid']),
568                         'self' => $uinfo[0]['self'],
569                         'network' => $uinfo[0]['network'],
570                 );
571
572                 return $ret;
573
574         }
575
576         function api_item_get_user(&$a, $item) {
577
578                 $author = q("SELECT * FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
579                         dbesc(normalise_link($item['author-link'])));
580
581                 if (count($author) == 0) {
582                         q("INSERT INTO `unique_contacts` (`url`, `name`, `avatar`) VALUES ('%s', '%s', '%s')",
583                                 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
584
585                         $author = q("SELECT `id` FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
586                                 dbesc(normalise_link($item['author-link'])));
587                 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
588                         $r = q("SELECT `id` FROM `unique_contacts` WHERE `name` = '%s' AND `avatar` = '%s' AND url = '%s'",
589                                 dbesc($item["author-name"]), dbesc($item["author-avatar"]),
590                                 dbesc(normalise_link($item["author-link"])));
591
592                         if (!$r)
593                                 q("UPDATE `unique_contacts` SET `name` = '%s', `avatar` = '%s' WHERE `url` = '%s'",
594                                         dbesc($item["author-name"]), dbesc($item["author-avatar"]),
595                                         dbesc(normalise_link($item["author-link"])));
596                 }
597
598                 $owner = q("SELECT `id` FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
599                         dbesc(normalise_link($item['owner-link'])));
600
601                 if (count($owner) == 0) {
602                         q("INSERT INTO `unique_contacts` (`url`, `name`, `avatar`) VALUES ('%s', '%s', '%s')",
603                                 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
604
605                         $owner = q("SELECT `id` FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
606                                 dbesc(normalise_link($item['owner-link'])));
607                 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
608                         $r = q("SELECT `id` FROM `unique_contacts` WHERE `name` = '%s' AND `avatar` = '%s' AND url = '%s'",
609                                 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]),
610                                 dbesc(normalise_link($item["owner-link"])));
611
612                         if (!$r)
613                                 q("UPDATE `unique_contacts` SET `name` = '%s', `avatar` = '%s' WHERE `url` = '%s'",
614                                         dbesc($item["owner-name"]), dbesc($item["owner-avatar"]),
615                                         dbesc(normalise_link($item["owner-link"])));
616                 }
617
618                 // Comments in threads may appear as wall-to-wall postings.
619                 // So only take the owner at the top posting.
620                 if ($item["id"] == $item["parent"])
621                         $status_user = api_get_user($a,$item["owner-link"]);
622                 else
623                         $status_user = api_get_user($a,$item["author-link"]);
624
625                 $status_user["protected"] = (($item["allow_cid"] != "") OR
626                                                 ($item["allow_gid"] != "") OR
627                                                 ($item["deny_cid"] != "") OR
628                                                 ($item["deny_gid"] != "") OR
629                                                 $item["private"]);
630
631                 return ($status_user);
632         }
633
634
635         /**
636          *  load api $templatename for $type and replace $data array
637          */
638         function api_apply_template($templatename, $type, $data){
639
640                 $a = get_app();
641
642                 switch($type){
643                         case "atom":
644                         case "rss":
645                         case "xml":
646                                 $data = array_xmlify($data);
647                                 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
648                                 if(! $tpl) {
649                                         header ("Content-Type: text/xml");
650                                         echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
651                                         killme();
652                                 }
653                                 $ret = replace_macros($tpl, $data);
654                                 break;
655                         case "json":
656                                 $ret = $data;
657                                 break;
658                 }
659
660                 return $ret;
661         }
662
663         /**
664          ** TWITTER API
665          */
666
667         /**
668          * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
669          * returns a 401 status code and an error message if not.
670          * http://developer.twitter.com/doc/get/account/verify_credentials
671          */
672         function api_account_verify_credentials(&$a, $type){
673                 if (api_user()===false) return false;
674
675                 unset($_REQUEST["user_id"]);
676                 unset($_GET["user_id"]);
677
678                 unset($_REQUEST["screen_name"]);
679                 unset($_GET["screen_name"]);
680
681                 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
682
683                 $user_info = api_get_user($a);
684
685                 // "verified" isn't used here in the standard
686                 unset($user_info["verified"]);
687
688                 // - Adding last status
689                 if (!$skip_status) {
690                         $user_info["status"] = api_status_show($a,"raw");
691                         if (!count($user_info["status"]))
692                                 unset($user_info["status"]);
693                         else
694                                 unset($user_info["status"]["user"]);
695                 }
696
697                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
698                 unset($user_info["uid"]);
699                 unset($user_info["self"]);
700
701                 return api_apply_template("user", $type, array('$user' => $user_info));
702
703         }
704         api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
705
706
707         /**
708          * get data from $_POST or $_GET
709          */
710         function requestdata($k){
711                 if (isset($_POST[$k])){
712                         return $_POST[$k];
713                 }
714                 if (isset($_GET[$k])){
715                         return $_GET[$k];
716                 }
717                 return null;
718         }
719
720 /*Waitman Gobble Mod*/
721         function api_statuses_mediap(&$a, $type) {
722                 if (api_user()===false) {
723                         logger('api_statuses_update: no user');
724                         return false;
725                 }
726                 $user_info = api_get_user($a);
727
728                 $_REQUEST['type'] = 'wall';
729                 $_REQUEST['profile_uid'] = api_user();
730                 $_REQUEST['api_source'] = true;
731                 $txt = requestdata('status');
732                 //$txt = urldecode(requestdata('status'));
733
734                 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
735
736                         require_once('library/HTMLPurifier.auto.php');
737
738                         $txt = html2bb_video($txt);
739                         $config = HTMLPurifier_Config::createDefault();
740                         $config->set('Cache.DefinitionImpl', null);
741                         $purifier = new HTMLPurifier($config);
742                         $txt = $purifier->purify($txt);
743                 }
744                 $txt = html2bbcode($txt);
745
746                 $a->argv[1]=$user_info['screen_name']; //should be set to username?
747
748                 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
749                 $bebop = wall_upload_post($a);
750
751                 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
752                 $_REQUEST['body']=$txt."\n\n".$bebop;
753                 item_post($a);
754
755                 // this should output the last post (the one we just posted).
756                 return api_status_show($a,$type);
757         }
758         api_register_func('api/statuses/mediap','api_statuses_mediap', true);
759 /*Waitman Gobble Mod*/
760
761
762         function api_statuses_update(&$a, $type) {
763                 if (api_user()===false) {
764                         logger('api_statuses_update: no user');
765                         return false;
766                 }
767
768                 $user_info = api_get_user($a);
769
770                 // convert $_POST array items to the form we use for web posts.
771
772                 // logger('api_post: ' . print_r($_POST,true));
773
774                 if(requestdata('htmlstatus')) {
775                         $txt = requestdata('htmlstatus');
776                         if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
777
778                                 require_once('library/HTMLPurifier.auto.php');
779
780                                 $txt = html2bb_video($txt);
781
782                                 $config = HTMLPurifier_Config::createDefault();
783                                 $config->set('Cache.DefinitionImpl', null);
784
785                                 $purifier = new HTMLPurifier($config);
786                                 $txt = $purifier->purify($txt);
787
788                                 $_REQUEST['body'] = html2bbcode($txt);
789                         }
790
791                 } else
792                         $_REQUEST['body'] = requestdata('status');
793
794                 $_REQUEST['title'] = requestdata('title');
795
796                 $parent = requestdata('in_reply_to_status_id');
797
798                 // Twidere sends "-1" if it is no reply ...
799                 if ($parent == -1)
800                         $parent = "";
801
802                 if(ctype_digit($parent))
803                         $_REQUEST['parent'] = $parent;
804                 else
805                         $_REQUEST['parent_uri'] = $parent;
806
807                 if(requestdata('lat') && requestdata('long'))
808                         $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
809                 $_REQUEST['profile_uid'] = api_user();
810
811                 if($parent)
812                         $_REQUEST['type'] = 'net-comment';
813                 else {
814                         // Check for throttling (maximum posts per day, week and month)
815                         $throttle_day = get_config('system','throttle_limit_day');
816                         if ($throttle_day > 0) {
817                                 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
818
819                                 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
820                                         AND `created` > '%s' AND `id` = `parent`",
821                                         intval(api_user()), dbesc($datefrom));
822
823                                 if ($r)
824                                         $posts_day = $r[0]["posts_day"];
825                                 else
826                                         $posts_day = 0;
827
828                                 if ($posts_day > $throttle_day) {
829                                         logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
830                                         die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
831                                 }
832                         }
833
834                         $throttle_week = get_config('system','throttle_limit_week');
835                         if ($throttle_week > 0) {
836                                 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
837
838                                 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
839                                         AND `created` > '%s' AND `id` = `parent`",
840                                         intval(api_user()), dbesc($datefrom));
841
842                                 if ($r)
843                                         $posts_week = $r[0]["posts_week"];
844                                 else
845                                         $posts_week = 0;
846
847                                 if ($posts_week > $throttle_week) {
848                                         logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
849                                         die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
850                                 }
851                         }
852
853                         $throttle_month = get_config('system','throttle_limit_month');
854                         if ($throttle_month > 0) {
855                                 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
856
857                                 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
858                                         AND `created` > '%s' AND `id` = `parent`",
859                                         intval(api_user()), dbesc($datefrom));
860
861                                 if ($r)
862                                         $posts_month = $r[0]["posts_month"];
863                                 else
864                                         $posts_month = 0;
865
866                                 if ($posts_month > $throttle_month) {
867                                         logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
868                                         die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
869                                 }
870                         }
871
872                         $_REQUEST['type'] = 'wall';
873                 }
874
875                 if(x($_FILES,'media')) {
876                         // upload the image if we have one
877                         $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
878                         $media = wall_upload_post($a);
879                         if(strlen($media)>0)
880                                 $_REQUEST['body'] .= "\n\n".$media;
881                 }
882
883                 // To-Do: Multiple IDs
884                 if (requestdata('media_ids')) {
885                         $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",
886                                 intval(requestdata('media_ids')), api_user());
887                         if ($r) {
888                                 $phototypes = Photo::supportedTypes();
889                                 $ext = $phototypes[$r[0]['type']];
890                                 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
891                                 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
892                         }
893                 }
894
895                 // set this so that the item_post() function is quiet and doesn't redirect or emit json
896
897                 $_REQUEST['api_source'] = true;
898
899                 if (!x($_REQUEST, "source"))
900                         $_REQUEST["source"] = api_source();
901
902                 // call out normal post function
903
904                 item_post($a);
905
906                 // this should output the last post (the one we just posted).
907                 return api_status_show($a,$type);
908         }
909         api_register_func('api/statuses/update','api_statuses_update', true);
910         api_register_func('api/statuses/update_with_media','api_statuses_update', true);
911
912
913         function api_media_upload(&$a, $type) {
914                 if (api_user()===false) {
915                         logger('no user');
916                         return false;
917                 }
918
919                 $user_info = api_get_user($a);
920
921                 if(!x($_FILES,'media')) {
922                         // Output error
923                         return false;
924                 }
925
926                 $media = wall_upload_post($a, false);
927                 if(!$media) {
928                         // Output error
929                         return false;
930                 }
931
932                 $returndata = array();
933                 $returndata["media_id"] = $media["id"];
934                 $returndata["media_id_string"] = (string)$media["id"];
935                 $returndata["size"] = $media["size"];
936                 $returndata["image"] = array("w" => $media["width"],
937                                                 "h" => $media["height"],
938                                                 "image_type" => $media["type"]);
939
940                 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
941
942                 return array("media" => $returndata);
943         }
944
945         api_register_func('api/media/upload','api_media_upload', true);
946
947         function api_status_show(&$a, $type){
948                 $user_info = api_get_user($a);
949
950                 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
951
952                 if ($type == "raw")
953                         $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
954                 else
955                         $privacy_sql = "";
956
957                 // get last public wall message
958                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
959                                 FROM `item`, `item` as `i`
960                                 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
961                                         AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
962                                         AND `i`.`id` = `item`.`parent`
963                                         AND `item`.`type`!='activity' $privacy_sql
964                                 ORDER BY `item`.`created` DESC
965                                 LIMIT 1",
966                                 intval($user_info['cid']),
967                                 intval(api_user()),
968                                 dbesc($user_info['url']),
969                                 dbesc(normalise_link($user_info['url'])),
970                                 dbesc($user_info['url']),
971                                 dbesc(normalise_link($user_info['url']))
972                 );
973
974                 if (count($lastwall)>0){
975                         $lastwall = $lastwall[0];
976
977                         $in_reply_to_status_id = NULL;
978                         $in_reply_to_user_id = NULL;
979                         $in_reply_to_status_id_str = NULL;
980                         $in_reply_to_user_id_str = NULL;
981                         $in_reply_to_screen_name = NULL;
982                         if (intval($lastwall['parent']) != intval($lastwall['id'])) {
983                                 $in_reply_to_status_id= intval($lastwall['parent']);
984                                 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
985
986                                 $r = q("SELECT * FROM `unique_contacts` WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
987                                 if ($r) {
988                                         if ($r[0]['nick'] == "")
989                                                 $r[0]['nick'] = api_get_nick($r[0]["url"]);
990
991                                         $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
992                                         $in_reply_to_user_id = intval($r[0]['id']);
993                                         $in_reply_to_user_id_str = (string) intval($r[0]['id']);
994                                 }
995                         }
996
997                         // There seems to be situation, where both fields are identical:
998                         // https://github.com/friendica/friendica/issues/1010
999                         // This is a bugfix for that.
1000                         if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
1001                                 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
1002                                 $in_reply_to_status_id = NULL;
1003                                 $in_reply_to_user_id = NULL;
1004                                 $in_reply_to_status_id_str = NULL;
1005                                 $in_reply_to_user_id_str = NULL;
1006                                 $in_reply_to_screen_name = NULL;
1007                         }
1008
1009                         $converted = api_convert_item($lastwall);
1010
1011                         $status_info = array(
1012                                 'created_at' => api_date($lastwall['created']),
1013                                 'id' => intval($lastwall['id']),
1014                                 'id_str' => (string) $lastwall['id'],
1015                                 'text' => $converted["text"],
1016                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1017                                 'truncated' => false,
1018                                 'in_reply_to_status_id' => $in_reply_to_status_id,
1019                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1020                                 'in_reply_to_user_id' => $in_reply_to_user_id,
1021                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1022                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1023                                 'user' => $user_info,
1024                                 'geo' => NULL,
1025                                 'coordinates' => "",
1026                                 'place' => "",
1027                                 'contributors' => "",
1028                                 'is_quote_status' => false,
1029                                 'retweet_count' => 0,
1030                                 'favorite_count' => 0,
1031                                 'favorited' => $lastwall['starred'] ? true : false,
1032                                 'retweeted' => false,
1033                                 'possibly_sensitive' => false,
1034                                 'lang' => "",
1035                                 'statusnet_html'                => $converted["html"],
1036                                 'statusnet_conversation_id'     => $lastwall['parent'],
1037                         );
1038
1039                         if (count($converted["attachments"]) > 0)
1040                                 $status_info["attachments"] = $converted["attachments"];
1041
1042                         if (count($converted["entities"]) > 0)
1043                                 $status_info["entities"] = $converted["entities"];
1044
1045                         if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1046                                 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1047                         elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1048                                 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1049
1050                         // "uid" and "self" are only needed for some internal stuff, so remove it from here
1051                         unset($status_info["user"]["uid"]);
1052                         unset($status_info["user"]["self"]);
1053                 }
1054
1055                 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1056
1057                 if ($type == "raw")
1058                         return($status_info);
1059
1060                 return  api_apply_template("status", $type, array('$status' => $status_info));
1061
1062         }
1063
1064
1065
1066
1067
1068         /**
1069          * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1070          * The author's most recent status will be returned inline.
1071          * http://developer.twitter.com/doc/get/users/show
1072          */
1073         function api_users_show(&$a, $type){
1074                 $user_info = api_get_user($a);
1075
1076                 $lastwall = q("SELECT `item`.*
1077                                 FROM `item`, `contact`
1078                                 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1079                                         AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1080                                         AND `contact`.`id`=`item`.`contact-id`
1081                                         AND `type`!='activity'
1082                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1083                                 ORDER BY `created` DESC
1084                                 LIMIT 1",
1085                                 intval(api_user()),
1086                                 dbesc(ACTIVITY_POST),
1087                                 intval($user_info['cid']),
1088                                 dbesc($user_info['url']),
1089                                 dbesc(normalise_link($user_info['url'])),
1090                                 dbesc($user_info['url']),
1091                                 dbesc(normalise_link($user_info['url']))
1092                 );
1093                 if (count($lastwall)>0){
1094                         $lastwall = $lastwall[0];
1095
1096                         $in_reply_to_status_id = NULL;
1097                         $in_reply_to_user_id = NULL;
1098                         $in_reply_to_status_id_str = NULL;
1099                         $in_reply_to_user_id_str = NULL;
1100                         $in_reply_to_screen_name = NULL;
1101                         if ($lastwall['parent']!=$lastwall['id']) {
1102                                 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1103                                                 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1104                                 if (count($reply)>0) {
1105                                         $in_reply_to_status_id = intval($lastwall['parent']);
1106                                         $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1107
1108                                         $r = q("SELECT * FROM `unique_contacts` WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1109                                         if ($r) {
1110                                                 if ($r[0]['nick'] == "")
1111                                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);
1112
1113                                                 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1114                                                 $in_reply_to_user_id = intval($r[0]['id']);
1115                                                 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1116                                         }
1117                                 }
1118                         }
1119
1120                         $converted = api_convert_item($lastwall);
1121
1122                         $user_info['status'] = array(
1123                                 'text' => $converted["text"],
1124                                 'truncated' => false,
1125                                 'created_at' => api_date($lastwall['created']),
1126                                 'in_reply_to_status_id' => $in_reply_to_status_id,
1127                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1128                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1129                                 'id' => intval($lastwall['contact-id']),
1130                                 'id_str' => (string) $lastwall['contact-id'],
1131                                 'in_reply_to_user_id' => $in_reply_to_user_id,
1132                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1133                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1134                                 'geo' => NULL,
1135                                 'favorited' => $lastwall['starred'] ? true : false,
1136                                 'statusnet_html'                => $converted["html"],
1137                                 'statusnet_conversation_id'     => $lastwall['parent'],
1138                         );
1139
1140                         if (count($converted["attachments"]) > 0)
1141                                 $user_info["status"]["attachments"] = $converted["attachments"];
1142
1143                         if (count($converted["entities"]) > 0)
1144                                 $user_info["status"]["entities"] = $converted["entities"];
1145
1146                         if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1147                                 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1148                         if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1149                                 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1150
1151                 }
1152
1153                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1154                 unset($user_info["uid"]);
1155                 unset($user_info["self"]);
1156
1157                 return  api_apply_template("user", $type, array('$user' => $user_info));
1158
1159         }
1160         api_register_func('api/users/show','api_users_show');
1161
1162
1163         function api_users_search(&$a, $type) {
1164                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1165
1166                 $userlist = array();
1167
1168                 if (isset($_GET["q"])) {
1169                         $r = q("SELECT id FROM `unique_contacts` WHERE `name`='%s'", dbesc($_GET["q"]));
1170                         if (!count($r))
1171                                 $r = q("SELECT `id` FROM `unique_contacts` WHERE `nick`='%s'", dbesc($_GET["q"]));
1172
1173                         if (count($r)) {
1174                                 foreach ($r AS $user) {
1175                                         $user_info = api_get_user($a, $user["id"]);
1176                                         //echo print_r($user_info, true)."\n";
1177                                         $userdata = api_apply_template("user", $type, array('user' => $user_info));
1178                                         $userlist[] = $userdata["user"];
1179                                 }
1180                                 $userlist = array("users" => $userlist);
1181                         } else
1182                                 die(api_error($a, $type, t("User not found.")));
1183                 } else
1184                         die(api_error($a, $type, t("User not found.")));
1185
1186                 return ($userlist);
1187         }
1188
1189         api_register_func('api/users/search','api_users_search');
1190
1191         /**
1192          *
1193          * http://developer.twitter.com/doc/get/statuses/home_timeline
1194          *
1195          * TODO: Optional parameters
1196          * TODO: Add reply info
1197          */
1198         function api_statuses_home_timeline(&$a, $type){
1199                 if (api_user()===false) return false;
1200
1201                 unset($_REQUEST["user_id"]);
1202                 unset($_GET["user_id"]);
1203
1204                 unset($_REQUEST["screen_name"]);
1205                 unset($_GET["screen_name"]);
1206
1207                 $user_info = api_get_user($a);
1208                 // get last newtork messages
1209
1210
1211                 // params
1212                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1213                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1214                 if ($page<0) $page=0;
1215                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1216                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1217                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1218                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1219                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1220
1221                 $start = $page*$count;
1222
1223                 $sql_extra = '';
1224                 if ($max_id > 0)
1225                         $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1226                 if ($exclude_replies > 0)
1227                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1228                 if ($conversation_id > 0)
1229                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1230
1231                 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1232                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1233                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1234                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1235                         FROM `item`, `contact`
1236                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1237                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1238                         AND `contact`.`id` = `item`.`contact-id`
1239                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1240                         $sql_extra
1241                         AND `item`.`id`>%d
1242                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1243                         intval(api_user()),
1244                         dbesc(ACTIVITY_POST),
1245                         intval($since_id),
1246                         intval($start), intval($count)
1247                 );
1248
1249                 $ret = api_format_items($r,$user_info);
1250
1251                 // Set all posts from the query above to seen
1252                 $idarray = array();
1253                 foreach ($r AS $item)
1254                         $idarray[] = intval($item["id"]);
1255
1256                 $idlist = implode(",", $idarray);
1257
1258                 if ($idlist != "")
1259                         $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1260
1261
1262                 $data = array('$statuses' => $ret);
1263                 switch($type){
1264                         case "atom":
1265                         case "rss":
1266                                 $data = api_rss_extra($a, $data, $user_info);
1267                                 break;
1268                         case "as":
1269                                 $as = api_format_as($a, $ret, $user_info);
1270                                 $as['title'] = $a->config['sitename']." Home Timeline";
1271                                 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1272                                 return($as);
1273                                 break;
1274                 }
1275
1276                 return  api_apply_template("timeline", $type, $data);
1277         }
1278         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1279         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1280
1281         function api_statuses_public_timeline(&$a, $type){
1282                 if (api_user()===false) return false;
1283
1284                 $user_info = api_get_user($a);
1285                 // get last newtork messages
1286
1287
1288                 // params
1289                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1290                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1291                 if ($page<0) $page=0;
1292                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1293                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1294                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1295                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1296                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1297
1298                 $start = $page*$count;
1299
1300                 if ($max_id > 0)
1301                         $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1302                 if ($exclude_replies > 0)
1303                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1304                 if ($conversation_id > 0)
1305                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1306
1307                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1308                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1309                         `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1310                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1311                         `user`.`nickname`, `user`.`hidewall`
1312                         FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1313                         STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1314                         WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1315                         AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
1316                         AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
1317                         AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1318                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1319                         $sql_extra
1320                         AND `item`.`id`>%d
1321                         ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1322                         dbesc(ACTIVITY_POST),
1323                         intval($since_id),
1324                         intval($start),
1325                         intval($count));
1326
1327                 $ret = api_format_items($r,$user_info);
1328
1329
1330                 $data = array('$statuses' => $ret);
1331                 switch($type){
1332                         case "atom":
1333                         case "rss":
1334                                 $data = api_rss_extra($a, $data, $user_info);
1335                                 break;
1336                         case "as":
1337                                 $as = api_format_as($a, $ret, $user_info);
1338                                 $as['title'] = $a->config['sitename']." Public Timeline";
1339                                 $as['link']['url'] = $a->get_baseurl()."/";
1340                                 return($as);
1341                                 break;
1342                 }
1343
1344                 return  api_apply_template("timeline", $type, $data);
1345         }
1346         api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1347
1348         /**
1349          *
1350          */
1351         function api_statuses_show(&$a, $type){
1352                 if (api_user()===false) return false;
1353
1354                 $user_info = api_get_user($a);
1355
1356                 // params
1357                 $id = intval($a->argv[3]);
1358
1359                 if ($id == 0)
1360                         $id = intval($_REQUEST["id"]);
1361
1362                 // Hotot workaround
1363                 if ($id == 0)
1364                         $id = intval($a->argv[4]);
1365
1366                 logger('API: api_statuses_show: '.$id);
1367
1368                 $conversation = (x($_REQUEST,'conversation')?1:0);
1369
1370                 $sql_extra = '';
1371                 if ($conversation)
1372                         $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1373                 else
1374                         $sql_extra .= " AND `item`.`id` = %d";
1375
1376                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1377                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1378                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1379                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1380                         FROM `item`, `contact`
1381                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1382                         AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1383                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1384                         $sql_extra",
1385                         intval(api_user()),
1386                         dbesc(ACTIVITY_POST),
1387                         intval($id)
1388                 );
1389
1390                 if (!$r)
1391                         die(api_error($a, $type, t("There is no status with this id.")));
1392
1393                 $ret = api_format_items($r,$user_info);
1394
1395                 if ($conversation) {
1396                         $data = array('$statuses' => $ret);
1397                         return api_apply_template("timeline", $type, $data);
1398                 } else {
1399                         $data = array('$status' => $ret[0]);
1400                         /*switch($type){
1401                                 case "atom":
1402                                 case "rss":
1403                                         $data = api_rss_extra($a, $data, $user_info);
1404                         }*/
1405                         return  api_apply_template("status", $type, $data);
1406                 }
1407         }
1408         api_register_func('api/statuses/show','api_statuses_show', true);
1409
1410
1411         /**
1412          *
1413          */
1414         function api_conversation_show(&$a, $type){
1415                 if (api_user()===false) return false;
1416
1417                 $user_info = api_get_user($a);
1418
1419                 // params
1420                 $id = intval($a->argv[3]);
1421                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1422                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1423                 if ($page<0) $page=0;
1424                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1425                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1426
1427                 $start = $page*$count;
1428
1429                 if ($id == 0)
1430                         $id = intval($_REQUEST["id"]);
1431
1432                 // Hotot workaround
1433                 if ($id == 0)
1434                         $id = intval($a->argv[4]);
1435
1436                 logger('API: api_conversation_show: '.$id);
1437
1438                 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1439                 if ($r)
1440                         $id = $r[0]["parent"];
1441
1442                 $sql_extra = '';
1443
1444                 if ($max_id > 0)
1445                         $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1446
1447                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1448                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1449                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1450                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1451                         FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1452                         ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1453                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1454                         AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1455                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1456                         AND `item`.`id`>%d $sql_extra
1457                         ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1458                         intval($id), intval(api_user()),
1459                         dbesc(ACTIVITY_POST),
1460                         intval($since_id),
1461                         intval($start), intval($count)
1462                 );
1463
1464                 if (!$r)
1465                         die(api_error($a, $type, t("There is no conversation with this id.")));
1466
1467                 $ret = api_format_items($r,$user_info);
1468
1469                 $data = array('$statuses' => $ret);
1470                 return api_apply_template("timeline", $type, $data);
1471         }
1472         api_register_func('api/conversation/show','api_conversation_show', true);
1473
1474
1475         /**
1476          *
1477          */
1478         function api_statuses_repeat(&$a, $type){
1479                 global $called_api;
1480
1481                 if (api_user()===false) return false;
1482
1483                 $user_info = api_get_user($a);
1484
1485                 // params
1486                 $id = intval($a->argv[3]);
1487
1488                 if ($id == 0)
1489                         $id = intval($_REQUEST["id"]);
1490
1491                 // Hotot workaround
1492                 if ($id == 0)
1493                         $id = intval($a->argv[4]);
1494
1495                 logger('API: api_statuses_repeat: '.$id);
1496
1497                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1498                         `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1499                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1500                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1501                         FROM `item`, `contact`
1502                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1503                         AND `contact`.`id` = `item`.`contact-id`
1504                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1505                         $sql_extra
1506                         AND `item`.`id`=%d",
1507                         intval($id)
1508                 );
1509
1510                 if ($r[0]['body'] != "") {
1511                         if (!intval(get_config('system','old_share'))) {
1512                                 if (strpos($r[0]['body'], "[/share]") !== false) {
1513                                         $pos = strpos($r[0]['body'], "[share");
1514                                         $post = substr($r[0]['body'], $pos);
1515                                 } else {
1516                                         $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1517
1518                                         $post .= $r[0]['body'];
1519                                         $post .= "[/share]";
1520                                 }
1521                                 $_REQUEST['body'] = $post;
1522                         } else
1523                                 $_REQUEST['body'] = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1524
1525                         $_REQUEST['profile_uid'] = api_user();
1526                         $_REQUEST['type'] = 'wall';
1527                         $_REQUEST['api_source'] = true;
1528
1529                         if (!x($_REQUEST, "source"))
1530                                 $_REQUEST["source"] = api_source();
1531
1532                         item_post($a);
1533                 }
1534
1535                 // this should output the last post (the one we just posted).
1536                 $called_api = null;
1537                 return(api_status_show($a,$type));
1538         }
1539         api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1540
1541         /**
1542          *
1543          */
1544         function api_statuses_destroy(&$a, $type){
1545                 if (api_user()===false) return false;
1546
1547                 $user_info = api_get_user($a);
1548
1549                 // params
1550                 $id = intval($a->argv[3]);
1551
1552                 if ($id == 0)
1553                         $id = intval($_REQUEST["id"]);
1554
1555                 // Hotot workaround
1556                 if ($id == 0)
1557                         $id = intval($a->argv[4]);
1558
1559                 logger('API: api_statuses_destroy: '.$id);
1560
1561                 $ret = api_statuses_show($a, $type);
1562
1563                 drop_item($id, false);
1564
1565                 return($ret);
1566         }
1567         api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1568
1569         /**
1570          *
1571          * http://developer.twitter.com/doc/get/statuses/mentions
1572          *
1573          */
1574         function api_statuses_mentions(&$a, $type){
1575                 if (api_user()===false) return false;
1576
1577                 unset($_REQUEST["user_id"]);
1578                 unset($_GET["user_id"]);
1579
1580                 unset($_REQUEST["screen_name"]);
1581                 unset($_GET["screen_name"]);
1582
1583                 $user_info = api_get_user($a);
1584                 // get last newtork messages
1585
1586
1587                 // params
1588                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1589                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1590                 if ($page<0) $page=0;
1591                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1592                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1593                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1594
1595                 $start = $page*$count;
1596
1597                 // Ugly code - should be changed
1598                 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1599                 $myurl = substr($myurl,strpos($myurl,'://')+3);
1600                 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1601                 $myurl = str_replace('www.','',$myurl);
1602                 $diasp_url = str_replace('/profile/','/u/',$myurl);
1603
1604                 if ($max_id > 0)
1605                         $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1606
1607                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1608                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1609                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1610                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1611                         FROM `item`, `contact`
1612                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1613                         AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1614                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1615                         AND `contact`.`id` = `item`.`contact-id`
1616                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1617                         AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1618                         $sql_extra
1619                         AND `item`.`id`>%d
1620                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1621                         intval(api_user()),
1622                         dbesc(ACTIVITY_POST),
1623                         dbesc(protect_sprintf($myurl)),
1624                         dbesc(protect_sprintf($myurl)),
1625                         intval(api_user()),
1626                         intval($since_id),
1627                         intval($start), intval($count)
1628                 );
1629
1630                 $ret = api_format_items($r,$user_info);
1631
1632
1633                 $data = array('$statuses' => $ret);
1634                 switch($type){
1635                         case "atom":
1636                         case "rss":
1637                                 $data = api_rss_extra($a, $data, $user_info);
1638                                 break;
1639                         case "as":
1640                                 $as = api_format_as($a, $ret, $user_info);
1641                                 $as["title"] = $a->config['sitename']." Mentions";
1642                                 $as['link']['url'] = $a->get_baseurl()."/";
1643                                 return($as);
1644                                 break;
1645                 }
1646
1647                 return  api_apply_template("timeline", $type, $data);
1648         }
1649         api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1650         api_register_func('api/statuses/replies','api_statuses_mentions', true);
1651
1652
1653         function api_statuses_user_timeline(&$a, $type){
1654                 if (api_user()===false) return false;
1655
1656                 $user_info = api_get_user($a);
1657                 // get last network messages
1658
1659                 logger("api_statuses_user_timeline: api_user: ". api_user() .
1660                            "\nuser_info: ".print_r($user_info, true) .
1661                            "\n_REQUEST:  ".print_r($_REQUEST, true),
1662                            LOGGER_DEBUG);
1663
1664                 // params
1665                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1666                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1667                 if ($page<0) $page=0;
1668                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1669                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1670                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1671                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1672
1673                 $start = $page*$count;
1674
1675                 $sql_extra = '';
1676                 if ($user_info['self']==1)
1677                         $sql_extra .= " AND `item`.`wall` = 1 ";
1678
1679                 if ($exclude_replies > 0)
1680                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1681                 if ($conversation_id > 0)
1682                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1683
1684                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1685                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1686                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1687                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1688                         FROM `item`, `contact`
1689                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1690                         AND `item`.`contact-id` = %d
1691                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1692                         AND `contact`.`id` = `item`.`contact-id`
1693                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1694                         $sql_extra
1695                         AND `item`.`id`>%d
1696                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1697                         intval(api_user()),
1698                         dbesc(ACTIVITY_POST),
1699                         intval($user_info['cid']),
1700                         intval($since_id),
1701                         intval($start), intval($count)
1702                 );
1703
1704                 $ret = api_format_items($r,$user_info, true);
1705
1706                 $data = array('$statuses' => $ret);
1707                 switch($type){
1708                         case "atom":
1709                         case "rss":
1710                                 $data = api_rss_extra($a, $data, $user_info);
1711                 }
1712
1713                 return  api_apply_template("timeline", $type, $data);
1714         }
1715
1716         api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1717
1718
1719         /**
1720          * Star/unstar an item
1721          * param: id : id of the item
1722          *
1723          * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1724          */
1725         function api_favorites_create_destroy(&$a, $type){
1726                 if (api_user()===false) return false;
1727
1728                 # for versioned api.
1729                 # TODO: we need a better global soluton
1730                 $action_argv_id=2;
1731                 if ($a->argv[1]=="1.1") $action_argv_id=3;
1732
1733                 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1734                 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1735                 if ($a->argc==$action_argv_id+2) {
1736                         $itemid = intval($a->argv[$action_argv_id+1]);
1737                 } else {
1738                         $itemid = intval($_REQUEST['id']);
1739                 }
1740
1741                 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1742                                 $itemid, api_user());
1743
1744                 if ($item===false || count($item)==0) die(api_error($a, $type, t("Invalid item.")));
1745
1746                 switch($action){
1747                         case "create":
1748                                 $item[0]['starred']=1;
1749                                 break;
1750                         case "destroy":
1751                                 $item[0]['starred']=0;
1752                                 break;
1753                         default:
1754                                 die(api_error($a, $type, t("Invalid action. ".$action)));
1755                 }
1756                 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1757                                 $item[0]['starred'], $itemid, api_user());
1758
1759                 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1760                         $item[0]['starred'], $itemid, api_user());
1761
1762                 if ($r===false) die(api_error($a, $type, t("DB error")));
1763
1764
1765                 $user_info = api_get_user($a);
1766                 $rets = api_format_items($item,$user_info);
1767                 $ret = $rets[0];
1768
1769                 $data = array('$status' => $ret);
1770                 switch($type){
1771                         case "atom":
1772                         case "rss":
1773                                 $data = api_rss_extra($a, $data, $user_info);
1774                 }
1775
1776                 return api_apply_template("status", $type, $data);
1777         }
1778
1779         api_register_func('api/favorites/create', 'api_favorites_create_destroy', true);
1780         api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true);
1781
1782         function api_favorites(&$a, $type){
1783                 global $called_api;
1784
1785                 if (api_user()===false) return false;
1786
1787                 $called_api= array();
1788
1789                 $user_info = api_get_user($a);
1790
1791                 // in friendica starred item are private
1792                 // return favorites only for self
1793                 logger('api_favorites: self:' . $user_info['self']);
1794
1795                 if ($user_info['self']==0) {
1796                         $ret = array();
1797                 } else {
1798                         $sql_extra = "";
1799
1800                         // params
1801                         $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1802                         $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1803                         $count = (x($_GET,'count')?$_GET['count']:20);
1804                         $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1805                         if ($page<0) $page=0;
1806
1807                         $start = $page*$count;
1808
1809                         if ($max_id > 0)
1810                                 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1811
1812                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1813                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1814                                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1815                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1816                                 FROM `item`, `contact`
1817                                 WHERE `item`.`uid` = %d
1818                                 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1819                                 AND `item`.`starred` = 1
1820                                 AND `contact`.`id` = `item`.`contact-id`
1821                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1822                                 $sql_extra
1823                                 AND `item`.`id`>%d
1824                                 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1825                                 intval(api_user()),
1826                                 intval($since_id),
1827                                 intval($start), intval($count)
1828                         );
1829
1830                         $ret = api_format_items($r,$user_info);
1831
1832                 }
1833
1834                 $data = array('$statuses' => $ret);
1835                 switch($type){
1836                         case "atom":
1837                         case "rss":
1838                                 $data = api_rss_extra($a, $data, $user_info);
1839                 }
1840
1841                 return  api_apply_template("timeline", $type, $data);
1842         }
1843
1844         api_register_func('api/favorites','api_favorites', true);
1845
1846
1847
1848
1849         function api_format_as($a, $ret, $user_info) {
1850
1851                 $as = array();
1852                 $as['title'] = $a->config['sitename']." Public Timeline";
1853                 $items = array();
1854                 foreach ($ret as $item) {
1855                         $singleitem["actor"]["displayName"] = $item["user"]["name"];
1856                         $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1857                         $avatar[0]["url"] = $item["user"]["profile_image_url"];
1858                         $avatar[0]["rel"] = "avatar";
1859                         $avatar[0]["type"] = "";
1860                         $avatar[0]["width"] = 96;
1861                         $avatar[0]["height"] = 96;
1862                         $avatar[1]["url"] = $item["user"]["profile_image_url"];
1863                         $avatar[1]["rel"] = "avatar";
1864                         $avatar[1]["type"] = "";
1865                         $avatar[1]["width"] = 48;
1866                         $avatar[1]["height"] = 48;
1867                         $avatar[2]["url"] = $item["user"]["profile_image_url"];
1868                         $avatar[2]["rel"] = "avatar";
1869                         $avatar[2]["type"] = "";
1870                         $avatar[2]["width"] = 24;
1871                         $avatar[2]["height"] = 24;
1872                         $singleitem["actor"]["avatarLinks"] = $avatar;
1873
1874                         $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1875                         $singleitem["actor"]["image"]["rel"] = "avatar";
1876                         $singleitem["actor"]["image"]["type"] = "";
1877                         $singleitem["actor"]["image"]["width"] = 96;
1878                         $singleitem["actor"]["image"]["height"] = 96;
1879                         $singleitem["actor"]["type"] = "person";
1880                         $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1881                         $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1882                         $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1883                         $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1884                         $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1885                         $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1886                         $singleitem["actor"]["contact"]["addresses"] = "";
1887
1888                         $singleitem["body"] = $item["text"];
1889                         $singleitem["object"]["displayName"] = $item["text"];
1890                         $singleitem["object"]["id"] = $item["url"];
1891                         $singleitem["object"]["type"] = "note";
1892                         $singleitem["object"]["url"] = $item["url"];
1893                         //$singleitem["context"] =;
1894                         $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1895                         $singleitem["provider"]["objectType"] = "service";
1896                         $singleitem["provider"]["displayName"] = "Test";
1897                         $singleitem["provider"]["url"] = "http://test.tld";
1898                         $singleitem["title"] = $item["text"];
1899                         $singleitem["verb"] = "post";
1900                         $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1901                         $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1902                         $singleitem["statusnet:notice_info"]["favorite"] = "false";
1903                         $singleitem["statusnet:notice_info"]["repeated"] = "false";
1904                         //$singleitem["original"] = $item;
1905                         $items[] = $singleitem;
1906                 }
1907                 $as['items'] = $items;
1908                 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1909                 $as['link']['rel'] = "alternate";
1910                 $as['link']['type'] = "text/html";
1911                 return($as);
1912         }
1913
1914         function api_format_messages($item, $recipient, $sender) {
1915                 // standard meta information
1916                 $ret=Array(
1917                                 'id'                    => $item['id'],
1918                                 'sender_id'             => $sender['id'] ,
1919                                 'text'                  => "",
1920                                 'recipient_id'          => $recipient['id'],
1921                                 'created_at'            => api_date($item['created']),
1922                                 'sender_screen_name'    => $sender['screen_name'],
1923                                 'recipient_screen_name' => $recipient['screen_name'],
1924                                 'sender'                => $sender,
1925                                 'recipient'             => $recipient,
1926                 );
1927
1928                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1929                 unset($ret["sender"]["uid"]);
1930                 unset($ret["sender"]["self"]);
1931                 unset($ret["recipient"]["uid"]);
1932                 unset($ret["recipient"]["self"]);
1933
1934                 //don't send title to regular StatusNET requests to avoid confusing these apps
1935                 if (x($_GET, 'getText')) {
1936                         $ret['title'] = $item['title'] ;
1937                         if ($_GET["getText"] == "html") {
1938                                 $ret['text'] = bbcode($item['body'], false, false);
1939                         }
1940                         elseif ($_GET["getText"] == "plain") {
1941                                 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1942                                 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1943                         }
1944                 }
1945                 else {
1946                         $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1947                 }
1948                 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1949                         unset($ret['sender']);
1950                         unset($ret['recipient']);
1951                 }
1952
1953                 return $ret;
1954         }
1955
1956         function api_convert_item($item) {
1957
1958                 $body = $item['body'];
1959                 $attachments = api_get_attachments($body);
1960
1961                 // Workaround for ostatus messages where the title is identically to the body
1962                 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
1963                 $statusbody = trim(html2plain($html, 0));
1964
1965                 // handle data: images
1966                 $statusbody = api_format_items_embeded_images($item,$statusbody);
1967
1968                 $statustitle = trim($item['title']);
1969
1970                 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1971                         $statustext = trim($statusbody);
1972                 else
1973                         $statustext = trim($statustitle."\n\n".$statusbody);
1974
1975                 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1976                         $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1977
1978                 $statushtml = trim(bbcode($body, false, false));
1979
1980                 if ($item['title'] != "")
1981                         $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
1982
1983                 $entities = api_get_entitities($statustext, $body);
1984
1985                 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
1986         }
1987
1988         function api_get_attachments(&$body) {
1989
1990                 $text = $body;
1991                 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1992
1993                 $URLSearchString = "^\[\]";
1994                 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
1995
1996                 if (!$ret)
1997                         return false;
1998
1999                 $attachments = array();
2000
2001                 foreach ($images[1] AS $image) {
2002                         $imagedata = get_photo_info($image);
2003
2004                         if ($imagedata)
2005                                 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2006                 }
2007
2008                 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2009                         foreach ($images[0] AS $orig)
2010                                 $body = str_replace($orig, "", $body);
2011
2012                 return $attachments;
2013         }
2014
2015         function api_get_entitities(&$text, $bbcode) {
2016                 /*
2017                 To-Do:
2018                 * Links at the first character of the post
2019                 */
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 /* To-Do:
2875  - remove trailing junk from profile url
2876  - pump.io check has to check the website
2877 */
2878
2879         $nick = "";
2880
2881         $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
2882                 dbesc(normalise_link($profile)));
2883         if ($r)
2884                 $nick = $r[0]["nick"];
2885
2886         if (!$nick == "") {
2887                 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
2888                         dbesc(normalise_link($profile)));
2889                 if ($r)
2890                         $nick = $r[0]["nick"];
2891         }
2892
2893         if (!$nick == "") {
2894                 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2895                 if ($friendica != $profile)
2896                         $nick = $friendica;
2897         }
2898
2899         if (!$nick == "") {
2900                 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2901                 if ($diaspora != $profile)
2902                         $nick = $diaspora;
2903         }
2904
2905         if (!$nick == "") {
2906                 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2907                 if ($twitter != $profile)
2908                         $nick = $twitter;
2909         }
2910
2911
2912         if (!$nick == "") {
2913                 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2914                 if ($StatusnetHost != $profile) {
2915                         $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2916                         if ($StatusnetUser != $profile) {
2917                                 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2918                                 $user = json_decode($UserData);
2919                                 if ($user)
2920                                         $nick = $user->screen_name;
2921                         }
2922                 }
2923         }
2924
2925         // To-Do: look at the page if its really a pumpio site
2926         //if (!$nick == "") {
2927         //      $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2928         //      if ($pumpio != $profile)
2929         //              $nick = $pumpio;
2930                 //      <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2931
2932         //}
2933
2934         if ($nick != "") {
2935                 q("UPDATE `unique_contacts` SET `nick` = '%s' WHERE `nick` != '%s' AND url = '%s'",
2936                         dbesc($nick), dbesc($nick), dbesc(normalise_link($profile)));
2937                 return($nick);
2938         }
2939
2940         return(false);
2941 }
2942
2943 function api_clean_plain_items($Text) {
2944         $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2945
2946         $Text = bb_CleanPictureLinks($Text);
2947
2948         $URLSearchString = "^\[\]";
2949
2950         $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2951
2952         if ($include_entities == "true") {
2953                 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2954         }
2955
2956         $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2957         return($Text);
2958 }
2959
2960 function api_cleanup_share($shared) {
2961         if ($shared[2] != "type-link")
2962                 return($shared[0]);
2963
2964         if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2965                 return($shared[0]);
2966
2967         $title = "";
2968         $link = "";
2969
2970         if (isset($bookmark[2][0]))
2971                 $title = $bookmark[2][0];
2972
2973         if (isset($bookmark[1][0]))
2974                 $link = $bookmark[1][0];
2975
2976         if (strpos($shared[1],$title) !== false)
2977                 $title = "";
2978
2979         if (strpos($shared[1],$link) !== false)
2980                 $link = "";
2981
2982         $text = trim($shared[1]);
2983
2984         //if (strlen($text) < strlen($title))
2985         if (($text == "") AND ($title != ""))
2986                 $text .= "\n\n".trim($title);
2987
2988         if ($link != "")
2989                 $text .= "\n".trim($link);
2990
2991         return(trim($text));
2992 }
2993
2994 function api_best_nickname(&$contacts) {
2995         $best_contact = array();
2996
2997         if (count($contact) == 0)
2998                 return;
2999
3000         foreach ($contacts AS $contact)
3001                 if ($contact["network"] == "") {
3002                         $contact["network"] = "dfrn";
3003                         $best_contact = array($contact);
3004                 }
3005
3006         if (sizeof($best_contact) == 0)
3007                 foreach ($contacts AS $contact)
3008                         if ($contact["network"] == "dfrn")
3009                                 $best_contact = array($contact);
3010
3011         if (sizeof($best_contact) == 0)
3012                 foreach ($contacts AS $contact)
3013                         if ($contact["network"] == "dspr")
3014                                 $best_contact = array($contact);
3015
3016         if (sizeof($best_contact) == 0)
3017                 foreach ($contacts AS $contact)
3018                         if ($contact["network"] == "stat")
3019                                 $best_contact = array($contact);
3020
3021         if (sizeof($best_contact) == 0)
3022                 foreach ($contacts AS $contact)
3023                         if ($contact["network"] == "pump")
3024                                 $best_contact = array($contact);
3025
3026         if (sizeof($best_contact) == 0)
3027                 foreach ($contacts AS $contact)
3028                         if ($contact["network"] == "twit")
3029                                 $best_contact = array($contact);
3030
3031         if (sizeof($best_contact) == 1)
3032                 $contacts = $best_contact;
3033         else
3034                 $contacts = array($contacts[0]);
3035 }
3036
3037         // return all or a specified group of the user with the containing contacts
3038         function api_friendica_group_show(&$a, $type) {
3039                 if (api_user()===false) return false;           
3040
3041                 // params
3042                 $user_info = api_get_user($a);
3043                 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3044                 $uid = $user_info['uid'];
3045         
3046                 // get data of the specified group id or all groups if not specified
3047                 if ($gid != 0) {
3048                         $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3049                                 intval($uid), 
3050                                 intval($gid));
3051                         // error message if specified gid is not in database
3052                         if (count($r) == 0) 
3053                                 die(api_error($a, $type, 'gid not available'));
3054                 }
3055                 else 
3056                         $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3057                                 intval($uid));
3058                 
3059                 // loop through all groups and retrieve all members for adding data in the user array
3060                 foreach ($r as $rr) {
3061                         $members = group_get_members($rr['id']);
3062                         $users = array();
3063                         foreach ($members as $member) {
3064                                 $user = api_get_user($a, $member['nurl']);
3065                                 $users[] = $user;
3066                         }
3067                         $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], 'user' => $users);
3068                 }
3069                 return api_apply_template("group_show", $type, array('$groups' => $grps));
3070         }
3071         api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3072
3073
3074         // delete the specified group of the user
3075         function api_friendica_group_delete(&$a, $type) {
3076                 if (api_user()===false) return false;           
3077
3078                 // params
3079                 $user_info = api_get_user($a);
3080                 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3081                 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3082                 $uid = $user_info['uid'];
3083         
3084                 // error if no gid specified
3085                 if ($gid == 0 || $name == "")
3086                         die(api_error($a, $type, 'gid or name not specified'));
3087
3088                 // get data of the specified group id
3089                 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3090                         intval($uid), 
3091                         intval($gid));
3092                 // error message if specified gid is not in database
3093                 if (count($r) == 0) 
3094                         die(api_error($a, $type, 'gid not available'));
3095
3096                 // get data of the specified group id and group name
3097                 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3098                         intval($uid), 
3099                         intval($gid),
3100                         dbesc($name));
3101                 // error message if specified gid is not in database
3102                 if (count($rname) == 0) 
3103                         die(api_error($a, $type, 'wrong group name'));
3104
3105                 // delete group
3106                 $ret = group_rmv($uid, $name);
3107                 if ($ret) {
3108                         // return success
3109                         $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3110                         return api_apply_template("group_delete", $type, array('$result' => $success));
3111                 }
3112                 else
3113                         die(api_error($a, $type, 'other API error'));
3114         }
3115         api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true);
3116
3117
3118         // create the specified group with the posted array of contacts 
3119         function api_friendica_group_create(&$a, $type) {
3120                 if (api_user()===false) return false;           
3121
3122                 // params
3123                 $user_info = api_get_user($a);
3124                 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3125                 $uid = $user_info['uid'];
3126                 $json = json_decode($_POST['json'], true);
3127                 $users = $json['user'];
3128
3129                 // error if no name specified
3130                 if ($name == "")
3131                         die(api_error($a, $type, 'group name not specified'));
3132
3133                 // get data of the specified group name
3134                 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3135                         intval($uid), 
3136                         dbesc($name));
3137                 // error message if specified group name already exists
3138                 if (count($rname) != 0) 
3139                         die(api_error($a, $type, 'group name already exists'));
3140
3141                 // check if specified group name is a deleted group
3142                 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3143                         intval($uid), 
3144                         dbesc($name));
3145                 // error message if specified group name already exists
3146                 if (count($rname) != 0) 
3147                         $reactivate_group = true;
3148
3149                 // create group
3150                 $ret = group_add($uid, $name);
3151                 if ($ret) 
3152                         $gid = group_byname($uid, $name);
3153                 else
3154                         die(api_error($a, $type, 'other API error'));
3155                 
3156                 // add members
3157                 $erroraddinguser = false;
3158                 $errorusers = array();
3159                 foreach ($users as $user) {
3160                         $cid = $user['cid'];
3161                         // check if user really exists as contact
3162                         $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d", 
3163                                 intval($cid),
3164                                 intval($uid));
3165                         if (count($contact))
3166                                 $result = group_add_member($uid, $name, $cid, $gid);
3167                         else {
3168                                 $erroraddinguser = true;
3169                                 $errorusers[] = $cid;
3170                         }
3171                 }
3172
3173                 // return success message incl. missing users in array
3174                 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3175                 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3176                 return api_apply_template("group_create", $type, array('result' => $success));          
3177         }
3178         api_register_func('api/friendica/group_create', 'api_friendica_group_create', true);
3179
3180
3181         // update the specified group with the posted array of contacts 
3182         function api_friendica_group_update(&$a, $type) {
3183                 if (api_user()===false) return false;           
3184
3185                 // params
3186                 $user_info = api_get_user($a);
3187                 $uid = $user_info['uid'];
3188                 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3189                 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3190                 $json = json_decode($_POST['json'], true);
3191                 $users = $json['user'];
3192
3193                 // error if no name specified
3194                 if ($name == "")
3195                         die(api_error($a, $type, 'group name not specified'));
3196
3197                 // error if no gid specified
3198                 if ($gid == "")
3199                         die(api_error($a, $type, 'gid not specified'));
3200
3201                 // remove members
3202                 $members = group_get_members($gid);
3203                 foreach ($members as $member) {
3204                         $cid = $member['id'];
3205                         foreach ($users as $user) {
3206                                 $found = ($user['cid'] == $cid ? true : false);
3207                         }
3208                         if (!$found) {
3209                                 $ret = group_rmv_member($uid, $name, $cid);
3210                         }
3211                 }
3212
3213                 // add members
3214                 $erroraddinguser = false;
3215                 $errorusers = array();
3216                 foreach ($users as $user) {
3217                         $cid = $user['cid'];
3218                         // check if user really exists as contact
3219                         $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d", 
3220                                 intval($cid),
3221                                 intval($uid));
3222                         if (count($contact))
3223                                 $result = group_add_member($uid, $name, $cid, $gid);
3224                         else {
3225                                 $erroraddinguser = true;
3226                                 $errorusers[] = $cid;
3227                         }
3228                 }
3229                 
3230                 // return success message incl. missing users in array
3231                 $status = ($erroraddinguser ? "missing user" : "ok");
3232                 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3233                 return api_apply_template("group_update", $type, array('result' => $success));          
3234         }
3235         api_register_func('api/friendica/group_update', 'api_friendica_group_update', true);
3236
3237 /*
3238 To.Do:
3239     [pagename] => api/1.1/statuses/lookup.json
3240     [id] => 605138389168451584
3241     [include_cards] => true
3242     [cards_platform] => Android-12
3243     [include_entities] => true
3244     [include_my_retweet] => 1
3245     [include_rts] => 1
3246     [include_reply_count] => true
3247     [include_descendent_reply_count] => true
3248
3249
3250
3251 Not implemented by now:
3252 statuses/retweets_of_me
3253 friendships/create
3254 friendships/destroy
3255 friendships/exists
3256 friendships/show
3257 account/update_location
3258 account/update_profile_background_image
3259 account/update_profile_image
3260 blocks/create
3261 blocks/destroy
3262
3263 Not implemented in status.net:
3264 statuses/retweeted_to_me
3265 statuses/retweeted_by_me
3266 direct_messages/destroy
3267 account/end_session
3268 account/update_delivery_device
3269 notifications/follow
3270 notifications/leave
3271 blocks/exists
3272 blocks/blocking
3273 lists
3274 */