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