Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4051 lines
123KB

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