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

5044 lines
155KB

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