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.

5027 lines
154KB

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