Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

5045 Zeilen
155 KiB

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