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