Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

4321 líneas
129KB

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