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