greader.php 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. == Description ==
  5. Server-side API compatible with Google Reader API layer 2
  6. for the FreshRSS project https://freshrss.org
  7. == Credits ==
  8. * 2014-03: Released by Alexandre Alapetite https://alexandre.alapetite.fr
  9. under GNU AGPL 3 license http://www.gnu.org/licenses/agpl-3.0.html
  10. == Documentation ==
  11. * https://code.google.com/archive/p/pyrfeed/wikis/GoogleReaderAPI.wiki
  12. * https://web.archive.org/web/20130718025427/http://undoc.in/
  13. * http://ranchero.com/downloads/GoogleReaderAPI-2009.pdf
  14. * https://github.com/mihaip/google-reader-api
  15. * https://web.archive.org/web/20210126113527/https://blog.martindoms.com/2009/08/15/using-the-google-reader-api-part-1
  16. * https://github.com/noinnion/newsplus/blob/master/extensions/GoogleReaderCloneExtension/src/com/noinnion/android/newsplus/extension/google_reader/GoogleReaderClient.java
  17. * https://github.com/ericmann/gReader-Library/blob/master/greader.class.php
  18. * https://github.com/devongovett/reader
  19. * https://github.com/theoldreader/api
  20. * https://www.inoreader.com/developers/
  21. * https://feedhq.readthedocs.io/en/latest/api/index.html
  22. * https://github.com/bazqux/bazqux-api
  23. */
  24. require dirname(__DIR__, 2) . '/constants.php';
  25. require LIB_PATH . '/lib_rss.php'; //Includes class autoloader
  26. header("Content-Security-Policy: default-src 'none'; frame-ancestors 'none'; sandbox");
  27. header('X-Content-Type-Options: nosniff');
  28. if (PHP_INT_SIZE < 8) { //32-bit
  29. /** @return numeric-string */
  30. function hex2dec(string $hex): string {
  31. if (!ctype_xdigit($hex)) return '0';
  32. $result = gmp_strval(gmp_init($hex, 16), 10);
  33. /** @var numeric-string $result */
  34. return $result;
  35. }
  36. } else { //64-bit
  37. /** @return numeric-string */
  38. function hex2dec(string $hex): string {
  39. if (!ctype_xdigit($hex)) {
  40. return '0';
  41. }
  42. return '' . hexdec($hex);
  43. }
  44. }
  45. const JSON_OPTIONS = JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
  46. function headerVariable(string $headerName, string $varName): string {
  47. $header = '';
  48. $upName = 'HTTP_' . strtoupper($headerName);
  49. if (is_string($_SERVER[$upName] ?? null)) {
  50. $header = '' . $_SERVER[$upName];
  51. } elseif (is_string($_SERVER['REDIRECT_' . $upName] ?? null)) {
  52. $header = '' . $_SERVER['REDIRECT_' . $upName];
  53. } elseif (function_exists('getallheaders')) {
  54. $ALL_HEADERS = getallheaders();
  55. if (is_string($ALL_HEADERS[$headerName] ?? null)) {
  56. $header = '' . $ALL_HEADERS[$headerName];
  57. }
  58. }
  59. parse_str($header, $pairs);
  60. if (empty($pairs[$varName])) {
  61. return '';
  62. }
  63. return is_string($pairs[$varName]) ? $pairs[$varName] : '';
  64. }
  65. final class GReaderAPI {
  66. private static string $ORIGINAL_INPUT = '';
  67. /** @return list<string> */
  68. private static function multiplePosts(string $name): array {
  69. //https://bugs.php.net/bug.php?id=51633
  70. $inputs = explode('&', self::$ORIGINAL_INPUT);
  71. $result = [];
  72. $prefix = $name . '=';
  73. $prefixLength = strlen($prefix);
  74. foreach ($inputs as $input) {
  75. if (str_starts_with($input, $prefix)) {
  76. $result[] = urldecode(substr($input, $prefixLength));
  77. }
  78. }
  79. return $result;
  80. }
  81. private static function debugInfo(): string {
  82. if (function_exists('getallheaders')) {
  83. $ALL_HEADERS = getallheaders();
  84. } else { //nginx http://php.net/getallheaders#84262
  85. $ALL_HEADERS = [];
  86. foreach ($_SERVER as $name => $value) {
  87. if (is_string($name) && str_starts_with($name, 'HTTP_')) {
  88. $ALL_HEADERS[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
  89. }
  90. }
  91. }
  92. $log = sensitive_log([
  93. 'date' => date('c'),
  94. 'headers' => $ALL_HEADERS,
  95. '_SERVER' => $_SERVER,
  96. '_GET' => $_GET,
  97. '_POST' => $_POST,
  98. '_COOKIE' => $_COOKIE,
  99. 'INPUT' => self::$ORIGINAL_INPUT,
  100. ]);
  101. return print_r($log, true);
  102. }
  103. private static function noContent(): never {
  104. header('HTTP/1.1 204 No Content');
  105. exit();
  106. }
  107. private static function badRequest(): never {
  108. Minz_Log::warning(__METHOD__, API_LOG);
  109. Minz_Log::debug(__METHOD__ . ' ' . self::debugInfo(), API_LOG);
  110. header('HTTP/1.1 400 Bad Request');
  111. header('Content-Type: text/plain; charset=UTF-8');
  112. die('Bad Request!');
  113. }
  114. private static function unauthorized(): never {
  115. Minz_Log::warning(__METHOD__, API_LOG);
  116. Minz_Log::debug(__METHOD__ . ' ' . self::debugInfo(), API_LOG);
  117. header('HTTP/1.1 401 Unauthorized');
  118. header('Content-Type: text/plain; charset=UTF-8');
  119. header('Google-Bad-Token: true');
  120. die('Unauthorized!');
  121. }
  122. private static function internalServerError(): never {
  123. Minz_Log::warning(__METHOD__, API_LOG);
  124. Minz_Log::debug(__METHOD__ . ' ' . self::debugInfo(), API_LOG);
  125. header('HTTP/1.1 500 Internal Server Error');
  126. header('Content-Type: text/plain; charset=UTF-8');
  127. die('Internal Server Error!');
  128. }
  129. private static function notImplemented(): never {
  130. Minz_Log::warning(__METHOD__, API_LOG);
  131. Minz_Log::debug(__METHOD__ . ' ' . self::debugInfo(), API_LOG);
  132. header('HTTP/1.1 501 Not Implemented');
  133. header('Content-Type: text/plain; charset=UTF-8');
  134. die('Not Implemented!');
  135. }
  136. private static function serviceUnavailable(): never {
  137. Minz_Log::warning(__METHOD__, API_LOG);
  138. Minz_Log::debug(__METHOD__ . ' ' . self::debugInfo(), API_LOG);
  139. header('HTTP/1.1 503 Service Unavailable');
  140. header('Content-Type: text/plain; charset=UTF-8');
  141. die('Service Unavailable!');
  142. }
  143. private static function checkCompatibility(): never {
  144. Minz_Log::warning(__METHOD__, API_LOG);
  145. Minz_Log::debug(__METHOD__ . ' ' . self::debugInfo(), API_LOG);
  146. header('Content-Type: text/plain; charset=UTF-8');
  147. if (PHP_INT_SIZE < 8 && !function_exists('gmp_init')) {
  148. die('FAIL 64-bit or GMP extension! Wrong PHP configuration.');
  149. }
  150. $headerAuth = headerVariable('Authorization', 'GoogleLogin_auth');
  151. if ($headerAuth == '') {
  152. die('FAIL get HTTP Authorization header! Wrong Web server configuration.');
  153. }
  154. echo 'PASS';
  155. exit();
  156. }
  157. private static function authorizationToUser(): string {
  158. //Input is 'GoogleLogin auth', but PHP replaces spaces by '_' http://php.net/language.variables.external
  159. $headerAuth = headerVariable('Authorization', 'GoogleLogin_auth');
  160. if ($headerAuth != '') {
  161. $headerAuthX = explode('/', $headerAuth, 2);
  162. if (count($headerAuthX) === 2) {
  163. $user = $headerAuthX[0];
  164. if (FreshRSS_user_Controller::checkUsername($user)) {
  165. FreshRSS_Context::initUser($user);
  166. if (!FreshRSS_Context::hasUserConf() || !FreshRSS_Context::hasSystemConf()) {
  167. Minz_Log::warning('Invalid API user ' . $user . ': configuration cannot be found.');
  168. self::unauthorized();
  169. }
  170. if (!FreshRSS_Context::userConf()->enabled) {
  171. Minz_Log::warning('Invalid API user ' . $user . ': configuration cannot be found.');
  172. self::unauthorized();
  173. }
  174. if ($headerAuthX[1] === sha1(FreshRSS_Context::systemConf()->salt . $user . FreshRSS_Context::userConf()->apiPasswordHash)) {
  175. return $user;
  176. } else {
  177. Minz_Log::warning('Invalid API authorisation for user ' . $user);
  178. self::unauthorized();
  179. }
  180. } else {
  181. self::badRequest();
  182. }
  183. }
  184. }
  185. return '';
  186. }
  187. private static function clientLogin(string $email, string $pass): never {
  188. //https://web.archive.org/web/20130604091042/http://undoc.in/clientLogin.html
  189. if (FreshRSS_user_Controller::checkUsername($email)) {
  190. FreshRSS_Context::initUser($email);
  191. if (!FreshRSS_Context::hasUserConf() || !FreshRSS_Context::hasSystemConf()) {
  192. Minz_Log::warning('Invalid API user ' . $email . ': configuration cannot be found.');
  193. self::unauthorized();
  194. }
  195. if (FreshRSS_Context::userConf()->apiPasswordHash != '' && password_verify($pass, FreshRSS_Context::userConf()->apiPasswordHash)) {
  196. header('Content-Type: text/plain; charset=UTF-8');
  197. $auth = $email . '/' . sha1(FreshRSS_Context::systemConf()->salt . $email . FreshRSS_Context::userConf()->apiPasswordHash);
  198. echo 'SID=', $auth, "\n",
  199. 'LSID=null', "\n", //Vienna RSS
  200. 'Auth=', $auth, "\n";
  201. exit();
  202. } else {
  203. Minz_Log::warning('Password API mismatch for user ' . $email);
  204. self::unauthorized();
  205. }
  206. } else {
  207. self::badRequest();
  208. }
  209. }
  210. private static function token(?FreshRSS_UserConfiguration $conf): never {
  211. // https://web.archive.org/web/20210126113527/https://blog.martindoms.com/2009/08/15/using-the-google-reader-api-part-1
  212. // https://github.com/ericmann/gReader-Library/blob/master/greader.class.php
  213. $user = Minz_User::name();
  214. if ($user === null || $conf === null || !FreshRSS_Context::hasSystemConf()) {
  215. self::unauthorized();
  216. }
  217. //Minz_Log::debug('token('. $user . ')', API_LOG); //TODO: Implement real token that expires
  218. $token = str_pad(sha1(FreshRSS_Context::systemConf()->salt . $user . $conf->apiPasswordHash), 57, 'Z'); //Must have 57 characters
  219. echo $token, "\n";
  220. exit();
  221. }
  222. private static function checkToken(?FreshRSS_UserConfiguration $conf, string $token): bool {
  223. // https://github.com/mihaip/google-reader-api/blob/master/wiki/ActionToken.wiki
  224. $user = Minz_User::name();
  225. if ($user === null || $conf === null || !FreshRSS_Context::hasSystemConf()) {
  226. self::unauthorized();
  227. }
  228. if ($user !== Minz_User::INTERNAL_USER && ( //TODO: Check security consequences
  229. $token === '' || //FeedMe
  230. $token === 'x')) { //Reeder
  231. return true;
  232. }
  233. if ($token === str_pad(sha1(FreshRSS_Context::systemConf()->salt . $user . $conf->apiPasswordHash), 57, 'Z')) {
  234. return true;
  235. }
  236. Minz_Log::warning('Invalid POST token: ' . $token, API_LOG);
  237. self::unauthorized();
  238. }
  239. private static function userInfo(): never {
  240. //https://github.com/theoldreader/api#user-info
  241. if (!FreshRSS_Context::hasUserConf()) {
  242. self::unauthorized();
  243. }
  244. $user = Minz_User::name();
  245. exit(json_encode([
  246. 'userId' => $user,
  247. 'userName' => $user,
  248. 'userProfileId' => $user,
  249. 'userEmail' => FreshRSS_Context::userConf()->mail_login,
  250. ], JSON_OPTIONS));
  251. }
  252. private static function tagList(): never {
  253. header('Content-Type: application/json; charset=UTF-8');
  254. $tags = [
  255. ['id' => 'user/-/state/com.google/starred'],
  256. // ['id' => 'user/-/state/com.google/broadcast', 'sortid' => '2']
  257. ];
  258. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  259. $categories = $categoryDAO->listCategories(prePopulateFeeds: false, details: false);
  260. foreach ($categories as $cat) {
  261. $tags[] = [
  262. 'id' => 'user/-/label/' . htmlspecialchars_decode($cat->name(), ENT_QUOTES),
  263. //'sortid' => $cat->name(),
  264. 'type' => 'folder', //Inoreader
  265. ];
  266. }
  267. $tagDAO = FreshRSS_Factory::createTagDao();
  268. $labels = $tagDAO->listTags(precounts: true);
  269. foreach ($labels as $label) {
  270. $tags[] = [
  271. 'id' => 'user/-/label/' . htmlspecialchars_decode($label->name(), ENT_QUOTES),
  272. //'sortid' => $label->name(),
  273. 'type' => 'tag', //Inoreader
  274. 'unread_count' => $label->nbUnread(), //Inoreader
  275. ];
  276. }
  277. echo json_encode(['tags' => $tags], JSON_OPTIONS), "\n";
  278. exit();
  279. }
  280. private static function subscriptionExport(): never {
  281. $user = Minz_User::name() ?? Minz_User::INTERNAL_USER;
  282. $export_service = new FreshRSS_Export_Service($user);
  283. [$filename, $content] = $export_service->generateOpml();
  284. header('Content-Type: application/xml; charset=UTF-8');
  285. header('Content-disposition: attachment; filename="' . $filename . '"');
  286. echo $content;
  287. exit();
  288. }
  289. private static function subscriptionImport(string $opml): never {
  290. $user = Minz_User::name() ?? Minz_User::INTERNAL_USER;
  291. $importService = new FreshRSS_Import_Service($user);
  292. $importService->importOpml($opml);
  293. if ($importService->lastStatus()) {
  294. FreshRSS_feed_Controller::actualizeFeedsAndCommit();
  295. invalidateHttpCache($user);
  296. exit('OK');
  297. } else {
  298. self::badRequest();
  299. }
  300. }
  301. private static function subscriptionList(): never {
  302. if (!FreshRSS_Context::hasSystemConf()) {
  303. self::internalServerError();
  304. }
  305. header('Content-Type: application/json; charset=UTF-8');
  306. $subscriptions = [];
  307. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  308. foreach ($categoryDAO->listCategories(prePopulateFeeds: true, details: true) as $cat) {
  309. foreach ($cat->feeds() as $feed) {
  310. if ($feed->priority() <= FreshRSS_Feed::PRIORITY_HIDDEN) {
  311. continue;
  312. }
  313. $subscriptions[] = [
  314. 'id' => 'feed/' . $feed->id(),
  315. 'title' => escapeToUnicodeAlternative($feed->name(), true),
  316. 'categories' => [
  317. [
  318. 'id' => 'user/-/label/' . htmlspecialchars_decode($cat->name(), ENT_QUOTES),
  319. 'label' => htmlspecialchars_decode($cat->name(), ENT_QUOTES),
  320. ],
  321. ],
  322. //'sortid' => $feed->name(),
  323. //'firstitemmsec' => 0,
  324. 'url' => htmlspecialchars_decode($feed->url(), ENT_QUOTES),
  325. 'htmlUrl' => htmlspecialchars_decode($feed->website(), ENT_QUOTES),
  326. 'iconUrl' => str_replace(
  327. '/api/greader.php/reader/api/0/subscription', '', // Security if base_url is not set properly
  328. $feed->favicon(absolute: true)),
  329. ];
  330. }
  331. }
  332. echo json_encode(['subscriptions' => $subscriptions], JSON_OPTIONS), "\n";
  333. exit();
  334. }
  335. /**
  336. * @param list<string> $streamNames StreamId(s) to operate on. The parameter may be repeated to edit multiple subscriptions at once
  337. * @param list<string> $titles Title(s) to use for the subscription(s). Each title is associated with the corresponding streamName
  338. * @param string $action 'subscribe'|'unsubscribe'|'edit'
  339. * @param string $add StreamId to add the subscription(s) to (generally a category)
  340. * @param string $remove StreamId to remove the subscription(s) from (generally a category)
  341. */
  342. private static function subscriptionEdit(array $streamNames, array $titles, string $action, string $add = '', string $remove = ''): never {
  343. // https://github.com/mihaip/google-reader-api/blob/master/wiki/ApiSubscriptionEdit.wiki
  344. if (count($streamNames) < 1) {
  345. self::badRequest();
  346. }
  347. switch ($action) {
  348. case 'subscribe':
  349. case 'unsubscribe':
  350. case 'edit':
  351. break;
  352. default:
  353. self::badRequest();
  354. }
  355. $addCatId = 0;
  356. if (str_starts_with($add, 'user/')) { // user/-/label/Example ; user/username/label/Example
  357. if (str_starts_with($add, 'user/-/label/')) {
  358. $c_name = substr($add, 13);
  359. } else {
  360. $prefix = 'user/' . Minz_User::name() . '/label/';
  361. if (str_starts_with($add, $prefix)) {
  362. $c_name = substr($add, strlen($prefix));
  363. } else {
  364. $c_name = '';
  365. }
  366. }
  367. $c_name = htmlspecialchars($c_name, ENT_COMPAT, 'UTF-8');
  368. if (in_array($c_name, ['', 'Uncategorized', _t('gen.short.default_category')], true)) {
  369. $addCatId = FreshRSS_CategoryDAO::DEFAULTCATEGORYID;
  370. } else {
  371. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  372. $cat = $categoryDAO->searchByName($c_name);
  373. $addCatId = $cat === null ? 0 : $cat->id();
  374. if ($addCatId === 0) {
  375. $addCatId = $categoryDAO->addCategory(['name' => $c_name]) ?: FreshRSS_CategoryDAO::DEFAULTCATEGORYID;
  376. }
  377. }
  378. } elseif (str_starts_with($remove, 'user/-/label/')) {
  379. $addCatId = FreshRSS_CategoryDAO::DEFAULTCATEGORYID;
  380. }
  381. $feedDAO = FreshRSS_Factory::createFeedDao();
  382. for ($i = count($streamNames) - 1; $i >= 0; $i--) {
  383. $streamUrl = $streamNames[$i]; //feed/http://example.net/sample.xml ; feed/338
  384. if (str_starts_with($streamUrl, 'feed/')) {
  385. $streamUrl = '' . preg_replace('%^(feed/)+%', '', $streamUrl);
  386. $feedId = 0;
  387. if (is_numeric($streamUrl)) {
  388. if ($action === 'subscribe') {
  389. continue;
  390. }
  391. $feedId = (int)$streamUrl;
  392. } else {
  393. $streamUrl = htmlspecialchars($streamUrl, ENT_COMPAT, 'UTF-8');
  394. $feed = $feedDAO->searchByUrl($streamUrl);
  395. $feedId = $feed == null ? -1 : $feed->id();
  396. }
  397. $title = $titles[$i] ?? '';
  398. $title = htmlspecialchars($title, ENT_COMPAT, 'UTF-8');
  399. switch ($action) {
  400. case 'subscribe':
  401. if ($feedId <= 0) {
  402. $http_auth = '';
  403. try {
  404. FreshRSS_feed_Controller::addFeed($streamUrl, $title, $addCatId, '', $http_auth);
  405. continue 2;
  406. } catch (Exception $e) {
  407. Minz_Log::error('subscriptionEdit error subscribe: ' . $e->getMessage(), API_LOG);
  408. }
  409. }
  410. self::badRequest();
  411. // Always exits
  412. case 'unsubscribe':
  413. if (!($feedId > 0 && FreshRSS_feed_Controller::deleteFeed($feedId))) {
  414. self::badRequest();
  415. }
  416. break;
  417. case 'edit':
  418. if ($feedId > 0) {
  419. if ($addCatId > 0) {
  420. FreshRSS_feed_Controller::moveFeed($feedId, $addCatId);
  421. }
  422. if ($title != '') {
  423. FreshRSS_feed_Controller::renameFeed($feedId, $title);
  424. }
  425. } else {
  426. self::badRequest();
  427. }
  428. break;
  429. }
  430. }
  431. }
  432. exit('OK');
  433. }
  434. private static function quickadd(string $url): never {
  435. try {
  436. $url = htmlspecialchars($url, ENT_COMPAT, 'UTF-8');
  437. if (str_starts_with($url, 'feed/')) {
  438. $url = substr($url, 5);
  439. }
  440. $feed = FreshRSS_feed_Controller::addFeed($url);
  441. exit(json_encode([
  442. 'numResults' => 1,
  443. 'query' => $feed->url(),
  444. 'streamId' => 'feed/' . $feed->id(),
  445. 'streamName' => $feed->name(),
  446. ], JSON_OPTIONS));
  447. } catch (Exception $e) {
  448. Minz_Log::error('quickadd error: ' . $e->getMessage(), API_LOG);
  449. die(json_encode([
  450. 'numResults' => 0,
  451. 'error' => $e->getMessage(),
  452. ], JSON_OPTIONS));
  453. }
  454. }
  455. private static function unreadCount(): never {
  456. // https://web.archive.org/web/20210126115837/https://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2#unread-count
  457. header('Content-Type: application/json; charset=UTF-8');
  458. $totalUnreads = 0;
  459. $totalLastUpdate = 0;
  460. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  461. $feedDAO = FreshRSS_Factory::createFeedDao();
  462. $feedsNewestItemUsec = $feedDAO->listFeedsNewestItemUsec();
  463. $unreadcounts = [];
  464. foreach ($categoryDAO->listCategories(prePopulateFeeds: true, details: true) as $cat) {
  465. $catLastUpdate = 0;
  466. foreach ($cat->feeds() as $feed) {
  467. if ($feed->priority() <= FreshRSS_Feed::PRIORITY_HIDDEN) {
  468. continue;
  469. }
  470. $lastUpdate = $feedsNewestItemUsec['f_' . $feed->id()] ?? 0;
  471. $unreadcounts[] = [
  472. 'id' => 'feed/' . $feed->id(),
  473. 'count' => $feed->nbNotRead(),
  474. 'newestItemTimestampUsec' => '' . $lastUpdate,
  475. ];
  476. if ($catLastUpdate < $lastUpdate) {
  477. $catLastUpdate = $lastUpdate;
  478. }
  479. }
  480. $unreadcounts[] = [
  481. 'id' => 'user/-/label/' . htmlspecialchars_decode($cat->name(), ENT_QUOTES),
  482. 'count' => $cat->nbNotRead(),
  483. 'newestItemTimestampUsec' => '' . $catLastUpdate,
  484. ];
  485. $totalUnreads += $cat->nbNotRead();
  486. if ($totalLastUpdate < $catLastUpdate) {
  487. $totalLastUpdate = $catLastUpdate;
  488. }
  489. }
  490. $tagDAO = FreshRSS_Factory::createTagDao();
  491. $tagsNewestItemUsec = $tagDAO->listTagsNewestItemUsec();
  492. foreach ($tagDAO->listTags(precounts: true) as $label) {
  493. $lastUpdate = $tagsNewestItemUsec['t_' . $label->id()] ?? 0;
  494. $unreadcounts[] = [
  495. 'id' => 'user/-/label/' . htmlspecialchars_decode($label->name(), ENT_QUOTES),
  496. 'count' => $label->nbUnread(),
  497. 'newestItemTimestampUsec' => '' . $lastUpdate,
  498. ];
  499. }
  500. $unreadcounts[] = [
  501. 'id' => 'user/-/state/com.google/reading-list',
  502. 'count' => $totalUnreads,
  503. 'newestItemTimestampUsec' => '' . $totalLastUpdate,
  504. ];
  505. echo json_encode([
  506. 'max' => $totalUnreads,
  507. 'unreadcounts' => $unreadcounts,
  508. ], JSON_OPTIONS), "\n";
  509. exit();
  510. }
  511. /**
  512. * @param iterable<FreshRSS_Entry> $entries
  513. * @param list<numeric-string>|null $e_ids List of entry IDs if known, for performance
  514. * @return Generator<int,array<string,mixed>>
  515. */
  516. private static function entriesToArray(iterable $entries, ?array $e_ids = null): Generator {
  517. $catDAO = FreshRSS_Factory::createCategoryDao();
  518. $categories = $catDAO->listCategories(prePopulateFeeds: true);
  519. $tagDAO = FreshRSS_Factory::createTagDao();
  520. if (is_array($e_ids)) {
  521. $entryIdsTagNames = $tagDAO->getEntryIdsTagNames($e_ids);
  522. } else {
  523. // If we do not have the list of entry IDs, we first need to iterate through all entries
  524. //TODO: Improve: avoid iterator_to_array. Type test only for PHP < 8.2
  525. $entries = array_values(is_array($entries) ? $entries : iterator_to_array($entries));
  526. $entryIdsTagNames = $tagDAO->getEntryIdsTagNames($entries);
  527. }
  528. foreach ($entries as $item) {
  529. /** @var FreshRSS_Entry|null $entry */
  530. $entry = Minz_ExtensionManager::callHook(Minz_HookType::EntryBeforeDisplay, $item);
  531. if ($entry === null) {
  532. continue;
  533. }
  534. $feed = FreshRSS_Category::findFeed($categories, $entry->feedId());
  535. if ($feed === null) {
  536. continue;
  537. }
  538. $entry->_feed($feed);
  539. yield $entry->toGReader('compat', $entryIdsTagNames['e_' . $entry->id()] ?? []);
  540. }
  541. }
  542. /**
  543. * @param 'A'|'c'|'f'|'s' $type
  544. * @return array{'A'|'c'|'f'|'s'|'t',int,int,FreshRSS_BooleanSearch}
  545. */
  546. private static function streamContentsFilters(string $type, int|string $streamId,
  547. string $filter_target, string $exclude_target, int $start_time, int $stop_time): array {
  548. switch ($type) {
  549. case 'f': //feed
  550. if ($streamId != '' && is_string($streamId) && !is_numeric($streamId)) {
  551. $feedDAO = FreshRSS_Factory::createFeedDao();
  552. $streamId = htmlspecialchars($streamId, ENT_COMPAT, 'UTF-8');
  553. $feed = $feedDAO->searchByUrl($streamId);
  554. $streamId = $feed === null ? -1 : $feed->id();
  555. }
  556. break;
  557. case 'c': //category or label
  558. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  559. $streamId = htmlspecialchars((string)$streamId, ENT_COMPAT, 'UTF-8');
  560. $cat = $categoryDAO->searchByName($streamId);
  561. if ($cat !== null) {
  562. $streamId = $cat->id();
  563. } else {
  564. $tagDAO = FreshRSS_Factory::createTagDao();
  565. $tag = $tagDAO->searchByName($streamId);
  566. if ($tag !== null) {
  567. $type = 't';
  568. $streamId = $tag->id();
  569. } else {
  570. $streamId = -1;
  571. }
  572. }
  573. break;
  574. }
  575. $streamId = is_numeric($streamId) ? (int)$streamId : 0;
  576. $state = match ($filter_target) {
  577. 'user/-/state/com.google/read' => FreshRSS_Entry::STATE_READ,
  578. 'user/-/state/com.google/unread' => FreshRSS_Entry::STATE_NOT_READ,
  579. 'user/-/state/com.google/starred' => FreshRSS_Entry::STATE_FAVORITE,
  580. default => FreshRSS_Entry::STATE_ALL,
  581. };
  582. switch ($exclude_target) {
  583. case 'user/-/state/com.google/read':
  584. $state &= FreshRSS_Entry::STATE_NOT_READ;
  585. break;
  586. case 'user/-/state/com.google/unread':
  587. $state &= FreshRSS_Entry::STATE_READ;
  588. break;
  589. case 'user/-/state/com.google/starred':
  590. $state &= FreshRSS_Entry::STATE_NOT_FAVORITE;
  591. break;
  592. }
  593. $searches = new FreshRSS_BooleanSearch('');
  594. if ($start_time !== 0) {
  595. $search = new FreshRSS_Search('');
  596. $search->setMinDate($start_time);
  597. $searches->add($search);
  598. }
  599. if ($stop_time !== 0) {
  600. $search = new FreshRSS_Search('');
  601. $search->setMaxDate($stop_time);
  602. $searches->add($search);
  603. }
  604. return [$type, $streamId, $state, $searches];
  605. }
  606. /**
  607. * @param numeric-string $continuation
  608. */
  609. private static function streamContents(string $path, string $include_target, int $start_time, int $stop_time, int $count,
  610. string $order, string $filter_target, string $exclude_target, string $continuation): never {
  611. // https://code.google.com/archive/p/pyrfeed/wikis/GoogleReaderAPI.wiki
  612. // https://web.archive.org/web/20210126115837/https://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2#feed
  613. header('Content-Type: application/json; charset=UTF-8');
  614. $type = match ($path) {
  615. 'starred' => 's',
  616. 'feed' => 'f',
  617. 'label' => 'c',
  618. 'reading-list' => 'A', // All except PRIORITY_HIDDEN
  619. default => 'A',
  620. };
  621. [$type, $include_target, $state, $searches] =
  622. self::streamContentsFilters($type, $include_target, $filter_target, $exclude_target, $start_time, $stop_time);
  623. if ($continuation !== '0') {
  624. $count++; //Shift by one element
  625. }
  626. $entryDAO = FreshRSS_Factory::createEntryDao();
  627. $entries = $entryDAO->listWhere($type, $include_target, $state, $searches,
  628. order: $order === 'o' ? 'ASC' : 'DESC',
  629. continuation_id: $continuation,
  630. limit: $count);
  631. $items = self::entriesToArray($entries);
  632. if ($continuation !== '0') {
  633. //Discard first element that was already sent in the previous response
  634. $items = new LimitIterator($items, offset: 1);
  635. $count--;
  636. }
  637. $time = time();
  638. $nbItems = 0;
  639. $lastEntryId = 0;
  640. // Note: This section must be streamed to avoid memory issues with large responses
  641. echo <<<TXT
  642. {
  643. "id": "user/-/state/com.google/reading-list",
  644. "updated": $time,
  645. "items": [
  646. TXT;
  647. foreach ($items as $item) {
  648. if (!is_array($item) || empty($item)) {
  649. continue;
  650. }
  651. if ($nbItems > 0) {
  652. echo ",\n";
  653. }
  654. $lastEntryId = is_numeric($item['frss:id'] ?? null) ? (int)$item['frss:id'] : 0;
  655. unset($item['frss:id']);
  656. echo json_encode($item, JSON_OPTIONS);
  657. $nbItems++;
  658. }
  659. echo <<<'TXT'
  660. ]
  661. TXT;
  662. if ($nbItems >= $count && $lastEntryId > 0) {
  663. echo <<<TXT
  664. ,
  665. "continuation": "$lastEntryId"
  666. TXT;
  667. }
  668. echo <<<'TXT'
  669. }
  670. TXT;
  671. exit();
  672. }
  673. /**
  674. * @param numeric-string $continuation
  675. */
  676. private static function streamContentsItemsIds(string $streamId, int $start_time, int $stop_time, int $count,
  677. string $order, string $filter_target, string $exclude_target, string $continuation): never {
  678. // https://github.com/mihaip/google-reader-api/blob/master/wiki/ApiStreamItemsIds.wiki
  679. // https://code.google.com/archive/p/pyrfeed/wikis/GoogleReaderAPI.wiki
  680. // https://web.archive.org/web/20210126115837/https://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2#feed
  681. $type = 'A';
  682. if ($streamId === 'user/-/state/com.google/reading-list') {
  683. $type = 'A';
  684. $streamId = '';
  685. } elseif ($streamId === 'user/-/state/com.google/starred') {
  686. $type = 's';
  687. $streamId = '';
  688. } elseif ($streamId === 'user/-/state/com.google/read') {
  689. $filter_target = $streamId;
  690. $type = 'A';
  691. $streamId = '';
  692. } elseif ($streamId === 'user/-/state/com.google/unread') {
  693. $filter_target = $streamId;
  694. $type = 'A';
  695. $streamId = '';
  696. } elseif (str_starts_with($streamId, 'feed/')) {
  697. $type = 'f';
  698. $streamId = substr($streamId, 5);
  699. } elseif (str_starts_with($streamId, 'user/-/label/')) {
  700. $type = 'c';
  701. $streamId = substr($streamId, 13);
  702. }
  703. [$type, $id, $state, $searches] = self::streamContentsFilters($type, $streamId, $filter_target, $exclude_target, $start_time, $stop_time);
  704. if ($continuation !== '0') {
  705. $count++; //Shift by one element
  706. }
  707. $entryDAO = FreshRSS_Factory::createEntryDao();
  708. $ids = $entryDAO->listIdsWhere($type, $id, $state, $searches,
  709. order: $order === 'o' ? 'ASC' : 'DESC',
  710. continuation_id: $continuation,
  711. limit: $count);
  712. if ($ids === null) {
  713. self::internalServerError();
  714. }
  715. if ($continuation !== '0') {
  716. array_shift($ids); //Discard first element that was already sent in the previous response
  717. $count--;
  718. }
  719. if (empty($ids) && isset($_GET['client']) && $_GET['client'] === 'newsplus') {
  720. $ids = [ 0 ]; //For News+ bug https://github.com/noinnion/newsplus/issues/84#issuecomment-57834632
  721. }
  722. $itemRefs = [];
  723. foreach ($ids as $entryId) {
  724. $itemRefs[] = [
  725. 'id' => '' . $entryId, //64-bit decimal
  726. ];
  727. }
  728. $response = [
  729. 'itemRefs' => $itemRefs,
  730. ];
  731. if (count($ids) >= $count) {
  732. $entryId = end($ids);
  733. if ($entryId != false) {
  734. $response['continuation'] = '' . $entryId;
  735. }
  736. }
  737. echo json_encode($response, JSON_OPTIONS), "\n";
  738. exit();
  739. }
  740. /**
  741. * @param list<string> $e_ids
  742. */
  743. private static function streamContentsItems(array $e_ids, string $order): never {
  744. header('Content-Type: application/json; charset=UTF-8');
  745. foreach ($e_ids as $i => $e_id) {
  746. // https://feedhq.readthedocs.io/en/latest/api/terminology.html#items
  747. if (!ctype_digit($e_id) || $e_id[0] === '0') {
  748. $e_ids[$i] = hex2dec(basename($e_id)); //Strip prefix 'tag:google.com,2005:reader/item/'
  749. }
  750. }
  751. /** @var list<numeric-string> $e_ids */
  752. $entryDAO = FreshRSS_Factory::createEntryDao();
  753. $entries = $entryDAO->listByIds($e_ids, order: $order === 'o' ? 'ASC' : 'DESC');
  754. $items = self::entriesToArray($entries, $e_ids);
  755. $time = time();
  756. $nbItems = 0;
  757. // Note: This section must be streamed to avoid memory issues with large responses
  758. echo <<<TXT
  759. {
  760. "id": "user/-/state/com.google/reading-list",
  761. "updated": $time,
  762. "items": [
  763. TXT;
  764. foreach ($items as $item) {
  765. if (!is_array($item) || empty($item)) {
  766. continue;
  767. }
  768. if ($nbItems > 0) {
  769. echo ",\n";
  770. }
  771. unset($item['frss:id']);
  772. echo json_encode($item, JSON_OPTIONS);
  773. $nbItems++;
  774. }
  775. echo <<<'TXT'
  776. ]
  777. }
  778. TXT;
  779. exit();
  780. }
  781. /**
  782. * @param list<string> $e_ids IDs of the items to edit
  783. * @param list<string> $as tags to add to all the listed items
  784. * @param list<string> $rs tags to remove from all the listed items
  785. */
  786. private static function editTag(array $e_ids, array $as, array $rs): never {
  787. foreach ($e_ids as $i => $e_id) {
  788. if (!ctype_digit($e_id) || $e_id[0] === '0') {
  789. $e_ids[$i] = hex2dec(basename($e_id)); //Strip prefix 'tag:google.com,2005:reader/item/'
  790. }
  791. }
  792. /** @var list<numeric-string> $e_ids */
  793. $entryDAO = FreshRSS_Factory::createEntryDao();
  794. $tagDAO = FreshRSS_Factory::createTagDao();
  795. foreach ($as as $a) {
  796. switch ($a) {
  797. case 'user/-/state/com.google/read':
  798. $entryDAO->markRead($e_ids, true);
  799. break;
  800. case 'user/-/state/com.google/starred':
  801. $entryDAO->markFavorite($e_ids, true);
  802. break;
  803. case 'user/-/state/com.google/broadcast':
  804. case 'user/-/state/com.google/like':
  805. case 'user/-/state/com.google/tracking-kept-unread':
  806. // Not supported
  807. break;
  808. default:
  809. $tagName = '';
  810. if (str_starts_with($a, 'user/-/label/')) {
  811. $tagName = substr($a, 13);
  812. } else {
  813. $user = Minz_User::name() ?? '';
  814. $prefix = 'user/' . $user . '/label/';
  815. if (str_starts_with($a, $prefix)) {
  816. $tagName = substr($a, strlen($prefix));
  817. }
  818. }
  819. if ($tagName !== '') {
  820. $tagName = htmlspecialchars($tagName, ENT_COMPAT, 'UTF-8');
  821. $tag = $tagDAO->searchByName($tagName);
  822. if ($tag === null) {
  823. $tagDAO->addTag(['name' => $tagName]);
  824. $tag = $tagDAO->searchByName($tagName);
  825. }
  826. if ($tag !== null) {
  827. foreach ($e_ids as $e_id) {
  828. $tagDAO->tagEntry($tag->id(), $e_id, true);
  829. }
  830. }
  831. }
  832. break;
  833. }
  834. }
  835. foreach ($rs as $r) {
  836. switch ($r) {
  837. case 'user/-/state/com.google/read':
  838. $entryDAO->markRead($e_ids, false);
  839. break;
  840. case 'user/-/state/com.google/starred':
  841. $entryDAO->markFavorite($e_ids, false);
  842. break;
  843. case 'user/-/state/com.google/broadcast':
  844. case 'user/-/state/com.google/like':
  845. case 'user/-/state/com.google/tracking-kept-unread':
  846. // Not supported
  847. break;
  848. default:
  849. if (str_starts_with($r, 'user/-/label/')) {
  850. $tagName = substr($r, 13);
  851. $tagName = htmlspecialchars($tagName, ENT_COMPAT, 'UTF-8');
  852. $tag = $tagDAO->searchByName($tagName);
  853. if ($tag !== null) {
  854. foreach ($e_ids as $e_id) {
  855. $tagDAO->tagEntry($tag->id(), $e_id, false);
  856. }
  857. }
  858. }
  859. break;
  860. }
  861. }
  862. exit('OK');
  863. }
  864. private static function renameTag(string $s, string $dest): never {
  865. if (str_starts_with($s, 'user/-/label/') && str_starts_with($dest, 'user/-/label/')) {
  866. $s = substr($s, 13);
  867. $s = htmlspecialchars($s, ENT_COMPAT, 'UTF-8');
  868. $dest = substr($dest, 13);
  869. $dest = htmlspecialchars($dest, ENT_COMPAT, 'UTF-8');
  870. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  871. $cat = $categoryDAO->searchByName($s);
  872. if ($cat != null) {
  873. $categoryDAO->updateCategory($cat->id(), [
  874. 'name' => $dest, 'kind' => $cat->kind(), 'attributes' => $cat->attributes()
  875. ]);
  876. exit('OK');
  877. } else {
  878. $tagDAO = FreshRSS_Factory::createTagDao();
  879. $tag = $tagDAO->searchByName($s);
  880. if ($tag != null) {
  881. $tagDAO->updateTagName($tag->id(), $dest);
  882. exit('OK');
  883. }
  884. }
  885. }
  886. self::badRequest();
  887. }
  888. private static function disableTag(string $s): never {
  889. if (str_starts_with($s, 'user/-/label/')) {
  890. $s = substr($s, 13);
  891. $s = htmlspecialchars($s, ENT_COMPAT, 'UTF-8');
  892. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  893. $cat = $categoryDAO->searchByName($s);
  894. if ($cat != null) {
  895. $feedDAO = FreshRSS_Factory::createFeedDao();
  896. $feedDAO->changeCategory($cat->id(), 0);
  897. if ($cat->id() > FreshRSS_CategoryDAO::DEFAULTCATEGORYID) {
  898. $categoryDAO->deleteCategory($cat->id());
  899. }
  900. exit('OK');
  901. } else {
  902. $tagDAO = FreshRSS_Factory::createTagDao();
  903. $tag = $tagDAO->searchByName($s);
  904. if ($tag != null) {
  905. $tagDAO->deleteTag($tag->id());
  906. exit('OK');
  907. }
  908. }
  909. }
  910. self::badRequest();
  911. }
  912. /**
  913. * @param numeric-string $olderThanId
  914. */
  915. private static function markAllAsRead(string $streamId, string $olderThanId): never {
  916. $entryDAO = FreshRSS_Factory::createEntryDao();
  917. if (str_starts_with($streamId, 'feed/')) {
  918. $f_id = basename($streamId);
  919. if (!is_numeric($f_id)) {
  920. self::badRequest();
  921. }
  922. $f_id = (int)$f_id;
  923. $entryDAO->markReadFeed($f_id, $olderThanId);
  924. } elseif (str_starts_with($streamId, 'user/-/label/')) {
  925. $c_name = substr($streamId, 13);
  926. $c_name = htmlspecialchars($c_name, ENT_COMPAT, 'UTF-8');
  927. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  928. $cat = $categoryDAO->searchByName($c_name);
  929. if ($cat != null) {
  930. $entryDAO->markReadCat($cat->id(), $olderThanId);
  931. } else {
  932. $tagDAO = FreshRSS_Factory::createTagDao();
  933. $tag = $tagDAO->searchByName($c_name);
  934. if ($tag != null) {
  935. $entryDAO->markReadTag($tag->id(), $olderThanId);
  936. } else {
  937. self::badRequest();
  938. }
  939. }
  940. } elseif ($streamId === 'user/-/state/com.google/reading-list') {
  941. $entryDAO->markReadEntries($olderThanId, onlyFavorites: false);
  942. } elseif ($streamId === 'user/-/state/com.google/starred') {
  943. $entryDAO->markReadEntries($olderThanId, onlyFavorites: true);
  944. } elseif ($streamId === 'user/-/state/com.google/read') {
  945. $entryDAO->markReadEntries($olderThanId, state: FreshRSS_Entry::STATE_READ);
  946. } elseif ($streamId === 'user/-/state/com.google/unread') {
  947. $entryDAO->markReadEntries($olderThanId, state: FreshRSS_Entry::STATE_NOT_READ);
  948. } else {
  949. self::badRequest();
  950. }
  951. exit('OK');
  952. }
  953. public static function parse(): never {
  954. header('Access-Control-Allow-Headers: Authorization');
  955. header('Access-Control-Allow-Methods: GET, POST');
  956. header('Access-Control-Allow-Origin: *');
  957. header('Access-Control-Max-Age: 600');
  958. if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
  959. self::noContent();
  960. }
  961. $pathInfo = '';
  962. if (empty($_SERVER['PATH_INFO']) || !is_string($_SERVER['PATH_INFO'])) {
  963. if (!empty($_SERVER['ORIG_PATH_INFO']) && is_string($_SERVER['ORIG_PATH_INFO'])) {
  964. // Compatibility https://php.net/reserved.variables.server
  965. $pathInfo = $_SERVER['ORIG_PATH_INFO'];
  966. }
  967. } else {
  968. $pathInfo = $_SERVER['PATH_INFO'];
  969. }
  970. $pathInfo = rawurldecode($pathInfo);
  971. $pathInfo = '' . preg_replace('%^(/api)?(/greader\.php)?%', '', $pathInfo); //Discard common errors
  972. if ($pathInfo == '' && empty($_SERVER['QUERY_STRING'])) {
  973. exit('OK');
  974. }
  975. $pathInfos = explode('/', $pathInfo);
  976. if (count($pathInfos) < 3) {
  977. self::badRequest();
  978. }
  979. FreshRSS_Context::initSystem();
  980. //Minz_Log::debug('----------------------------------------------------------------', API_LOG);
  981. //Minz_Log::debug(self::debugInfo(), API_LOG);
  982. if (!FreshRSS_Context::hasSystemConf() || !FreshRSS_Context::systemConf()->api_enabled) {
  983. self::serviceUnavailable();
  984. } elseif ($pathInfos[1] === 'check' && $pathInfos[2] === 'compatibility') {
  985. self::checkCompatibility();
  986. }
  987. Minz_Session::init('FreshRSS', true);
  988. if ($pathInfos[1] !== 'accounts') {
  989. self::authorizationToUser();
  990. }
  991. if (FreshRSS_Context::hasUserConf()) {
  992. Minz_Translate::init(FreshRSS_Context::userConf()->language);
  993. Minz_ExtensionManager::init();
  994. Minz_ExtensionManager::enableByList(FreshRSS_Context::userConf()->extensions_enabled, 'user');
  995. } else {
  996. Minz_Translate::init();
  997. }
  998. self::$ORIGINAL_INPUT = file_get_contents('php://input', false, null, 0, 1048576) ?: '';
  999. if ($pathInfos[1] === 'accounts') {
  1000. if (($pathInfos[2] === 'ClientLogin') && is_string($_REQUEST['Email'] ?? null) && is_string($_REQUEST['Passwd'] ?? null)) {
  1001. self::clientLogin($_REQUEST['Email'], $_REQUEST['Passwd']);
  1002. }
  1003. } elseif (isset($pathInfos[3], $pathInfos[4]) && $pathInfos[1] === 'reader' && $pathInfos[2] === 'api' && $pathInfos[3] === '0') {
  1004. if (Minz_User::name() === null) {
  1005. self::unauthorized();
  1006. }
  1007. // ck=[unix timestamp]: Use the current Unix time here, helps Google with caching
  1008. $timestamp = is_numeric($_GET['ck'] ?? null) ? (int)$_GET['ck'] : 0;
  1009. switch ($pathInfos[4]) {
  1010. case 'stream':
  1011. /**
  1012. * xt=[exclude target]: Used to exclude certain items from the feed.
  1013. * For example, using xt=user/-/state/com.google/read will exclude items
  1014. * that the current user has marked as read, or xt=feed/[feedurl] will
  1015. * exclude items from a particular feed (obviously not useful in this request,
  1016. * but xt appears in other listing requests).
  1017. */
  1018. $exclude_target = is_string($_GET['xt'] ?? null) ? $_GET['xt'] : '';
  1019. $filter_target = is_string($_GET['it'] ?? null) ? $_GET['it'] : '';
  1020. //n=[integer] : The maximum number of results to return.
  1021. $count = is_numeric($_GET['n'] ?? null) ? (int)$_GET['n'] : 20;
  1022. //r=[d|n|o] : Sort order of item results. d or n gives items in descending date order, o in ascending order.
  1023. $order = is_string($_GET['r'] ?? null) ? $_GET['r'] : 'd';
  1024. /**
  1025. * ot=[unix timestamp] : The time from which you want to retrieve items.
  1026. * Only items that have been crawled by Google Reader after this time will be returned.
  1027. */
  1028. $start_time = is_numeric($_GET['ot'] ?? null) ? (int)$_GET['ot'] : 0;
  1029. $stop_time = is_numeric($_GET['nt'] ?? null) ? (int)$_GET['nt'] : 0;
  1030. /**
  1031. * Continuation token. If a StreamContents response does not represent
  1032. * all items in a timestamp range, it will have a continuation attribute.
  1033. * The same request can be re-issued with the value of that attribute put
  1034. * in this parameter to get more items
  1035. */
  1036. $continuation = is_string($_GET['c'] ?? null) ? trim($_GET['c']) : '';
  1037. if (!ctype_digit($continuation)) {
  1038. $continuation = '0';
  1039. }
  1040. if (isset($pathInfos[5]) && $pathInfos[5] === 'contents') {
  1041. if (!isset($pathInfos[6]) && is_string($_GET['s'] ?? null)) {
  1042. // Compatibility BazQux API https://github.com/bazqux/bazqux-api#fetching-streams
  1043. $streamIdInfos = explode('/', $_GET['s']);
  1044. foreach ($streamIdInfos as $streamIdInfo) {
  1045. $pathInfos[] = $streamIdInfo;
  1046. }
  1047. }
  1048. if (isset($pathInfos[6], $pathInfos[7])) {
  1049. if ($pathInfos[6] === 'feed') {
  1050. $include_target = $pathInfos[7];
  1051. if ($include_target !== '' && !is_numeric($include_target)) {
  1052. $include_target = empty($_SERVER['REQUEST_URI']) || !is_string($_SERVER['REQUEST_URI']) ? '' : $_SERVER['REQUEST_URI'];
  1053. if (preg_match('#/reader/api/0/stream/contents/feed/([A-Za-z0-9\'!*()%$_.~+-]+)#', $include_target, $matches) === 1) {
  1054. $include_target = urldecode($matches[1]);
  1055. } else {
  1056. $include_target = '';
  1057. }
  1058. }
  1059. self::streamContents($pathInfos[6], $include_target, $start_time, $stop_time,
  1060. $count, $order, $filter_target, $exclude_target, $continuation);
  1061. } elseif (isset($pathInfos[8], $pathInfos[9]) && $pathInfos[6] === 'user') {
  1062. if ($pathInfos[8] === 'state') {
  1063. if ($pathInfos[9] === 'com.google' && isset($pathInfos[10])) {
  1064. if ($pathInfos[10] === 'reading-list' || $pathInfos[10] === 'starred') {
  1065. $include_target = '';
  1066. self::streamContents($pathInfos[10], $include_target, $start_time, $stop_time, $count, $order,
  1067. $filter_target, $exclude_target, $continuation);
  1068. }
  1069. }
  1070. } elseif ($pathInfos[8] === 'label') {
  1071. $include_target = empty($_SERVER['REQUEST_URI']) || !is_string($_SERVER['REQUEST_URI']) ? '' : $_SERVER['REQUEST_URI'];
  1072. if (preg_match('#/reader/api/0/stream/contents/user/[^/+]/label/([A-Za-z0-9\'!*()%$_.~+-]+)#', $include_target, $matches)) {
  1073. $include_target = urldecode($matches[1]);
  1074. } else {
  1075. $include_target = $pathInfos[9];
  1076. }
  1077. self::streamContents($pathInfos[8], $include_target, $start_time, $stop_time,
  1078. $count, $order, $filter_target, $exclude_target, $continuation);
  1079. }
  1080. }
  1081. } else { //EasyRSS, FeedMe
  1082. $include_target = '';
  1083. self::streamContents('reading-list', $include_target, $start_time, $stop_time,
  1084. $count, $order, $filter_target, $exclude_target, $continuation);
  1085. }
  1086. } elseif ($pathInfos[5] === 'items') {
  1087. if ($pathInfos[6] === 'ids' && is_string($_GET['s'] ?? null)) {
  1088. // StreamId for which to fetch the item IDs.
  1089. // TODO: support multiple streams
  1090. $streamId = $_GET['s'];
  1091. self::streamContentsItemsIds($streamId, $start_time, $stop_time, $count, $order, $filter_target, $exclude_target, $continuation);
  1092. } elseif ($pathInfos[6] === 'contents' && isset($_POST['i'])) { //FeedMe
  1093. $e_ids = self::multiplePosts('i'); //item IDs
  1094. self::streamContentsItems($e_ids, $order);
  1095. }
  1096. }
  1097. break;
  1098. case 'tag':
  1099. if (isset($pathInfos[5]) && $pathInfos[5] === 'list') {
  1100. $output = $_GET['output'] ?? '';
  1101. if ($output !== 'json') self::notImplemented();
  1102. self::tagList();
  1103. }
  1104. break;
  1105. case 'subscription':
  1106. if (isset($pathInfos[5])) {
  1107. switch ($pathInfos[5]) {
  1108. case 'export':
  1109. self::subscriptionExport();
  1110. // Always exits
  1111. case 'import':
  1112. if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && self::$ORIGINAL_INPUT != '') {
  1113. self::subscriptionImport(self::$ORIGINAL_INPUT);
  1114. }
  1115. break;
  1116. case 'list':
  1117. $output = $_GET['output'] ?? '';
  1118. if ($output !== 'json') self::notImplemented();
  1119. self::subscriptionList();
  1120. // Always exits
  1121. case 'edit':
  1122. if (isset($_REQUEST['s'], $_REQUEST['ac'])) {
  1123. // StreamId to operate on. The parameter may be repeated to edit multiple subscriptions at once
  1124. $streamNames = empty($_POST['s']) && is_string($_GET['s'] ?? null) ? [$_GET['s']] : self::multiplePosts('s');
  1125. /* Title to use for the subscription. For the `subscribe` action,
  1126. * if not specified then the feed’s current title will be used. Can
  1127. * be used with the `edit` action to rename a subscription */
  1128. $titles = empty($_POST['t']) && is_string($_GET['t'] ?? null) ? [$_GET['t']] : self::multiplePosts('t');
  1129. // Action to perform on the given StreamId. Possible values are `subscribe`, `unsubscribe` and `edit`
  1130. $action = is_string($_REQUEST['ac'] ?? null) ? $_REQUEST['ac'] : '';
  1131. // StreamId to add the subscription to (generally a user label)
  1132. // (in FreshRSS, we do not support repeated values since a feed can only be in one category)
  1133. $add = is_string($_REQUEST['a'] ?? null) ? $_REQUEST['a'] : '';
  1134. // StreamId to remove the subscription from (generally a user label) (in FreshRSS, we do not support repeated values)
  1135. $remove = is_string($_REQUEST['r'] ?? null) ? $_REQUEST['r'] : '';
  1136. self::subscriptionEdit($streamNames, $titles, $action, $add, $remove);
  1137. }
  1138. break;
  1139. case 'quickadd': //https://github.com/theoldreader/api
  1140. if (is_string($_REQUEST['quickadd'] ?? null)) {
  1141. self::quickadd($_REQUEST['quickadd']);
  1142. }
  1143. break;
  1144. }
  1145. }
  1146. break;
  1147. case 'unread-count':
  1148. $output = $_GET['output'] ?? '';
  1149. if ($output !== 'json') self::notImplemented();
  1150. self::unreadCount();
  1151. // Always exits
  1152. case 'edit-tag': // https://web.archive.org/web/20200616071132/https://blog.martindoms.com/2010/01/20/using-the-google-reader-api-part-3
  1153. $token = is_string($_POST['T'] ?? null) ? trim($_POST['T']) : '';
  1154. self::checkToken(FreshRSS_Context::userConf(), $token);
  1155. // Add (Can be repeated to add multiple tags at once): user/-/state/com.google/read user/-/state/com.google/starred
  1156. $as = self::multiplePosts('a');
  1157. // Remove (Can be repeated to remove multiple tags at once): user/-/state/com.google/read user/-/state/com.google/starred
  1158. $rs = self::multiplePosts('r');
  1159. $e_ids = self::multiplePosts('i'); //item IDs
  1160. self::editTag($e_ids, $as, $rs);
  1161. // Always exits
  1162. case 'rename-tag': //https://github.com/theoldreader/api
  1163. $token = is_string($_POST['T'] ?? null) ? trim($_POST['T']) : '';
  1164. self::checkToken(FreshRSS_Context::userConf(), $token);
  1165. $s = is_string($_POST['s'] ?? null) ? trim($_POST['s']) : ''; //user/-/label/Folder
  1166. $dest = is_string($_POST['dest'] ?? null) ? trim($_POST['dest']) : ''; //user/-/label/NewFolder
  1167. self::renameTag($s, $dest);
  1168. // Always exits
  1169. case 'disable-tag': //https://github.com/theoldreader/api
  1170. $token = is_string($_POST['T'] ?? null) ? trim($_POST['T']) : '';
  1171. self::checkToken(FreshRSS_Context::userConf(), $token);
  1172. $s_s = self::multiplePosts('s');
  1173. foreach ($s_s as $s) {
  1174. self::disableTag($s); //user/-/label/Folder
  1175. }
  1176. // Always exits
  1177. case 'mark-all-as-read':
  1178. $token = is_string($_POST['T'] ?? null) ? trim($_POST['T']) : '';
  1179. self::checkToken(FreshRSS_Context::userConf(), $token);
  1180. $streamId = is_string($_POST['s'] ?? null) ? trim($_POST['s']) : '';
  1181. $ts = is_string($_POST['ts'] ?? null) ? trim($_POST['ts']) : '0'; //Older than timestamp in nanoseconds
  1182. if (!ctype_digit($ts)) {
  1183. self::badRequest();
  1184. }
  1185. self::markAllAsRead($streamId, $ts);
  1186. // Always exits
  1187. case 'token':
  1188. self::token(FreshRSS_Context::userConf());
  1189. // Always exits
  1190. case 'user-info':
  1191. self::userInfo();
  1192. // Always exits
  1193. }
  1194. }
  1195. self::badRequest();
  1196. }
  1197. }
  1198. GReaderAPI::parse();