functions.php 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248
  1. <?php
  2. define('EXPECTED_CONFIG_VERSION', 26);
  3. define('SCHEMA_VERSION', 116);
  4. define('LABEL_BASE_INDEX', -1024);
  5. define('PLUGIN_FEED_BASE_INDEX', -128);
  6. $fetch_last_error = false;
  7. $fetch_last_error_code = false;
  8. $fetch_last_content_type = false;
  9. $pluginhost = false;
  10. function __autoload($class) {
  11. $class_file = str_replace("_", "/", strtolower(basename($class)));
  12. $file = dirname(__FILE__)."/../classes/$class_file.php";
  13. if (file_exists($file)) {
  14. require $file;
  15. }
  16. }
  17. mb_internal_encoding("UTF-8");
  18. date_default_timezone_set('UTC');
  19. if (defined('E_DEPRECATED')) {
  20. error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
  21. } else {
  22. error_reporting(E_ALL & ~E_NOTICE);
  23. }
  24. require_once 'config.php';
  25. /**
  26. * Define a constant if not already defined
  27. *
  28. * @param string $name The constant name.
  29. * @param mixed $value The constant value.
  30. * @access public
  31. * @return boolean True if defined successfully or not.
  32. */
  33. function define_default($name, $value) {
  34. defined($name) or define($name, $value);
  35. }
  36. ///// Some defaults that you can override in config.php //////
  37. define_default('FEED_FETCH_TIMEOUT', 45);
  38. // How may seconds to wait for response when requesting feed from a site
  39. define_default('FEED_FETCH_NO_CACHE_TIMEOUT', 15);
  40. // How may seconds to wait for response when requesting feed from a
  41. // site when that feed wasn't cached before
  42. define_default('FILE_FETCH_TIMEOUT', 45);
  43. // Default timeout when fetching files from remote sites
  44. define_default('FILE_FETCH_CONNECT_TIMEOUT', 15);
  45. // How many seconds to wait for initial response from website when
  46. // fetching files from remote sites
  47. if (DB_TYPE == "pgsql") {
  48. define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
  49. } else {
  50. define('SUBSTRING_FOR_DATE', 'SUBSTRING');
  51. }
  52. /**
  53. * Return available translations names.
  54. *
  55. * @access public
  56. * @return array A array of available translations.
  57. */
  58. function get_translations() {
  59. $tr = array(
  60. "auto" => "Detect automatically",
  61. "ca_CA" => "Català",
  62. "cs_CZ" => "Česky",
  63. "en_US" => "English",
  64. "es_ES" => "Español",
  65. "de_DE" => "Deutsch",
  66. "fr_FR" => "Français",
  67. "hu_HU" => "Magyar (Hungarian)",
  68. "it_IT" => "Italiano",
  69. "ja_JP" => "日本語 (Japanese)",
  70. "lv_LV" => "Latviešu",
  71. "nb_NO" => "Norwegian bokmål",
  72. "nl_NL" => "Dutch",
  73. "pl_PL" => "Polski",
  74. "ru_RU" => "Русский",
  75. "pt_BR" => "Portuguese/Brazil",
  76. "zh_CN" => "Simplified Chinese",
  77. "sv_SE" => "Svenska",
  78. "fi_FI" => "Suomi");
  79. return $tr;
  80. }
  81. require_once "lib/accept-to-gettext.php";
  82. require_once "lib/gettext/gettext.inc";
  83. function startup_gettext() {
  84. # Get locale from Accept-Language header
  85. $lang = al2gt(array_keys(get_translations()), "text/html");
  86. if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
  87. $lang = _TRANSLATION_OVERRIDE_DEFAULT;
  88. }
  89. if ($_SESSION["language"] && $_SESSION["language"] != "auto") {
  90. $lang = $_SESSION["language"];
  91. }
  92. if ($lang) {
  93. if (defined('LC_MESSAGES')) {
  94. _setlocale(LC_MESSAGES, $lang);
  95. } else if (defined('LC_ALL')) {
  96. _setlocale(LC_ALL, $lang);
  97. }
  98. _bindtextdomain("messages", "locale");
  99. _textdomain("messages");
  100. _bind_textdomain_codeset("messages", "UTF-8");
  101. }
  102. }
  103. startup_gettext();
  104. require_once 'db-prefs.php';
  105. require_once 'version.php';
  106. require_once 'ccache.php';
  107. require_once 'labels.php';
  108. define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
  109. ini_set('user_agent', SELF_USER_AGENT);
  110. require_once 'lib/pubsubhubbub/publisher.php';
  111. $tz_offset = -1;
  112. $utc_tz = new DateTimeZone('UTC');
  113. $schema_version = false;
  114. /**
  115. * Print a timestamped debug message.
  116. *
  117. * @param string $msg The debug message.
  118. * @return void
  119. */
  120. function _debug($msg) {
  121. $ts = strftime("%H:%M:%S", time());
  122. if (function_exists('posix_getpid')) {
  123. $ts = "$ts/" . posix_getpid();
  124. }
  125. if (!(defined('QUIET') && QUIET)) {
  126. print "[$ts] $msg\n";
  127. }
  128. if (defined('LOGFILE')) {
  129. $fp = fopen(LOGFILE, 'a+');
  130. if ($fp) {
  131. fputs($fp, "[$ts] $msg\n");
  132. fclose($fp);
  133. }
  134. }
  135. } // function _debug
  136. /**
  137. * Purge a feed old posts.
  138. *
  139. * @param mixed $link A database connection.
  140. * @param mixed $feed_id The id of the purged feed.
  141. * @param mixed $purge_interval Olderness of purged posts.
  142. * @param boolean $debug Set to True to enable the debug. False by default.
  143. * @access public
  144. * @return void
  145. */
  146. function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
  147. if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
  148. $rows = -1;
  149. $result = db_query($link,
  150. "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
  151. $owner_uid = false;
  152. if (db_num_rows($result) == 1) {
  153. $owner_uid = db_fetch_result($result, 0, "owner_uid");
  154. }
  155. if ($purge_interval == -1 || !$purge_interval) {
  156. if ($owner_uid) {
  157. ccache_update($link, $feed_id, $owner_uid);
  158. }
  159. return;
  160. }
  161. if (!$owner_uid) return;
  162. if (FORCE_ARTICLE_PURGE == 0) {
  163. $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
  164. $owner_uid, false);
  165. } else {
  166. $purge_unread = true;
  167. $purge_interval = FORCE_ARTICLE_PURGE;
  168. }
  169. if (!$purge_unread) $query_limit = " unread = false AND ";
  170. if (DB_TYPE == "pgsql") {
  171. $pg_version = get_pgsql_version($link);
  172. if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
  173. $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
  174. ttrss_entries.id = ref_id AND
  175. marked = false AND
  176. feed_id = '$feed_id' AND
  177. $query_limit
  178. ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
  179. } else {
  180. $result = db_query($link, "DELETE FROM ttrss_user_entries
  181. USING ttrss_entries
  182. WHERE ttrss_entries.id = ref_id AND
  183. marked = false AND
  184. feed_id = '$feed_id' AND
  185. $query_limit
  186. ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
  187. }
  188. $rows = pg_affected_rows($result);
  189. } else {
  190. /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
  191. marked = false AND feed_id = '$feed_id' AND
  192. (SELECT date_updated FROM ttrss_entries WHERE
  193. id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
  194. $result = db_query($link, "DELETE FROM ttrss_user_entries
  195. USING ttrss_user_entries, ttrss_entries
  196. WHERE ttrss_entries.id = ref_id AND
  197. marked = false AND
  198. feed_id = '$feed_id' AND
  199. $query_limit
  200. ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
  201. $rows = mysql_affected_rows($link);
  202. }
  203. ccache_update($link, $feed_id, $owner_uid);
  204. if ($debug) {
  205. _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
  206. }
  207. return $rows;
  208. } // function purge_feed
  209. function feed_purge_interval($link, $feed_id) {
  210. $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
  211. WHERE id = '$feed_id'");
  212. if (db_num_rows($result) == 1) {
  213. $purge_interval = db_fetch_result($result, 0, "purge_interval");
  214. $owner_uid = db_fetch_result($result, 0, "owner_uid");
  215. if ($purge_interval == 0) $purge_interval = get_pref($link,
  216. 'PURGE_OLD_DAYS', $owner_uid);
  217. return $purge_interval;
  218. } else {
  219. return -1;
  220. }
  221. }
  222. function purge_orphans($link, $do_output = false) {
  223. // purge orphaned posts in main content table
  224. $result = db_query($link, "DELETE FROM ttrss_entries WHERE
  225. (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
  226. if ($do_output) {
  227. $rows = db_affected_rows($link, $result);
  228. _debug("Purged $rows orphaned posts.");
  229. }
  230. }
  231. function get_feed_update_interval($link, $feed_id) {
  232. $result = db_query($link, "SELECT owner_uid, update_interval FROM
  233. ttrss_feeds WHERE id = '$feed_id'");
  234. if (db_num_rows($result) == 1) {
  235. $update_interval = db_fetch_result($result, 0, "update_interval");
  236. $owner_uid = db_fetch_result($result, 0, "owner_uid");
  237. if ($update_interval != 0) {
  238. return $update_interval;
  239. } else {
  240. return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
  241. }
  242. } else {
  243. return -1;
  244. }
  245. }
  246. function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false, $timeout = false, $timestamp = 0) {
  247. global $fetch_last_error;
  248. global $fetch_last_error_code;
  249. global $fetch_last_content_type;
  250. $url = str_replace(' ', '%20', $url);
  251. if (!defined('NO_CURL') && function_exists('curl_init') && !ini_get("open_basedir")) {
  252. if (ini_get("safe_mode")) {
  253. $ch = curl_init(geturl($url));
  254. } else {
  255. $ch = curl_init($url);
  256. }
  257. if ($timestamp) {
  258. curl_setopt($ch, CURLOPT_HTTPHEADER,
  259. array("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $timestamp)));
  260. }
  261. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout ? $timeout : FILE_FETCH_CONNECT_TIMEOUT);
  262. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout ? $timeout : FILE_FETCH_TIMEOUT);
  263. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("safe_mode"));
  264. curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
  265. curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
  266. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  267. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  268. curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  269. curl_setopt($ch, CURLOPT_USERAGENT, SELF_USER_AGENT);
  270. curl_setopt($ch, CURLOPT_ENCODING , "gzip");
  271. curl_setopt($ch, CURLOPT_REFERER, $url);
  272. if ($post_query) {
  273. curl_setopt($ch, CURLOPT_POST, true);
  274. curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
  275. }
  276. if ($login && $pass)
  277. curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
  278. $contents = @curl_exec($ch);
  279. if (curl_errno($ch) === 23 || curl_errno($ch) === 61) {
  280. curl_setopt($ch, CURLOPT_ENCODING, 'none');
  281. $contents = @curl_exec($ch);
  282. }
  283. if ($contents === false) {
  284. $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
  285. curl_close($ch);
  286. return false;
  287. }
  288. $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  289. $fetch_last_content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
  290. $fetch_last_error_code = $http_code;
  291. if ($http_code != 200 || $type && strpos($fetch_last_content_type, "$type") === false) {
  292. if (curl_errno($ch) != 0) {
  293. $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
  294. } else {
  295. $fetch_last_error = "HTTP Code: $http_code";
  296. }
  297. curl_close($ch);
  298. return false;
  299. }
  300. curl_close($ch);
  301. return $contents;
  302. } else {
  303. if ($login && $pass){
  304. $url_parts = array();
  305. preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
  306. $pass = urlencode($pass);
  307. if ($url_parts[1] && $url_parts[2]) {
  308. $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
  309. }
  310. }
  311. $data = @file_get_contents($url);
  312. $fetch_last_content_type = false; // reset if no type was sent from server
  313. foreach ($http_response_header as $h) {
  314. if (substr(strtolower($h), 0, 13) == 'content-type:') {
  315. $fetch_last_content_type = substr($h, 14);
  316. // don't abort here b/c there might be more than one
  317. // e.g. if we were being redirected -- last one is the right one
  318. }
  319. }
  320. if (!$data && function_exists('error_get_last')) {
  321. $error = error_get_last();
  322. $fetch_last_error = $error["message"];
  323. }
  324. return $data;
  325. }
  326. }
  327. /**
  328. * Try to determine the favicon URL for a feed.
  329. * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
  330. * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
  331. *
  332. * @param string $url A feed or page URL
  333. * @access public
  334. * @return mixed The favicon URL, or false if none was found.
  335. */
  336. function get_favicon_url($url) {
  337. $favicon_url = false;
  338. if ($html = @fetch_file_contents($url)) {
  339. libxml_use_internal_errors(true);
  340. $doc = new DOMDocument();
  341. $doc->loadHTML($html);
  342. $xpath = new DOMXPath($doc);
  343. $base = $xpath->query('/html/head/base');
  344. foreach ($base as $b) {
  345. $url = $b->getAttribute("href");
  346. break;
  347. }
  348. $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
  349. if (count($entries) > 0) {
  350. foreach ($entries as $entry) {
  351. $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
  352. break;
  353. }
  354. }
  355. }
  356. if (!$favicon_url)
  357. $favicon_url = rewrite_relative_url($url, "/favicon.ico");
  358. return $favicon_url;
  359. } // function get_favicon_url
  360. function check_feed_favicon($site_url, $feed, $link) {
  361. # print "FAVICON [$site_url]: $favicon_url\n";
  362. $icon_file = ICONS_DIR . "/$feed.ico";
  363. if (!file_exists($icon_file)) {
  364. $favicon_url = get_favicon_url($site_url);
  365. if ($favicon_url) {
  366. // Limiting to "image" type misses those served with text/plain
  367. $contents = fetch_file_contents($favicon_url); // , "image");
  368. if ($contents) {
  369. // Crude image type matching.
  370. // Patterns gleaned from the file(1) source code.
  371. if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
  372. // 0 string \000\000\001\000 MS Windows icon resource
  373. //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
  374. }
  375. elseif (preg_match('/^GIF8/', $contents)) {
  376. // 0 string GIF8 GIF image data
  377. //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
  378. }
  379. elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
  380. // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
  381. //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
  382. }
  383. elseif (preg_match('/^\xff\xd8/', $contents)) {
  384. // 0 beshort 0xffd8 JPEG image data
  385. //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
  386. }
  387. else {
  388. //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
  389. $contents = "";
  390. }
  391. }
  392. if ($contents) {
  393. $fp = @fopen($icon_file, "w");
  394. if ($fp) {
  395. fwrite($fp, $contents);
  396. fclose($fp);
  397. chmod($icon_file, 0644);
  398. }
  399. }
  400. }
  401. }
  402. }
  403. function print_select($id, $default, $values, $attributes = "") {
  404. print "<select name=\"$id\" id=\"$id\" $attributes>";
  405. foreach ($values as $v) {
  406. if ($v == $default)
  407. $sel = "selected=\"1\"";
  408. else
  409. $sel = "";
  410. $v = trim($v);
  411. print "<option value=\"$v\" $sel>$v</option>";
  412. }
  413. print "</select>";
  414. }
  415. function print_select_hash($id, $default, $values, $attributes = "") {
  416. print "<select name=\"$id\" id='$id' $attributes>";
  417. foreach (array_keys($values) as $v) {
  418. if ($v == $default)
  419. $sel = 'selected="selected"';
  420. else
  421. $sel = "";
  422. $v = trim($v);
  423. print "<option $sel value=\"$v\">".$values[$v]."</option>";
  424. }
  425. print "</select>";
  426. }
  427. function print_radio($id, $default, $true_is, $values, $attributes = "") {
  428. foreach ($values as $v) {
  429. if ($v == $default)
  430. $sel = "checked";
  431. else
  432. $sel = "";
  433. if ($v == $true_is) {
  434. $sel .= " value=\"1\"";
  435. } else {
  436. $sel .= " value=\"0\"";
  437. }
  438. print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
  439. type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
  440. }
  441. }
  442. function initialize_user_prefs($link, $uid, $profile = false) {
  443. $uid = db_escape_string($link, $uid);
  444. if (!$profile) {
  445. $profile = "NULL";
  446. $profile_qpart = "AND profile IS NULL";
  447. } else {
  448. $profile_qpart = "AND profile = '$profile'";
  449. }
  450. if (get_schema_version($link) < 63) $profile_qpart = "";
  451. db_query($link, "BEGIN");
  452. $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
  453. $u_result = db_query($link, "SELECT pref_name
  454. FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
  455. $active_prefs = array();
  456. while ($line = db_fetch_assoc($u_result)) {
  457. array_push($active_prefs, $line["pref_name"]);
  458. }
  459. while ($line = db_fetch_assoc($result)) {
  460. if (array_search($line["pref_name"], $active_prefs) === FALSE) {
  461. // print "adding " . $line["pref_name"] . "<br>";
  462. $line["def_value"] = db_escape_string($link, $line["def_value"]);
  463. $line["pref_name"] = db_escape_string($link, $line["pref_name"]);
  464. if (get_schema_version($link) < 63) {
  465. db_query($link, "INSERT INTO ttrss_user_prefs
  466. (owner_uid,pref_name,value) VALUES
  467. ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
  468. } else {
  469. db_query($link, "INSERT INTO ttrss_user_prefs
  470. (owner_uid,pref_name,value, profile) VALUES
  471. ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
  472. }
  473. }
  474. }
  475. db_query($link, "COMMIT");
  476. }
  477. function get_ssl_certificate_id() {
  478. if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
  479. return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
  480. $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
  481. $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
  482. $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
  483. }
  484. return "";
  485. }
  486. function authenticate_user($link, $login, $password, $check_only = false) {
  487. if (!SINGLE_USER_MODE) {
  488. $user_id = false;
  489. global $pluginhost;
  490. foreach ($pluginhost->get_hooks($pluginhost::HOOK_AUTH_USER) as $plugin) {
  491. $user_id = (int) $plugin->authenticate($login, $password);
  492. if ($user_id) {
  493. $_SESSION["auth_module"] = strtolower(get_class($plugin));
  494. break;
  495. }
  496. }
  497. if ($user_id && !$check_only) {
  498. @session_start();
  499. $_SESSION["uid"] = $user_id;
  500. $_SESSION["version"] = VERSION;
  501. $result = db_query($link, "SELECT login,access_level,pwd_hash FROM ttrss_users
  502. WHERE id = '$user_id'");
  503. $_SESSION["name"] = db_fetch_result($result, 0, "login");
  504. $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
  505. $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
  506. db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
  507. $_SESSION["uid"]);
  508. $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
  509. $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
  510. $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
  511. $_SESSION["last_version_check"] = time();
  512. initialize_user_prefs($link, $_SESSION["uid"]);
  513. return true;
  514. }
  515. return false;
  516. } else {
  517. $_SESSION["uid"] = 1;
  518. $_SESSION["name"] = "admin";
  519. $_SESSION["access_level"] = 10;
  520. $_SESSION["hide_hello"] = true;
  521. $_SESSION["hide_logout"] = true;
  522. $_SESSION["auth_module"] = false;
  523. if (!$_SESSION["csrf_token"]) {
  524. $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
  525. }
  526. $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
  527. initialize_user_prefs($link, $_SESSION["uid"]);
  528. return true;
  529. }
  530. }
  531. function make_password($length = 8) {
  532. $password = "";
  533. $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
  534. $i = 0;
  535. while ($i < $length) {
  536. $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
  537. if (!strstr($password, $char)) {
  538. $password .= $char;
  539. $i++;
  540. }
  541. }
  542. return $password;
  543. }
  544. // this is called after user is created to initialize default feeds, labels
  545. // or whatever else
  546. // user preferences are checked on every login, not here
  547. function initialize_user($link, $uid) {
  548. db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
  549. values ('$uid', 'Tiny Tiny RSS: New Releases',
  550. 'http://tt-rss.org/releases.rss')");
  551. db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
  552. values ('$uid', 'Tiny Tiny RSS: Forum',
  553. 'http://tt-rss.org/forum/rss.php')");
  554. }
  555. function logout_user() {
  556. session_destroy();
  557. if (isset($_COOKIE[session_name()])) {
  558. setcookie(session_name(), '', time()-42000, '/');
  559. }
  560. }
  561. function validate_csrf($csrf_token) {
  562. return $csrf_token == $_SESSION['csrf_token'];
  563. }
  564. function load_user_plugins($link, $owner_uid) {
  565. if ($owner_uid) {
  566. $plugins = get_pref($link, "_ENABLED_PLUGINS", $owner_uid);
  567. global $pluginhost;
  568. $pluginhost->load($plugins, $pluginhost::KIND_USER, $owner_uid);
  569. if (get_schema_version($link) > 100) {
  570. $pluginhost->load_data();
  571. }
  572. }
  573. }
  574. function login_sequence($link) {
  575. $_SESSION["prefs_cache"] = false;
  576. if (SINGLE_USER_MODE) {
  577. @session_start();
  578. authenticate_user($link, "admin", null);
  579. cache_prefs($link);
  580. load_user_plugins($link, $_SESSION["uid"]);
  581. } else {
  582. if (!validate_session($link)) $_SESSION["uid"] = false;
  583. if (!$_SESSION["uid"]) {
  584. if (AUTH_AUTO_LOGIN && authenticate_user($link, null, null)) {
  585. $_SESSION["ref_schema_version"] = get_schema_version($link, true);
  586. } else {
  587. authenticate_user($link, null, null, true);
  588. }
  589. if (!$_SESSION["uid"]) {
  590. @session_destroy();
  591. setcookie(session_name(), '', time()-42000, '/');
  592. render_login_form($link);
  593. exit;
  594. }
  595. } else {
  596. /* bump login timestamp */
  597. db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
  598. $_SESSION["uid"]);
  599. $_SESSION["last_login_update"] = time();
  600. }
  601. if ($_SESSION["uid"] && $_SESSION["language"] && SESSION_COOKIE_LIFETIME > 0) {
  602. setcookie("ttrss_lang", $_SESSION["language"],
  603. time() + SESSION_COOKIE_LIFETIME);
  604. }
  605. if ($_SESSION["uid"]) {
  606. cache_prefs($link);
  607. load_user_plugins($link, $_SESSION["uid"]);
  608. /* cleanup ccache */
  609. db_query($link, "DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
  610. $_SESSION["uid"] . " AND
  611. (SELECT COUNT(id) FROM ttrss_feeds WHERE
  612. ttrss_feeds.id = feed_id) = 0");
  613. db_query($link, "DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
  614. $_SESSION["uid"] . " AND
  615. (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
  616. ttrss_feed_categories.id = feed_id) = 0");
  617. }
  618. }
  619. }
  620. function truncate_string($str, $max_len, $suffix = '&hellip;') {
  621. if (mb_strlen($str, "utf-8") > $max_len - 3) {
  622. return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
  623. } else {
  624. return $str;
  625. }
  626. }
  627. function convert_timestamp($timestamp, $source_tz, $dest_tz) {
  628. try {
  629. $source_tz = new DateTimeZone($source_tz);
  630. } catch (Exception $e) {
  631. $source_tz = new DateTimeZone('UTC');
  632. }
  633. try {
  634. $dest_tz = new DateTimeZone($dest_tz);
  635. } catch (Exception $e) {
  636. $dest_tz = new DateTimeZone('UTC');
  637. }
  638. $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
  639. return $dt->format('U') + $dest_tz->getOffset($dt);
  640. }
  641. function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
  642. $no_smart_dt = false) {
  643. if (!$owner_uid) $owner_uid = $_SESSION['uid'];
  644. if (!$timestamp) $timestamp = '1970-01-01 0:00';
  645. global $utc_tz;
  646. global $tz_offset;
  647. # We store date in UTC internally
  648. $dt = new DateTime($timestamp, $utc_tz);
  649. if ($tz_offset == -1) {
  650. $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
  651. try {
  652. $user_tz = new DateTimeZone($user_tz_string);
  653. } catch (Exception $e) {
  654. $user_tz = $utc_tz;
  655. }
  656. $tz_offset = $user_tz->getOffset($dt);
  657. }
  658. $user_timestamp = $dt->format('U') + $tz_offset;
  659. if (!$no_smart_dt) {
  660. return smart_date_time($link, $user_timestamp,
  661. $tz_offset, $owner_uid);
  662. } else {
  663. if ($long)
  664. $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
  665. else
  666. $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
  667. return date($format, $user_timestamp);
  668. }
  669. }
  670. function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
  671. if (!$owner_uid) $owner_uid = $_SESSION['uid'];
  672. if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
  673. return date("G:i", $timestamp);
  674. } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
  675. $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
  676. return date($format, $timestamp);
  677. } else {
  678. $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
  679. return date($format, $timestamp);
  680. }
  681. }
  682. function sql_bool_to_bool($s) {
  683. if ($s == "t" || $s == "1" || strtolower($s) == "true") {
  684. return true;
  685. } else {
  686. return false;
  687. }
  688. }
  689. function bool_to_sql_bool($s) {
  690. if ($s) {
  691. return "true";
  692. } else {
  693. return "false";
  694. }
  695. }
  696. // Session caching removed due to causing wrong redirects to upgrade
  697. // script when get_schema_version() is called on an obsolete session
  698. // created on a previous schema version.
  699. function get_schema_version($link, $nocache = false) {
  700. global $schema_version;
  701. if (!$schema_version) {
  702. $result = db_query($link, "SELECT schema_version FROM ttrss_version");
  703. $version = db_fetch_result($result, 0, "schema_version");
  704. $schema_version = $version;
  705. return $version;
  706. } else {
  707. return $schema_version;
  708. }
  709. }
  710. function sanity_check($link) {
  711. require_once 'errors.php';
  712. $error_code = 0;
  713. $schema_version = get_schema_version($link, true);
  714. if ($schema_version != SCHEMA_VERSION) {
  715. $error_code = 5;
  716. }
  717. if (DB_TYPE == "mysql") {
  718. $result = db_query($link, "SELECT true", false);
  719. if (db_num_rows($result) != 1) {
  720. $error_code = 10;
  721. }
  722. }
  723. if (db_escape_string($link, "testTEST") != "testTEST") {
  724. $error_code = 12;
  725. }
  726. return array("code" => $error_code, "message" => $ERRORS[$error_code]);
  727. }
  728. function file_is_locked($filename) {
  729. if (function_exists('flock')) {
  730. $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
  731. if ($fp) {
  732. if (flock($fp, LOCK_EX | LOCK_NB)) {
  733. flock($fp, LOCK_UN);
  734. fclose($fp);
  735. return false;
  736. }
  737. fclose($fp);
  738. return true;
  739. } else {
  740. return false;
  741. }
  742. }
  743. return true; // consider the file always locked and skip the test
  744. }
  745. function make_lockfile($filename) {
  746. $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
  747. if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
  748. if (function_exists('posix_getpid')) {
  749. fwrite($fp, posix_getpid() . "\n");
  750. }
  751. return $fp;
  752. } else {
  753. return false;
  754. }
  755. }
  756. function make_stampfile($filename) {
  757. $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
  758. if (flock($fp, LOCK_EX | LOCK_NB)) {
  759. fwrite($fp, time() . "\n");
  760. flock($fp, LOCK_UN);
  761. fclose($fp);
  762. return true;
  763. } else {
  764. return false;
  765. }
  766. }
  767. function sql_random_function() {
  768. if (DB_TYPE == "mysql") {
  769. return "RAND()";
  770. } else {
  771. return "RANDOM()";
  772. }
  773. }
  774. function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false, $mode = 'all') {
  775. if (!$owner_uid) $owner_uid = $_SESSION['uid'];
  776. //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
  777. // Todo: all this interval stuff needs some generic generator function
  778. $date_qpart = "false";
  779. switch ($mode) {
  780. case "1day":
  781. if (DB_TYPE == "pgsql") {
  782. $date_qpart = "date_entered < NOW() - INTERVAL '1 day' ";
  783. } else {
  784. $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY) ";
  785. }
  786. break;
  787. case "1week":
  788. if (DB_TYPE == "pgsql") {
  789. $date_qpart = "date_entered < NOW() - INTERVAL '1 week' ";
  790. } else {
  791. $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 WEEK) ";
  792. }
  793. break;
  794. case "2weeks":
  795. if (DB_TYPE == "pgsql") {
  796. $date_qpart = "date_entered < NOW() - INTERVAL '2 week' ";
  797. } else {
  798. $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 2 WEEK) ";
  799. }
  800. break;
  801. default:
  802. $date_qpart = "true";
  803. }
  804. if (is_numeric($feed)) {
  805. if ($cat_view) {
  806. if ($feed >= 0) {
  807. if ($feed > 0) {
  808. $children = getChildCategories($link, $feed, $owner_uid);
  809. array_push($children, $feed);
  810. $children = join(",", $children);
  811. $cat_qpart = "cat_id IN ($children)";
  812. } else {
  813. $cat_qpart = "cat_id IS NULL";
  814. }
  815. db_query($link, "UPDATE ttrss_user_entries
  816. SET unread = false, last_read = NOW() WHERE ref_id IN
  817. (SELECT id FROM
  818. (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
  819. AND owner_uid = $owner_uid AND unread = true AND feed_id IN
  820. (SELECT id FROM ttrss_feeds WHERE $cat_qpart) AND $date_qpart) as tmp)");
  821. } else if ($feed == -2) {
  822. db_query($link, "UPDATE ttrss_user_entries
  823. SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
  824. FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
  825. AND unread = true AND $date_qpart AND owner_uid = $owner_uid");
  826. }
  827. } else if ($feed > 0) {
  828. db_query($link, "UPDATE ttrss_user_entries
  829. SET unread = false, last_read = NOW() WHERE ref_id IN
  830. (SELECT id FROM
  831. (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
  832. AND owner_uid = $owner_uid AND unread = true AND feed_id = $feed AND $date_qpart) as tmp)");
  833. } else if ($feed < 0 && $feed > LABEL_BASE_INDEX) { // special, like starred
  834. if ($feed == -1) {
  835. db_query($link, "UPDATE ttrss_user_entries
  836. SET unread = false, last_read = NOW() WHERE ref_id IN
  837. (SELECT id FROM
  838. (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
  839. AND owner_uid = $owner_uid AND unread = true AND marked = true AND $date_qpart) as tmp)");
  840. }
  841. if ($feed == -2) {
  842. db_query($link, "UPDATE ttrss_user_entries
  843. SET unread = false, last_read = NOW() WHERE ref_id IN
  844. (SELECT id FROM
  845. (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
  846. AND owner_uid = $owner_uid AND unread = true AND published = true AND $date_qpart) as tmp)");
  847. }
  848. if ($feed == -3) {
  849. $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
  850. if (DB_TYPE == "pgsql") {
  851. $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
  852. } else {
  853. $match_part = "date_entered > DATE_SUB(NOW(),
  854. INTERVAL $intl HOUR) ";
  855. }
  856. db_query($link, "UPDATE ttrss_user_entries
  857. SET unread = false, last_read = NOW() WHERE ref_id IN
  858. (SELECT id FROM
  859. (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
  860. AND owner_uid = $owner_uid AND unread = true AND $date_qpart AND $match_part) as tmp)");
  861. }
  862. if ($feed == -4) {
  863. db_query($link, "UPDATE ttrss_user_entries
  864. SET unread = false, last_read = NOW() WHERE ref_id IN
  865. (SELECT id FROM
  866. (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
  867. AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
  868. }
  869. } else if ($feed < LABEL_BASE_INDEX) { // label
  870. $label_id = feed_to_label_id($feed);
  871. db_query($link, "UPDATE ttrss_user_entries
  872. SET unread = false, last_read = NOW() WHERE ref_id IN
  873. (SELECT id FROM
  874. (SELECT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_user_labels2 WHERE ref_id = id
  875. AND label_id = '$label_id' AND ref_id = article_id
  876. AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
  877. }
  878. ccache_update($link, $feed, $owner_uid, $cat_view);
  879. } else { // tag
  880. db_query($link, "UPDATE ttrss_user_entries
  881. SET unread = false, last_read = NOW() WHERE ref_id IN
  882. (SELECT id FROM
  883. (SELECT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_tags WHERE ref_id = ttrss_entries.id
  884. AND post_int_id = int_id AND tag_name = '$feed'
  885. AND ttrss_user_entries.owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
  886. }
  887. }
  888. function getAllCounters($link) {
  889. $data = getGlobalCounters($link);
  890. $data = array_merge($data, getVirtCounters($link));
  891. $data = array_merge($data, getLabelCounters($link));
  892. $data = array_merge($data, getFeedCounters($link, $active_feed));
  893. $data = array_merge($data, getCategoryCounters($link));
  894. return $data;
  895. }
  896. function getCategoryTitle($link, $cat_id) {
  897. if ($cat_id == -1) {
  898. return __("Special");
  899. } else if ($cat_id == -2) {
  900. return __("Labels");
  901. } else {
  902. $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
  903. id = '$cat_id'");
  904. if (db_num_rows($result) == 1) {
  905. return db_fetch_result($result, 0, "title");
  906. } else {
  907. return __("Uncategorized");
  908. }
  909. }
  910. }
  911. function getCategoryCounters($link) {
  912. $ret_arr = array();
  913. /* Labels category */
  914. $cv = array("id" => -2, "kind" => "cat",
  915. "counter" => getCategoryUnread($link, -2));
  916. array_push($ret_arr, $cv);
  917. $result = db_query($link, "SELECT id AS cat_id, value AS unread,
  918. (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
  919. WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
  920. FROM ttrss_feed_categories, ttrss_cat_counters_cache
  921. WHERE ttrss_cat_counters_cache.feed_id = id AND
  922. ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
  923. ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
  924. while ($line = db_fetch_assoc($result)) {
  925. $line["cat_id"] = (int) $line["cat_id"];
  926. if ($line["num_children"] > 0) {
  927. $child_counter = getCategoryChildrenUnread($link, $line["cat_id"], $_SESSION["uid"]);
  928. } else {
  929. $child_counter = 0;
  930. }
  931. $cv = array("id" => $line["cat_id"], "kind" => "cat",
  932. "counter" => $line["unread"] + $child_counter);
  933. array_push($ret_arr, $cv);
  934. }
  935. /* Special case: NULL category doesn't actually exist in the DB */
  936. $cv = array("id" => 0, "kind" => "cat",
  937. "counter" => (int) ccache_find($link, 0, $_SESSION["uid"], true));
  938. array_push($ret_arr, $cv);
  939. return $ret_arr;
  940. }
  941. // only accepts real cats (>= 0)
  942. function getCategoryChildrenUnread($link, $cat, $owner_uid = false) {
  943. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  944. $result = db_query($link, "SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
  945. AND owner_uid = $owner_uid");
  946. $unread = 0;
  947. while ($line = db_fetch_assoc($result)) {
  948. $unread += getCategoryUnread($link, $line["id"], $owner_uid);
  949. $unread += getCategoryChildrenUnread($link, $line["id"], $owner_uid);
  950. }
  951. return $unread;
  952. }
  953. function getCategoryUnread($link, $cat, $owner_uid = false) {
  954. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  955. if ($cat >= 0) {
  956. if ($cat != 0) {
  957. $cat_query = "cat_id = '$cat'";
  958. } else {
  959. $cat_query = "cat_id IS NULL";
  960. }
  961. $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
  962. AND owner_uid = " . $owner_uid);
  963. $cat_feeds = array();
  964. while ($line = db_fetch_assoc($result)) {
  965. array_push($cat_feeds, "feed_id = " . $line["id"]);
  966. }
  967. if (count($cat_feeds) == 0) return 0;
  968. $match_part = implode(" OR ", $cat_feeds);
  969. $result = db_query($link, "SELECT COUNT(int_id) AS unread
  970. FROM ttrss_user_entries
  971. WHERE unread = true AND ($match_part)
  972. AND owner_uid = " . $owner_uid);
  973. $unread = 0;
  974. # this needs to be rewritten
  975. while ($line = db_fetch_assoc($result)) {
  976. $unread += $line["unread"];
  977. }
  978. return $unread;
  979. } else if ($cat == -1) {
  980. return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3) + getFeedUnread($link, 0);
  981. } else if ($cat == -2) {
  982. $result = db_query($link, "
  983. SELECT COUNT(unread) AS unread FROM
  984. ttrss_user_entries, ttrss_user_labels2
  985. WHERE article_id = ref_id AND unread = true
  986. AND ttrss_user_entries.owner_uid = '$owner_uid'");
  987. $unread = db_fetch_result($result, 0, "unread");
  988. return $unread;
  989. }
  990. }
  991. function getFeedUnread($link, $feed, $is_cat = false) {
  992. return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
  993. }
  994. function getLabelUnread($link, $label_id, $owner_uid = false) {
  995. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  996. $result = db_query($link, "SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
  997. WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
  998. if (db_num_rows($result) != 0) {
  999. return db_fetch_result($result, 0, "unread");
  1000. } else {
  1001. return 0;
  1002. }
  1003. }
  1004. function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
  1005. $owner_uid = false) {
  1006. $n_feed = (int) $feed;
  1007. $need_entries = false;
  1008. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  1009. if ($unread_only) {
  1010. $unread_qpart = "unread = true";
  1011. } else {
  1012. $unread_qpart = "true";
  1013. }
  1014. if ($is_cat) {
  1015. return getCategoryUnread($link, $n_feed, $owner_uid);
  1016. } else if ($n_feed == -6) {
  1017. return 0;
  1018. } else if ($feed != "0" && $n_feed == 0) {
  1019. $feed = db_escape_string($link, $feed);
  1020. $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
  1021. FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
  1022. AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
  1023. WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
  1024. return db_fetch_result($result, 0, "count");
  1025. } else if ($n_feed == -1) {
  1026. $match_part = "marked = true";
  1027. } else if ($n_feed == -2) {
  1028. $match_part = "published = true";
  1029. } else if ($n_feed == -3) {
  1030. $match_part = "unread = true AND score >= 0";
  1031. $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
  1032. if (DB_TYPE == "pgsql") {
  1033. $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
  1034. } else {
  1035. $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
  1036. }
  1037. $need_entries = true;
  1038. } else if ($n_feed == -4) {
  1039. $match_part = "true";
  1040. } else if ($n_feed >= 0) {
  1041. if ($n_feed != 0) {
  1042. $match_part = "feed_id = '$n_feed'";
  1043. } else {
  1044. $match_part = "feed_id IS NULL";
  1045. }
  1046. } else if ($feed < LABEL_BASE_INDEX) {
  1047. $label_id = feed_to_label_id($feed);
  1048. return getLabelUnread($link, $label_id, $owner_uid);
  1049. }
  1050. if ($match_part) {
  1051. if ($need_entries) {
  1052. $from_qpart = "ttrss_user_entries,ttrss_entries";
  1053. $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
  1054. } else {
  1055. $from_qpart = "ttrss_user_entries";
  1056. }
  1057. $query = "SELECT count(int_id) AS unread
  1058. FROM $from_qpart WHERE
  1059. $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
  1060. //echo "[$feed/$query]\n";
  1061. $result = db_query($link, $query);
  1062. } else {
  1063. $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
  1064. FROM ttrss_tags,ttrss_user_entries,ttrss_entries
  1065. WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
  1066. AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
  1067. }
  1068. $unread = db_fetch_result($result, 0, "unread");
  1069. return $unread;
  1070. }
  1071. function getGlobalUnread($link, $user_id = false) {
  1072. if (!$user_id) {
  1073. $user_id = $_SESSION["uid"];
  1074. }
  1075. $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
  1076. WHERE owner_uid = '$user_id' AND feed_id > 0");
  1077. $c_id = db_fetch_result($result, 0, "c_id");
  1078. return $c_id;
  1079. }
  1080. function getGlobalCounters($link, $global_unread = -1) {
  1081. $ret_arr = array();
  1082. if ($global_unread == -1) {
  1083. $global_unread = getGlobalUnread($link);
  1084. }
  1085. $cv = array("id" => "global-unread",
  1086. "counter" => (int) $global_unread);
  1087. array_push($ret_arr, $cv);
  1088. $result = db_query($link, "SELECT COUNT(id) AS fn FROM
  1089. ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
  1090. $subscribed_feeds = db_fetch_result($result, 0, "fn");
  1091. $cv = array("id" => "subscribed-feeds",
  1092. "counter" => (int) $subscribed_feeds);
  1093. array_push($ret_arr, $cv);
  1094. return $ret_arr;
  1095. }
  1096. function getVirtCounters($link) {
  1097. $ret_arr = array();
  1098. for ($i = 0; $i >= -4; $i--) {
  1099. $count = getFeedUnread($link, $i);
  1100. $cv = array("id" => $i,
  1101. "counter" => (int) $count);
  1102. // if (get_pref($link, 'EXTENDED_FEEDLIST'))
  1103. // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
  1104. array_push($ret_arr, $cv);
  1105. }
  1106. global $pluginhost;
  1107. if ($pluginhost) {
  1108. $feeds = $pluginhost->get_feeds(-1);
  1109. if (is_array($feeds)) {
  1110. foreach ($feeds as $feed) {
  1111. $cv = array("id" => PluginHost::pfeed_to_feed_id($feed['id']),
  1112. "counter" => $feed['sender']->get_unread($feed['id']));
  1113. array_push($ret_arr, $cv);
  1114. }
  1115. }
  1116. }
  1117. return $ret_arr;
  1118. }
  1119. function getLabelCounters($link, $descriptions = false) {
  1120. $ret_arr = array();
  1121. $owner_uid = $_SESSION["uid"];
  1122. $result = db_query($link, "SELECT id,caption,COUNT(unread) AS unread
  1123. FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
  1124. (ttrss_labels2.id = label_id)
  1125. LEFT JOIN ttrss_user_entries ON (ref_id = article_id AND unread = true
  1126. AND ttrss_user_entries.owner_uid = $owner_uid)
  1127. WHERE ttrss_labels2.owner_uid = $owner_uid GROUP BY ttrss_labels2.id,
  1128. ttrss_labels2.caption");
  1129. while ($line = db_fetch_assoc($result)) {
  1130. $id = label_to_feed_id($line["id"]);
  1131. $label_name = $line["caption"];
  1132. $count = $line["unread"];
  1133. $cv = array("id" => $id,
  1134. "counter" => (int) $count);
  1135. if ($descriptions)
  1136. $cv["description"] = $label_name;
  1137. // if (get_pref($link, 'EXTENDED_FEEDLIST'))
  1138. // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
  1139. array_push($ret_arr, $cv);
  1140. }
  1141. return $ret_arr;
  1142. }
  1143. function getFeedCounters($link, $active_feed = false) {
  1144. $ret_arr = array();
  1145. $query = "SELECT ttrss_feeds.id,
  1146. ttrss_feeds.title,
  1147. ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
  1148. last_error, value AS count
  1149. FROM ttrss_feeds, ttrss_counters_cache
  1150. WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
  1151. AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
  1152. AND ttrss_counters_cache.feed_id = id";
  1153. $result = db_query($link, $query);
  1154. $fctrs_modified = false;
  1155. while ($line = db_fetch_assoc($result)) {
  1156. $id = $line["id"];
  1157. $count = $line["count"];
  1158. $last_error = htmlspecialchars($line["last_error"]);
  1159. $last_updated = make_local_datetime($link, $line['last_updated'], false);
  1160. $has_img = feed_has_icon($id);
  1161. if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
  1162. $last_updated = '';
  1163. $cv = array("id" => $id,
  1164. "updated" => $last_updated,
  1165. "counter" => (int) $count,
  1166. "has_img" => (int) $has_img);
  1167. if ($last_error)
  1168. $cv["error"] = $last_error;
  1169. // if (get_pref($link, 'EXTENDED_FEEDLIST'))
  1170. // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
  1171. if ($active_feed && $id == $active_feed)
  1172. $cv["title"] = truncate_string($line["title"], 30);
  1173. array_push($ret_arr, $cv);
  1174. }
  1175. return $ret_arr;
  1176. }
  1177. function get_pgsql_version($link) {
  1178. $result = db_query($link, "SELECT version() AS version");
  1179. $version = explode(" ", db_fetch_result($result, 0, "version"));
  1180. return $version[1];
  1181. }
  1182. /**
  1183. * @return array (code => Status code, message => error message if available)
  1184. *
  1185. * 0 - OK, Feed already exists
  1186. * 1 - OK, Feed added
  1187. * 2 - Invalid URL
  1188. * 3 - URL content is HTML, no feeds available
  1189. * 4 - URL content is HTML which contains multiple feeds.
  1190. * Here you should call extractfeedurls in rpc-backend
  1191. * to get all possible feeds.
  1192. * 5 - Couldn't download the URL content.
  1193. */
  1194. function subscribe_to_feed($link, $url, $cat_id = 0,
  1195. $auth_login = '', $auth_pass = '') {
  1196. global $fetch_last_error;
  1197. require_once "include/rssfuncs.php";
  1198. $url = fix_url($url);
  1199. if (!$url || !validate_feed_url($url)) return array("code" => 2);
  1200. $contents = @fetch_file_contents($url, false, $auth_login, $auth_pass);
  1201. if (!$contents) {
  1202. return array("code" => 5, "message" => $fetch_last_error);
  1203. }
  1204. if (is_html($contents)) {
  1205. $feedUrls = get_feeds_from_html($url, $contents);
  1206. if (count($feedUrls) == 0) {
  1207. return array("code" => 3);
  1208. } else if (count($feedUrls) > 1) {
  1209. return array("code" => 4, "feeds" => $feedUrls);
  1210. }
  1211. //use feed url as new URL
  1212. $url = key($feedUrls);
  1213. }
  1214. if ($cat_id == "0" || !$cat_id) {
  1215. $cat_qpart = "NULL";
  1216. } else {
  1217. $cat_qpart = "'$cat_id'";
  1218. }
  1219. $result = db_query($link,
  1220. "SELECT id FROM ttrss_feeds
  1221. WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
  1222. if (db_num_rows($result) == 0) {
  1223. $result = db_query($link,
  1224. "INSERT INTO ttrss_feeds
  1225. (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
  1226. VALUES ('".$_SESSION["uid"]."', '$url',
  1227. '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0)");
  1228. $result = db_query($link,
  1229. "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
  1230. AND owner_uid = " . $_SESSION["uid"]);
  1231. $feed_id = db_fetch_result($result, 0, "id");
  1232. if ($feed_id) {
  1233. update_rss_feed($link, $feed_id, true);
  1234. }
  1235. return array("code" => 1);
  1236. } else {
  1237. return array("code" => 0);
  1238. }
  1239. }
  1240. function print_feed_select($link, $id, $default_id = "",
  1241. $attributes = "", $include_all_feeds = true,
  1242. $root_id = false, $nest_level = 0) {
  1243. if (!$root_id) {
  1244. print "<select id=\"$id\" name=\"$id\" $attributes>";
  1245. if ($include_all_feeds) {
  1246. $is_selected = ("0" == $default_id) ? "selected=\"1\"" : "";
  1247. print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
  1248. }
  1249. }
  1250. if (get_pref($link, 'ENABLE_FEED_CATS')) {
  1251. if ($root_id)
  1252. $parent_qpart = "parent_cat = '$root_id'";
  1253. else
  1254. $parent_qpart = "parent_cat IS NULL";
  1255. $result = db_query($link, "SELECT id,title,
  1256. (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
  1257. c2.parent_cat = ttrss_feed_categories.id) AS num_children
  1258. FROM ttrss_feed_categories
  1259. WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
  1260. while ($line = db_fetch_assoc($result)) {
  1261. for ($i = 0; $i < $nest_level; $i++)
  1262. $line["title"] = " - " . $line["title"];
  1263. $is_selected = ("CAT:".$line["id"] == $default_id) ? "selected=\"1\"" : "";
  1264. printf("<option $is_selected value='CAT:%d'>%s</option>",
  1265. $line["id"], htmlspecialchars($line["title"]));
  1266. if ($line["num_children"] > 0)
  1267. print_feed_select($link, $id, $default_id, $attributes,
  1268. $include_all_feeds, $line["id"], $nest_level+1);
  1269. $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
  1270. WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
  1271. while ($fline = db_fetch_assoc($feed_result)) {
  1272. $is_selected = ($fline["id"] == $default_id) ? "selected=\"1\"" : "";
  1273. $fline["title"] = " + " . $fline["title"];
  1274. for ($i = 0; $i < $nest_level; $i++)
  1275. $fline["title"] = " - " . $fline["title"];
  1276. printf("<option $is_selected value='%d'>%s</option>",
  1277. $fline["id"], htmlspecialchars($fline["title"]));
  1278. }
  1279. }
  1280. if (!$root_id) {
  1281. $is_selected = ($default_id == "CAT:0") ? "selected=\"1\"" : "";
  1282. printf("<option $is_selected value='CAT:0'>%s</option>",
  1283. __("Uncategorized"));
  1284. $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
  1285. WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
  1286. while ($fline = db_fetch_assoc($feed_result)) {
  1287. $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ? "selected=\"1\"" : "";
  1288. $fline["title"] = " + " . $fline["title"];
  1289. for ($i = 0; $i < $nest_level; $i++)
  1290. $fline["title"] = " - " . $fline["title"];
  1291. printf("<option $is_selected value='%d'>%s</option>",
  1292. $fline["id"], htmlspecialchars($fline["title"]));
  1293. }
  1294. }
  1295. } else {
  1296. $result = db_query($link, "SELECT id,title FROM ttrss_feeds
  1297. WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
  1298. while ($line = db_fetch_assoc($result)) {
  1299. $is_selected = ($line["id"] == $default_id) ? "selected=\"1\"" : "";
  1300. printf("<option $is_selected value='%d'>%s</option>",
  1301. $line["id"], htmlspecialchars($line["title"]));
  1302. }
  1303. }
  1304. if (!$root_id) {
  1305. print "</select>";
  1306. }
  1307. }
  1308. function print_feed_cat_select($link, $id, $default_id,
  1309. $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
  1310. if (!$root_id) {
  1311. print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
  1312. }
  1313. if ($root_id)
  1314. $parent_qpart = "parent_cat = '$root_id'";
  1315. else
  1316. $parent_qpart = "parent_cat IS NULL";
  1317. $result = db_query($link, "SELECT id,title,
  1318. (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
  1319. c2.parent_cat = ttrss_feed_categories.id) AS num_children
  1320. FROM ttrss_feed_categories
  1321. WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
  1322. while ($line = db_fetch_assoc($result)) {
  1323. if ($line["id"] == $default_id) {
  1324. $is_selected = "selected=\"1\"";
  1325. } else {
  1326. $is_selected = "";
  1327. }
  1328. for ($i = 0; $i < $nest_level; $i++)
  1329. $line["title"] = " - " . $line["title"];
  1330. if ($line["title"])
  1331. printf("<option $is_selected value='%d'>%s</option>",
  1332. $line["id"], htmlspecialchars($line["title"]));
  1333. if ($line["num_children"] > 0)
  1334. print_feed_cat_select($link, $id, $default_id, $attributes,
  1335. $include_all_cats, $line["id"], $nest_level+1);
  1336. }
  1337. if (!$root_id) {
  1338. if ($include_all_cats) {
  1339. if (db_num_rows($result) > 0) {
  1340. print "<option disabled=\"1\">--------</option>";
  1341. }
  1342. if ($default_id == 0) {
  1343. $is_selected = "selected=\"1\"";
  1344. } else {
  1345. $is_selected = "";
  1346. }
  1347. print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
  1348. }
  1349. print "</select>";
  1350. }
  1351. }
  1352. function checkbox_to_sql_bool($val) {
  1353. return ($val == "on") ? "true" : "false";
  1354. }
  1355. function getFeedCatTitle($link, $id) {
  1356. if ($id == -1) {
  1357. return __("Special");
  1358. } else if ($id < LABEL_BASE_INDEX) {
  1359. return __("Labels");
  1360. } else if ($id > 0) {
  1361. $result = db_query($link, "SELECT ttrss_feed_categories.title
  1362. FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
  1363. cat_id = ttrss_feed_categories.id");
  1364. if (db_num_rows($result) == 1) {
  1365. return db_fetch_result($result, 0, "title");
  1366. } else {
  1367. return __("Uncategorized");
  1368. }
  1369. } else {
  1370. return "getFeedCatTitle($id) failed";
  1371. }
  1372. }
  1373. function getFeedIcon($id) {
  1374. switch ($id) {
  1375. case 0:
  1376. return "images/archive.png";
  1377. break;
  1378. case -1:
  1379. return "images/mark_set.svg";
  1380. break;
  1381. case -2:
  1382. return "images/pub_set.svg";
  1383. break;
  1384. case -3:
  1385. return "images/fresh.png";
  1386. break;
  1387. case -4:
  1388. return "images/tag.png";
  1389. break;
  1390. case -6:
  1391. return "images/recently_read.png";
  1392. break;
  1393. default:
  1394. if ($id < LABEL_BASE_INDEX) {
  1395. return "images/label.png";
  1396. } else {
  1397. if (file_exists(ICONS_DIR . "/$id.ico"))
  1398. return ICONS_URL . "/$id.ico";
  1399. }
  1400. break;
  1401. }
  1402. }
  1403. function getFeedTitle($link, $id, $cat = false) {
  1404. if ($cat) {
  1405. return getCategoryTitle($link, $id);
  1406. } else if ($id == -1) {
  1407. return __("Starred articles");
  1408. } else if ($id == -2) {
  1409. return __("Published articles");
  1410. } else if ($id == -3) {
  1411. return __("Fresh articles");
  1412. } else if ($id == -4) {
  1413. return __("All articles");
  1414. } else if ($id === 0 || $id === "0") {
  1415. return __("Archived articles");
  1416. } else if ($id == -6) {
  1417. return __("Recently read");
  1418. } else if ($id < LABEL_BASE_INDEX) {
  1419. $label_id = feed_to_label_id($id);
  1420. $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
  1421. if (db_num_rows($result) == 1) {
  1422. return db_fetch_result($result, 0, "caption");
  1423. } else {
  1424. return "Unknown label ($label_id)";
  1425. }
  1426. } else if (is_numeric($id) && $id > 0) {
  1427. $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
  1428. if (db_num_rows($result) == 1) {
  1429. return db_fetch_result($result, 0, "title");
  1430. } else {
  1431. return "Unknown feed ($id)";
  1432. }
  1433. } else {
  1434. return $id;
  1435. }
  1436. }
  1437. function make_init_params($link) {
  1438. $params = array();
  1439. foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
  1440. "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
  1441. "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE",
  1442. "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
  1443. $params[strtolower($param)] = (int) get_pref($link, $param);
  1444. }
  1445. $params["icons_url"] = ICONS_URL;
  1446. $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME;
  1447. $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
  1448. $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
  1449. $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
  1450. $params["bw_limit"] = (int) $_SESSION["bw_limit"];
  1451. $params["label_base_index"] = (int) LABEL_BASE_INDEX;
  1452. $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
  1453. ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
  1454. $max_feed_id = db_fetch_result($result, 0, "mid");
  1455. $num_feeds = db_fetch_result($result, 0, "nf");
  1456. $params["max_feed_id"] = (int) $max_feed_id;
  1457. $params["num_feeds"] = (int) $num_feeds;
  1458. $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
  1459. $params["hotkeys"] = get_hotkeys_map($link);
  1460. $params["csrf_token"] = $_SESSION["csrf_token"];
  1461. $params["widescreen"] = (int) $_COOKIE["ttrss_widescreen"];
  1462. $params['simple_update'] = defined('SIMPLE_UPDATE_MODE') && SIMPLE_UPDATE_MODE;
  1463. return $params;
  1464. }
  1465. function get_hotkeys_info($link) {
  1466. $hotkeys = array(
  1467. __("Navigation") => array(
  1468. "next_feed" => __("Open next feed"),
  1469. "prev_feed" => __("Open previous feed"),
  1470. "next_article" => __("Open next article"),
  1471. "prev_article" => __("Open previous article"),
  1472. "next_article_noscroll" => __("Open next article (don't scroll long articles)"),
  1473. "prev_article_noscroll" => __("Open previous article (don't scroll long articles)"),
  1474. "next_article_noexpand" => __("Move to next article (don't expand or mark read)"),
  1475. "prev_article_noexpand" => __("Move to previous article (don't expand or mark read)"),
  1476. "search_dialog" => __("Show search dialog")),
  1477. __("Article") => array(
  1478. "toggle_mark" => __("Toggle starred"),
  1479. "toggle_publ" => __("Toggle published"),
  1480. "toggle_unread" => __("Toggle unread"),
  1481. "edit_tags" => __("Edit tags"),
  1482. "dismiss_selected" => __("Dismiss selected"),
  1483. "dismiss_read" => __("Dismiss read"),
  1484. "open_in_new_window" => __("Open in new window"),
  1485. "catchup_below" => __("Mark below as read"),
  1486. "catchup_above" => __("Mark above as read"),
  1487. "article_scroll_down" => __("Scroll down"),
  1488. "article_scroll_up" => __("Scroll up"),
  1489. "select_article_cursor" => __("Select article under cursor"),
  1490. "email_article" => __("Email article"),
  1491. "close_article" => __("Close/collapse article"),
  1492. "toggle_expand" => __("Toggle article expansion (combined mode)"),
  1493. "toggle_widescreen" => __("Toggle widescreen mode"),
  1494. "toggle_embed_original" => __("Toggle embed original")),
  1495. __("Article selection") => array(
  1496. "select_all" => __("Select all articles"),
  1497. "select_unread" => __("Select unread"),
  1498. "select_marked" => __("Select starred"),
  1499. "select_published" => __("Select published"),
  1500. "select_invert" => __("Invert selection"),
  1501. "select_none" => __("Deselect everything")),
  1502. __("Feed") => array(
  1503. "feed_refresh" => __("Refresh current feed"),
  1504. "feed_unhide_read" => __("Un/hide read feeds"),
  1505. "feed_subscribe" => __("Subscribe to feed"),
  1506. "feed_edit" => __("Edit feed"),
  1507. "feed_catchup" => __("Mark as read"),
  1508. "feed_reverse" => __("Reverse headlines"),
  1509. "feed_debug_update" => __("Debug feed update"),
  1510. "catchup_all" => __("Mark all feeds as read"),
  1511. "cat_toggle_collapse" => __("Un/collapse current category"),
  1512. "toggle_combined_mode" => __("Toggle combined mode"),
  1513. "toggle_cdm_expanded" => __("Toggle auto expand in combined mode")),
  1514. __("Go to") => array(
  1515. "goto_all" => __("All articles"),
  1516. "goto_fresh" => __("Fresh"),
  1517. "goto_marked" => __("Starred"),
  1518. "goto_published" => __("Published"),
  1519. "goto_tagcloud" => __("Tag cloud"),
  1520. "goto_prefs" => __("Preferences")),
  1521. __("Other") => array(
  1522. "create_label" => __("Create label"),
  1523. "create_filter" => __("Create filter"),
  1524. "collapse_sidebar" => __("Un/collapse sidebar"),
  1525. "help_dialog" => __("Show help dialog"))
  1526. );
  1527. global $pluginhost;
  1528. foreach ($pluginhost->get_hooks($pluginhost::HOOK_HOTKEY_INFO) as $plugin) {
  1529. $hotkeys = $plugin->hook_hotkey_info($hotkeys);
  1530. }
  1531. return $hotkeys;
  1532. }
  1533. function get_hotkeys_map($link) {
  1534. $hotkeys = array(
  1535. // "navigation" => array(
  1536. "k" => "next_feed",
  1537. "j" => "prev_feed",
  1538. "n" => "next_article",
  1539. "p" => "prev_article",
  1540. "(38)|up" => "prev_article",
  1541. "(40)|down" => "next_article",
  1542. // "^(38)|Ctrl-up" => "prev_article_noscroll",
  1543. // "^(40)|Ctrl-down" => "next_article_noscroll",
  1544. "(191)|/" => "search_dialog",
  1545. // "article" => array(
  1546. "s" => "toggle_mark",
  1547. "*s" => "toggle_publ",
  1548. "u" => "toggle_unread",
  1549. "*t" => "edit_tags",
  1550. "*d" => "dismiss_selected",
  1551. "*x" => "dismiss_read",
  1552. "o" => "open_in_new_window",
  1553. "c p" => "catchup_below",
  1554. "c n" => "catchup_above",
  1555. "*n" => "article_scroll_down",
  1556. "*p" => "article_scroll_up",
  1557. "*(38)|Shift+up" => "article_scroll_up",
  1558. "*(40)|Shift+down" => "article_scroll_down",
  1559. "a *w" => "toggle_widescreen",
  1560. "a e" => "toggle_embed_original",
  1561. "e" => "email_article",
  1562. "a q" => "close_article",
  1563. // "article_selection" => array(
  1564. "a a" => "select_all",
  1565. "a u" => "select_unread",
  1566. "a *u" => "select_marked",
  1567. "a p" => "select_published",
  1568. "a i" => "select_invert",
  1569. "a n" => "select_none",
  1570. // "feed" => array(
  1571. "f r" => "feed_refresh",
  1572. "f a" => "feed_unhide_read",
  1573. "f s" => "feed_subscribe",
  1574. "f e" => "feed_edit",
  1575. "f q" => "feed_catchup",
  1576. "f x" => "feed_reverse",
  1577. "f *d" => "feed_debug_update",
  1578. "f *c" => "toggle_combined_mode",
  1579. "f c" => "toggle_cdm_expanded",
  1580. "*q" => "catchup_all",
  1581. "x" => "cat_toggle_collapse",
  1582. // "goto" => array(
  1583. "g a" => "goto_all",
  1584. "g f" => "goto_fresh",
  1585. "g s" => "goto_marked",
  1586. "g p" => "goto_published",
  1587. "g t" => "goto_tagcloud",
  1588. "g *p" => "goto_prefs",
  1589. // "other" => array(
  1590. "(9)|Tab" => "select_article_cursor", // tab
  1591. "c l" => "create_label",
  1592. "c f" => "create_filter",
  1593. "c s" => "collapse_sidebar",
  1594. "^(191)|Ctrl+/" => "help_dialog",
  1595. );
  1596. if (get_pref($link, 'COMBINED_DISPLAY_MODE')) {
  1597. $hotkeys["^(38)|Ctrl-up"] = "prev_article_noscroll";
  1598. $hotkeys["^(40)|Ctrl-down"] = "next_article_noscroll";
  1599. }
  1600. global $pluginhost;
  1601. foreach ($pluginhost->get_hooks($pluginhost::HOOK_HOTKEY_MAP) as $plugin) {
  1602. $hotkeys = $plugin->hook_hotkey_map($hotkeys);
  1603. }
  1604. $prefixes = array();
  1605. foreach (array_keys($hotkeys) as $hotkey) {
  1606. $pair = explode(" ", $hotkey, 2);
  1607. if (count($pair) > 1 && !in_array($pair[0], $prefixes)) {
  1608. array_push($prefixes, $pair[0]);
  1609. }
  1610. }
  1611. return array($prefixes, $hotkeys);
  1612. }
  1613. function make_runtime_info($link) {
  1614. $data = array();
  1615. $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
  1616. ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
  1617. $max_feed_id = db_fetch_result($result, 0, "mid");
  1618. $num_feeds = db_fetch_result($result, 0, "nf");
  1619. $data["max_feed_id"] = (int) $max_feed_id;
  1620. $data["num_feeds"] = (int) $num_feeds;
  1621. $data['last_article_id'] = getLastArticleId($link);
  1622. $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
  1623. $data['dep_ts'] = calculate_dep_timestamp();
  1624. $data['reload_on_ts_change'] = !defined('_NO_RELOAD_ON_TS_CHANGE');
  1625. if (file_exists(LOCK_DIRECTORY . "/update_daemon.lock")) {
  1626. $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
  1627. if (time() - $_SESSION["daemon_stamp_check"] > 30) {
  1628. $stamp = (int) @file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp");
  1629. if ($stamp) {
  1630. $stamp_delta = time() - $stamp;
  1631. if ($stamp_delta > 1800) {
  1632. $stamp_check = 0;
  1633. } else {
  1634. $stamp_check = 1;
  1635. $_SESSION["daemon_stamp_check"] = time();
  1636. }
  1637. $data['daemon_stamp_ok'] = $stamp_check;
  1638. $stamp_fmt = date("Y.m.d, G:i", $stamp);
  1639. $data['daemon_stamp'] = $stamp_fmt;
  1640. }
  1641. }
  1642. }
  1643. if ($_SESSION["last_version_check"] + 86400 + rand(-1000, 1000) < time()) {
  1644. $new_version_details = @check_for_update($link);
  1645. $data['new_version_available'] = (int) ($new_version_details != false);
  1646. $_SESSION["last_version_check"] = time();
  1647. $_SESSION["version_data"] = $new_version_details;
  1648. }
  1649. return $data;
  1650. }
  1651. function search_to_sql($link, $search) {
  1652. $search_query_part = "";
  1653. $keywords = explode(" ", $search);
  1654. $query_keywords = array();
  1655. foreach ($keywords as $k) {
  1656. if (strpos($k, "-") === 0) {
  1657. $k = substr($k, 1);
  1658. $not = "NOT";
  1659. } else {
  1660. $not = "";
  1661. }
  1662. $commandpair = explode(":", mb_strtolower($k), 2);
  1663. switch ($commandpair[0]) {
  1664. case "title":
  1665. if ($commandpair[1]) {
  1666. array_push($query_keywords, "($not (LOWER(ttrss_entries.title) LIKE '%".
  1667. db_escape_string($link, mb_strtolower($commandpair[1]))."%'))");
  1668. } else {
  1669. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  1670. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  1671. }
  1672. break;
  1673. case "author":
  1674. if ($commandpair[1]) {
  1675. array_push($query_keywords, "($not (LOWER(author) LIKE '%".
  1676. db_escape_string($link, mb_strtolower($commandpair[1]))."%'))");
  1677. } else {
  1678. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  1679. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  1680. }
  1681. break;
  1682. case "note":
  1683. if ($commandpair[1]) {
  1684. if ($commandpair[1] == "true")
  1685. array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
  1686. else if ($commandpair[1] == "false")
  1687. array_push($query_keywords, "($not (note IS NULL OR note = ''))");
  1688. else
  1689. array_push($query_keywords, "($not (LOWER(note) LIKE '%".
  1690. db_escape_string($link, mb_strtolower($commandpair[1]))."%'))");
  1691. } else {
  1692. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  1693. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  1694. }
  1695. break;
  1696. case "star":
  1697. if ($commandpair[1]) {
  1698. if ($commandpair[1] == "true")
  1699. array_push($query_keywords, "($not (marked = true))");
  1700. else
  1701. array_push($query_keywords, "($not (marked = false))");
  1702. } else {
  1703. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  1704. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  1705. }
  1706. break;
  1707. case "pub":
  1708. if ($commandpair[1]) {
  1709. if ($commandpair[1] == "true")
  1710. array_push($query_keywords, "($not (published = true))");
  1711. else
  1712. array_push($query_keywords, "($not (published = false))");
  1713. } else {
  1714. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  1715. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  1716. }
  1717. break;
  1718. default:
  1719. if (strpos($k, "@") === 0) {
  1720. $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
  1721. $orig_ts = strtotime(substr($k, 1));
  1722. $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
  1723. //$k = date("Y-m-d", strtotime(substr($k, 1)));
  1724. array_push($query_keywords, "(".SUBSTRING_FOR_DATE."(updated,1,LENGTH('$k')) $not = '$k')");
  1725. } else {
  1726. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  1727. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  1728. }
  1729. }
  1730. }
  1731. $search_query_part = implode("AND", $query_keywords);
  1732. return $search_query_part;
  1733. }
  1734. function getParentCategories($link, $cat, $owner_uid) {
  1735. $rv = array();
  1736. $result = db_query($link, "SELECT parent_cat FROM ttrss_feed_categories
  1737. WHERE id = '$cat' AND parent_cat IS NOT NULL AND owner_uid = $owner_uid");
  1738. while ($line = db_fetch_assoc($result)) {
  1739. array_push($rv, $line["parent_cat"]);
  1740. $rv = array_merge($rv, getParentCategories($link, $line["parent_cat"], $owner_uid));
  1741. }
  1742. return $rv;
  1743. }
  1744. function getChildCategories($link, $cat, $owner_uid) {
  1745. $rv = array();
  1746. $result = db_query($link, "SELECT id FROM ttrss_feed_categories
  1747. WHERE parent_cat = '$cat' AND owner_uid = $owner_uid");
  1748. while ($line = db_fetch_assoc($result)) {
  1749. array_push($rv, $line["id"]);
  1750. $rv = array_merge($rv, getChildCategories($link, $line["id"], $owner_uid));
  1751. }
  1752. return $rv;
  1753. }
  1754. function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $override_order = false, $offset = 0, $owner_uid = 0, $filter = false, $since_id = 0, $include_children = false, $ignore_vfeed_group = false) {
  1755. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  1756. $ext_tables_part = "";
  1757. if ($search) {
  1758. if (SPHINX_ENABLED) {
  1759. $ids = join(",", @sphinx_search($search, 0, 500));
  1760. if ($ids)
  1761. $search_query_part = "ref_id IN ($ids) AND ";
  1762. else
  1763. $search_query_part = "ref_id = -1 AND ";
  1764. } else {
  1765. $search_query_part = search_to_sql($link, $search);
  1766. $search_query_part .= " AND ";
  1767. }
  1768. } else {
  1769. $search_query_part = "";
  1770. }
  1771. if ($filter) {
  1772. if (DB_TYPE == "pgsql") {
  1773. $query_strategy_part .= " AND updated > NOW() - INTERVAL '14 days' ";
  1774. } else {
  1775. $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL 14 DAY) ";
  1776. }
  1777. $override_order = "updated DESC";
  1778. $filter_query_part = filter_to_sql($link, $filter, $owner_uid);
  1779. // Try to check if SQL regexp implementation chokes on a valid regexp
  1780. $result = db_query($link, "SELECT true AS true_val FROM ttrss_entries,
  1781. ttrss_user_entries, ttrss_feeds, ttrss_feed_categories
  1782. WHERE $filter_query_part LIMIT 1", false);
  1783. if ($result) {
  1784. $test = db_fetch_result($result, 0, "true_val");
  1785. if (!$test) {
  1786. $filter_query_part = "false AND";
  1787. } else {
  1788. $filter_query_part .= " AND";
  1789. }
  1790. } else {
  1791. $filter_query_part = "false AND";
  1792. }
  1793. } else {
  1794. $filter_query_part = "";
  1795. }
  1796. if ($since_id) {
  1797. $since_id_part = "ttrss_entries.id > $since_id AND ";
  1798. } else {
  1799. $since_id_part = "";
  1800. }
  1801. $view_query_part = "";
  1802. if ($view_mode == "adaptive") {
  1803. if ($search) {
  1804. $view_query_part = " ";
  1805. } else if ($feed != -1) {
  1806. $unread = getFeedUnread($link, $feed, $cat_view);
  1807. if ($cat_view && $feed > 0 && $include_children)
  1808. $unread += getCategoryChildrenUnread($link, $feed);
  1809. if ($unread > 0)
  1810. $view_query_part = " unread = true AND ";
  1811. }
  1812. }
  1813. if ($view_mode == "marked") {
  1814. $view_query_part = " marked = true AND ";
  1815. }
  1816. if ($view_mode == "has_note") {
  1817. $view_query_part = " (note IS NOT NULL AND note != '') AND ";
  1818. }
  1819. if ($view_mode == "published") {
  1820. $view_query_part = " published = true AND ";
  1821. }
  1822. if ($view_mode == "unread" && $feed != -6) {
  1823. $view_query_part = " unread = true AND ";
  1824. }
  1825. if ($limit > 0) {
  1826. $limit_query_part = "LIMIT " . $limit;
  1827. }
  1828. $allow_archived = false;
  1829. $vfeed_query_part = "";
  1830. // override query strategy and enable feed display when searching globally
  1831. if ($search && $search_mode == "all_feeds") {
  1832. $query_strategy_part = "true";
  1833. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1834. /* tags */
  1835. } else if (!is_numeric($feed)) {
  1836. $query_strategy_part = "true";
  1837. $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
  1838. id = feed_id) as feed_title,";
  1839. } else if ($search && $search_mode == "this_cat") {
  1840. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1841. if ($feed > 0) {
  1842. if ($include_children) {
  1843. $subcats = getChildCategories($link, $feed, $owner_uid);
  1844. array_push($subcats, $feed);
  1845. $cats_qpart = join(",", $subcats);
  1846. } else {
  1847. $cats_qpart = $feed;
  1848. }
  1849. $query_strategy_part = "ttrss_feeds.cat_id IN ($cats_qpart)";
  1850. } else {
  1851. $query_strategy_part = "ttrss_feeds.cat_id IS NULL";
  1852. }
  1853. } else if ($feed > 0) {
  1854. if ($cat_view) {
  1855. if ($feed > 0) {
  1856. if ($include_children) {
  1857. # sub-cats
  1858. $subcats = getChildCategories($link, $feed, $owner_uid);
  1859. array_push($subcats, $feed);
  1860. $query_strategy_part = "cat_id IN (".
  1861. implode(",", $subcats).")";
  1862. } else {
  1863. $query_strategy_part = "cat_id = '$feed'";
  1864. }
  1865. } else {
  1866. $query_strategy_part = "cat_id IS NULL";
  1867. }
  1868. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1869. } else {
  1870. $query_strategy_part = "feed_id = '$feed'";
  1871. }
  1872. } else if ($feed == 0 && !$cat_view) { // archive virtual feed
  1873. $query_strategy_part = "feed_id IS NULL";
  1874. $allow_archived = true;
  1875. } else if ($feed == 0 && $cat_view) { // uncategorized
  1876. $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
  1877. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1878. } else if ($feed == -1) { // starred virtual feed
  1879. $query_strategy_part = "marked = true";
  1880. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1881. $allow_archived = true;
  1882. if (!$override_order) {
  1883. $override_order = "last_marked DESC, date_entered DESC, updated DESC";
  1884. }
  1885. } else if ($feed == -2) { // published virtual feed OR labels category
  1886. if (!$cat_view) {
  1887. $query_strategy_part = "published = true";
  1888. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1889. $allow_archived = true;
  1890. if (!$override_order) {
  1891. $override_order = "last_published DESC, date_entered DESC, updated DESC";
  1892. }
  1893. } else {
  1894. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1895. $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
  1896. $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
  1897. ttrss_user_labels2.article_id = ref_id";
  1898. }
  1899. } else if ($feed == -6) { // recently read
  1900. $query_strategy_part = "unread = false AND last_read IS NOT NULL";
  1901. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1902. $allow_archived = true;
  1903. if (!$override_order) $override_order = "last_read DESC";
  1904. } else if ($feed == -3) { // fresh virtual feed
  1905. $query_strategy_part = "unread = true AND score >= 0";
  1906. $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
  1907. if (DB_TYPE == "pgsql") {
  1908. $query_strategy_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
  1909. } else {
  1910. $query_strategy_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
  1911. }
  1912. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1913. } else if ($feed == -4) { // all articles virtual feed
  1914. $allow_archived = true;
  1915. $query_strategy_part = "true";
  1916. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1917. } else if ($feed <= LABEL_BASE_INDEX) { // labels
  1918. $label_id = feed_to_label_id($feed);
  1919. $query_strategy_part = "label_id = '$label_id' AND
  1920. ttrss_labels2.id = ttrss_user_labels2.label_id AND
  1921. ttrss_user_labels2.article_id = ref_id";
  1922. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1923. $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
  1924. $allow_archived = true;
  1925. } else {
  1926. $query_strategy_part = "true";
  1927. }
  1928. $order_by = "score DESC, date_entered DESC, updated DESC";
  1929. if ($view_mode == "unread_first") {
  1930. $order_by = "unread DESC, $order_by";
  1931. }
  1932. if ($override_order) {
  1933. $order_by = $override_order;
  1934. }
  1935. $feed_title = "";
  1936. if ($search) {
  1937. $feed_title = T_sprintf("Search results: %s", $search);
  1938. } else {
  1939. if ($cat_view) {
  1940. $feed_title = getCategoryTitle($link, $feed);
  1941. } else {
  1942. if (is_numeric($feed) && $feed > 0) {
  1943. $result = db_query($link, "SELECT title,site_url,last_error
  1944. FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
  1945. $feed_title = db_fetch_result($result, 0, "title");
  1946. $feed_site_url = db_fetch_result($result, 0, "site_url");
  1947. $last_error = db_fetch_result($result, 0, "last_error");
  1948. } else {
  1949. $feed_title = getFeedTitle($link, $feed);
  1950. }
  1951. }
  1952. }
  1953. $content_query_part = "content as content_preview, cached_content, ";
  1954. if (is_numeric($feed)) {
  1955. if ($feed >= 0) {
  1956. $feed_kind = "Feeds";
  1957. } else {
  1958. $feed_kind = "Labels";
  1959. }
  1960. if ($limit_query_part) {
  1961. $offset_query_part = "OFFSET $offset";
  1962. }
  1963. // proper override_order applied above
  1964. if ($vfeed_query_part && !$ignore_vfeed_group && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
  1965. if (!$override_order) {
  1966. $order_by = "ttrss_feeds.title, $order_by";
  1967. } else {
  1968. $order_by = "ttrss_feeds.title, $override_order";
  1969. }
  1970. }
  1971. if (!$allow_archived) {
  1972. $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
  1973. $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
  1974. } else {
  1975. $from_qpart = "ttrss_entries$ext_tables_part,ttrss_user_entries
  1976. LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
  1977. }
  1978. $query = "SELECT DISTINCT
  1979. date_entered,
  1980. guid,
  1981. ttrss_entries.id,ttrss_entries.title,
  1982. updated,
  1983. label_cache,
  1984. tag_cache,
  1985. always_display_enclosures,
  1986. site_url,
  1987. note,
  1988. num_comments,
  1989. comments,
  1990. int_id,
  1991. hide_images,
  1992. unread,feed_id,marked,published,link,last_read,orig_feed_id,
  1993. last_marked, last_published,
  1994. $vfeed_query_part
  1995. $content_query_part
  1996. author,score
  1997. FROM
  1998. $from_qpart
  1999. WHERE
  2000. $feed_check_qpart
  2001. ttrss_user_entries.ref_id = ttrss_entries.id AND
  2002. ttrss_user_entries.owner_uid = '$owner_uid' AND
  2003. $search_query_part
  2004. $filter_query_part
  2005. $view_query_part
  2006. $since_id_part
  2007. $query_strategy_part ORDER BY $order_by
  2008. $limit_query_part $offset_query_part";
  2009. if ($_REQUEST["debug"]) print $query;
  2010. $result = db_query($link, $query);
  2011. } else {
  2012. // browsing by tag
  2013. $select_qpart = "SELECT DISTINCT " .
  2014. "date_entered," .
  2015. "guid," .
  2016. "note," .
  2017. "ttrss_entries.id as id," .
  2018. "title," .
  2019. "updated," .
  2020. "unread," .
  2021. "feed_id," .
  2022. "orig_feed_id," .
  2023. "marked," .
  2024. "num_comments, " .
  2025. "comments, " .
  2026. "tag_cache," .
  2027. "label_cache," .
  2028. "link," .
  2029. "last_read," .
  2030. "(SELECT hide_images FROM ttrss_feeds WHERE id = feed_id) AS hide_images," .
  2031. "last_marked, last_published, " .
  2032. $since_id_part .
  2033. $vfeed_query_part .
  2034. $content_query_part .
  2035. "score ";
  2036. $feed_kind = "Tags";
  2037. $all_tags = explode(",", $feed);
  2038. if ($search_mode == 'any') {
  2039. $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
  2040. $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
  2041. $where_qpart = " WHERE " .
  2042. "ref_id = ttrss_entries.id AND " .
  2043. "ttrss_user_entries.owner_uid = $owner_uid AND " .
  2044. "post_int_id = int_id AND $tag_sql AND " .
  2045. $view_query_part .
  2046. $search_query_part .
  2047. $query_strategy_part . " ORDER BY $order_by " .
  2048. $limit_query_part;
  2049. } else {
  2050. $i = 1;
  2051. $sub_selects = array();
  2052. $sub_ands = array();
  2053. foreach ($all_tags as $term) {
  2054. array_push($sub_selects, "(SELECT post_int_id from ttrss_tags WHERE tag_name = " . db_quote($term) . " AND owner_uid = $owner_uid) as A$i");
  2055. $i++;
  2056. }
  2057. if ($i > 2) {
  2058. $x = 1;
  2059. $y = 2;
  2060. do {
  2061. array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
  2062. $x++;
  2063. $y++;
  2064. } while ($y < $i);
  2065. }
  2066. array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
  2067. array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
  2068. $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
  2069. $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
  2070. }
  2071. // error_log("TAG SQL: " . $tag_sql);
  2072. // $tag_sql = "tag_name = '$feed'"; DEFAULT way
  2073. // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
  2074. $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
  2075. }
  2076. return array($result, $feed_title, $feed_site_url, $last_error);
  2077. }
  2078. function sanitize($link, $str, $force_remove_images = false, $owner = false, $site_url = false) {
  2079. if (!$owner) $owner = $_SESSION["uid"];
  2080. $res = trim($str); if (!$res) return '';
  2081. if (strpos($res, "href=") === false)
  2082. $res = rewrite_urls($res);
  2083. $charset_hack = '<head>
  2084. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  2085. </head>';
  2086. $res = trim($res); if (!$res) return '';
  2087. libxml_use_internal_errors(true);
  2088. $doc = new DOMDocument();
  2089. $doc->loadHTML($charset_hack . $res);
  2090. $xpath = new DOMXPath($doc);
  2091. $entries = $xpath->query('(//a[@href]|//img[@src])');
  2092. foreach ($entries as $entry) {
  2093. if ($site_url) {
  2094. if ($entry->hasAttribute('href'))
  2095. $entry->setAttribute('href',
  2096. rewrite_relative_url($site_url, $entry->getAttribute('href')));
  2097. if ($entry->hasAttribute('src')) {
  2098. $src = rewrite_relative_url($site_url, $entry->getAttribute('src'));
  2099. $cached_filename = CACHE_DIR . '/images/' . sha1($src) . '.png';
  2100. if (file_exists($cached_filename)) {
  2101. $src = SELF_URL_PATH . '/image.php?hash=' . sha1($src);
  2102. }
  2103. $entry->setAttribute('src', $src);
  2104. }
  2105. if ($entry->nodeName == 'img') {
  2106. if (($owner && get_pref($link, "STRIP_IMAGES", $owner)) ||
  2107. $force_remove_images || $_SESSION["bw_limit"]) {
  2108. $p = $doc->createElement('p');
  2109. $a = $doc->createElement('a');
  2110. $a->setAttribute('href', $entry->getAttribute('src'));
  2111. $a->appendChild(new DOMText($entry->getAttribute('src')));
  2112. $a->setAttribute('target', '_blank');
  2113. $p->appendChild($a);
  2114. $entry->parentNode->replaceChild($p, $entry);
  2115. }
  2116. }
  2117. }
  2118. if (strtolower($entry->nodeName) == "a") {
  2119. $entry->setAttribute("target", "_blank");
  2120. }
  2121. }
  2122. $entries = $xpath->query('//iframe');
  2123. foreach ($entries as $entry) {
  2124. $entry->setAttribute('sandbox', 'allow-scripts');
  2125. }
  2126. $allowed_elements = array('a', 'address', 'audio', 'article', 'aside',
  2127. 'b', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br',
  2128. 'caption', 'cite', 'center', 'code', 'col', 'colgroup',
  2129. 'data', 'dd', 'del', 'details', 'div', 'dl', 'font',
  2130. 'dt', 'em', 'footer', 'figure', 'figcaption',
  2131. 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'html', 'i',
  2132. 'img', 'ins', 'kbd', 'li', 'main', 'mark', 'nav', 'noscript',
  2133. 'ol', 'p', 'pre', 'q', 'ruby', 'rp', 'rt', 's', 'samp', 'section',
  2134. 'small', 'source', 'span', 'strike', 'strong', 'sub', 'summary',
  2135. 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time',
  2136. 'tr', 'track', 'tt', 'u', 'ul', 'var', 'wbr', 'video' );
  2137. if ($_SESSION['hasSandbox']) $allowed_elements[] = 'iframe';
  2138. $disallowed_attributes = array('id', 'style', 'class');
  2139. global $pluginhost;
  2140. if (isset($pluginhost)) {
  2141. foreach ($pluginhost->get_hooks($pluginhost::HOOK_SANITIZE) as $plugin) {
  2142. $retval = $plugin->hook_sanitize($doc, $site_url, $allowed_elements, $disallowed_attributes);
  2143. if (is_array($retval)) {
  2144. $doc = $retval[0];
  2145. $allowed_elements = $retval[1];
  2146. $disallowed_attributes = $retval[2];
  2147. } else {
  2148. $doc = $retval;
  2149. }
  2150. }
  2151. }
  2152. $doc->removeChild($doc->firstChild); //remove doctype
  2153. $doc = strip_harmful_tags($doc, $allowed_elements, $disallowed_attributes);
  2154. $res = $doc->saveHTML();
  2155. return $res;
  2156. }
  2157. function strip_harmful_tags($doc, $allowed_elements, $disallowed_attributes) {
  2158. $entries = $doc->getElementsByTagName("*");
  2159. foreach ($entries as $entry) {
  2160. if (!in_array($entry->nodeName, $allowed_elements)) {
  2161. $entry->parentNode->removeChild($entry);
  2162. }
  2163. if ($entry->hasAttributes()) {
  2164. $attrs_to_remove = array();
  2165. foreach ($entry->attributes as $attr) {
  2166. if (strpos($attr->nodeName, 'on') === 0) {
  2167. array_push($attrs_to_remove, $attr);
  2168. }
  2169. if (in_array($attr->nodeName, $disallowed_attributes)) {
  2170. array_push($attrs_to_remove, $attr);
  2171. }
  2172. }
  2173. foreach ($attrs_to_remove as $attr) {
  2174. $entry->removeAttributeNode($attr);
  2175. }
  2176. }
  2177. }
  2178. return $doc;
  2179. }
  2180. function check_for_update($link) {
  2181. if (CHECK_FOR_NEW_VERSION && $_SESSION['access_level'] >= 10) {
  2182. $version_url = "http://tt-rss.org/version.php?ver=" . VERSION .
  2183. "&iid=" . sha1(SELF_URL_PATH);
  2184. $version_data = @fetch_file_contents($version_url);
  2185. if ($version_data) {
  2186. $version_data = json_decode($version_data, true);
  2187. if ($version_data && $version_data['version']) {
  2188. if (version_compare(VERSION, $version_data['version']) == -1) {
  2189. return $version_data;
  2190. }
  2191. }
  2192. }
  2193. }
  2194. return false;
  2195. }
  2196. function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
  2197. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  2198. if (count($ids) == 0) return;
  2199. $tmp_ids = array();
  2200. foreach ($ids as $id) {
  2201. array_push($tmp_ids, "ref_id = '$id'");
  2202. }
  2203. $ids_qpart = join(" OR ", $tmp_ids);
  2204. if ($cmode == 0) {
  2205. db_query($link, "UPDATE ttrss_user_entries SET
  2206. unread = false,last_read = NOW()
  2207. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  2208. } else if ($cmode == 1) {
  2209. db_query($link, "UPDATE ttrss_user_entries SET
  2210. unread = true
  2211. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  2212. } else {
  2213. db_query($link, "UPDATE ttrss_user_entries SET
  2214. unread = NOT unread,last_read = NOW()
  2215. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  2216. }
  2217. /* update ccache */
  2218. $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
  2219. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  2220. while ($line = db_fetch_assoc($result)) {
  2221. ccache_update($link, $line["feed_id"], $owner_uid);
  2222. }
  2223. }
  2224. function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
  2225. $a_id = db_escape_string($link, $id);
  2226. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  2227. $query = "SELECT DISTINCT tag_name,
  2228. owner_uid as owner FROM
  2229. ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
  2230. ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
  2231. $obj_id = md5("TAGS:$owner_uid:$id");
  2232. $tags = array();
  2233. /* check cache first */
  2234. if ($tag_cache === false) {
  2235. $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
  2236. WHERE ref_id = '$id' AND owner_uid = $owner_uid");
  2237. $tag_cache = db_fetch_result($result, 0, "tag_cache");
  2238. }
  2239. if ($tag_cache) {
  2240. $tags = explode(",", $tag_cache);
  2241. } else {
  2242. /* do it the hard way */
  2243. $tmp_result = db_query($link, $query);
  2244. while ($tmp_line = db_fetch_assoc($tmp_result)) {
  2245. array_push($tags, $tmp_line["tag_name"]);
  2246. }
  2247. /* update the cache */
  2248. $tags_str = db_escape_string($link, join(",", $tags));
  2249. db_query($link, "UPDATE ttrss_user_entries
  2250. SET tag_cache = '$tags_str' WHERE ref_id = '$id'
  2251. AND owner_uid = $owner_uid");
  2252. }
  2253. return $tags;
  2254. }
  2255. function trim_array($array) {
  2256. $tmp = $array;
  2257. array_walk($tmp, 'trim');
  2258. return $tmp;
  2259. }
  2260. function tag_is_valid($tag) {
  2261. if ($tag == '') return false;
  2262. if (preg_match("/^[0-9]*$/", $tag)) return false;
  2263. if (mb_strlen($tag) > 250) return false;
  2264. if (function_exists('iconv')) {
  2265. $tag = iconv("utf-8", "utf-8", $tag);
  2266. }
  2267. if (!$tag) return false;
  2268. return true;
  2269. }
  2270. function render_login_form($link) {
  2271. require_once "login_form.php";
  2272. exit;
  2273. }
  2274. // from http://developer.apple.com/internet/safari/faq.html
  2275. function no_cache_incantation() {
  2276. header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
  2277. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
  2278. header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
  2279. header("Cache-Control: post-check=0, pre-check=0", false);
  2280. header("Pragma: no-cache"); // HTTP/1.0
  2281. }
  2282. function format_warning($msg, $id = "") {
  2283. global $link;
  2284. return "<div class=\"warning\" id=\"$id\">
  2285. <img src=\"images/sign_excl.svg\"><div class='inner'>$msg</div></div>";
  2286. }
  2287. function format_notice($msg, $id = "") {
  2288. global $link;
  2289. return "<div class=\"notice\" id=\"$id\">
  2290. <img src=\"images/sign_info.svg\"><div class='inner'>$msg</div></div>";
  2291. }
  2292. function format_error($msg, $id = "") {
  2293. global $link;
  2294. return "<div class=\"error\" id=\"$id\">
  2295. <img src=\"images/sign_excl.svg\"><div class='inner'>$msg</div></div>";
  2296. }
  2297. function print_notice($msg) {
  2298. return print format_notice($msg);
  2299. }
  2300. function print_warning($msg) {
  2301. return print format_warning($msg);
  2302. }
  2303. function print_error($msg) {
  2304. return print format_error($msg);
  2305. }
  2306. function T_sprintf() {
  2307. $args = func_get_args();
  2308. return vsprintf(__(array_shift($args)), $args);
  2309. }
  2310. function format_inline_player($link, $url, $ctype) {
  2311. $entry = "";
  2312. $url = htmlspecialchars($url);
  2313. if (strpos($ctype, "audio/") === 0) {
  2314. if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
  2315. strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
  2316. strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
  2317. $id = 'AUDIO-' . uniqid();
  2318. $entry .= "<audio id=\"$id\"\" controls style='display : none'>
  2319. <source type=\"$ctype\" src=\"$url\"></source>
  2320. </audio>";
  2321. $entry .= "<span onclick=\"player(this)\"
  2322. title=\"".__("Click to play")."\" status=\"0\"
  2323. class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
  2324. } else {
  2325. $entry .= "<object type=\"application/x-shockwave-flash\"
  2326. data=\"lib/button/musicplayer.swf?song_url=$url\"
  2327. width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
  2328. <param name=\"movie\"
  2329. value=\"lib/button/musicplayer.swf?song_url=$url\" />
  2330. </object>";
  2331. }
  2332. if ($entry) $entry .= "&nbsp; <a target=\"_blank\"
  2333. href=\"$url\">" . basename($url) . "</a>";
  2334. return $entry;
  2335. }
  2336. return "";
  2337. /* $filename = substr($url, strrpos($url, "/")+1);
  2338. $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
  2339. $filename . " (" . $ctype . ")" . "</a>"; */
  2340. }
  2341. function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
  2342. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  2343. $rv = array();
  2344. $rv['id'] = $id;
  2345. /* we can figure out feed_id from article id anyway, why do we
  2346. * pass feed_id here? let's ignore the argument :( */
  2347. $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
  2348. WHERE ref_id = '$id'");
  2349. $feed_id = (int) db_fetch_result($result, 0, "feed_id");
  2350. $rv['feed_id'] = $feed_id;
  2351. //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
  2352. if ($mark_as_read) {
  2353. $result = db_query($link, "UPDATE ttrss_user_entries
  2354. SET unread = false,last_read = NOW()
  2355. WHERE ref_id = '$id' AND owner_uid = $owner_uid");
  2356. ccache_update($link, $feed_id, $owner_uid);
  2357. }
  2358. $result = db_query($link, "SELECT id,title,link,content,feed_id,comments,int_id,
  2359. ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
  2360. (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
  2361. (SELECT hide_images FROM ttrss_feeds WHERE id = feed_id) as hide_images,
  2362. (SELECT always_display_enclosures FROM ttrss_feeds WHERE id = feed_id) as always_display_enclosures,
  2363. num_comments,
  2364. tag_cache,
  2365. author,
  2366. orig_feed_id,
  2367. note,
  2368. cached_content
  2369. FROM ttrss_entries,ttrss_user_entries
  2370. WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
  2371. if ($result) {
  2372. $line = db_fetch_assoc($result);
  2373. $tag_cache = $line["tag_cache"];
  2374. $line["tags"] = get_article_tags($link, $id, $owner_uid, $line["tag_cache"]);
  2375. unset($line["tag_cache"]);
  2376. $line["content"] = sanitize($link, $line["content"], false, $owner_uid, $line["site_url"]);
  2377. global $pluginhost;
  2378. foreach ($pluginhost->get_hooks($pluginhost::HOOK_RENDER_ARTICLE) as $p) {
  2379. $line = $p->hook_render_article($line);
  2380. }
  2381. $num_comments = $line["num_comments"];
  2382. $entry_comments = "";
  2383. if ($num_comments > 0) {
  2384. if ($line["comments"]) {
  2385. $comments_url = htmlspecialchars($line["comments"]);
  2386. } else {
  2387. $comments_url = htmlspecialchars($line["link"]);
  2388. }
  2389. $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
  2390. } else {
  2391. if ($line["comments"] && $line["link"] != $line["comments"]) {
  2392. $entry_comments = "<a target='_blank' href=\"".htmlspecialchars($line["comments"])."\">comments</a>";
  2393. }
  2394. }
  2395. if ($zoom_mode) {
  2396. header("Content-Type: text/html");
  2397. $rv['content'] .= "<html><head>
  2398. <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
  2399. <title>Tiny Tiny RSS - ".$line["title"]."</title>
  2400. <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
  2401. </head><body id=\"ttrssZoom\">";
  2402. }
  2403. $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
  2404. $rv['content'] .= "<div class=\"postHeader\" id=\"POSTHDR-$id\">";
  2405. $entry_author = $line["author"];
  2406. if ($entry_author) {
  2407. $entry_author = __(" - ") . $entry_author;
  2408. }
  2409. $parsed_updated = make_local_datetime($link, $line["updated"], true,
  2410. $owner_uid, true);
  2411. $rv['content'] .= "<div class=\"postDate\">$parsed_updated</div>";
  2412. if ($line["link"]) {
  2413. $rv['content'] .= "<div class='postTitle'><a target='_blank'
  2414. title=\"".htmlspecialchars($line['title'])."\"
  2415. href=\"" .
  2416. htmlspecialchars($line["link"]) . "\">" .
  2417. $line["title"] . "</a>" .
  2418. "<span class='author'>$entry_author</span></div>";
  2419. } else {
  2420. $rv['content'] .= "<div class='postTitle'>" . $line["title"] . "$entry_author</div>";
  2421. }
  2422. $tags_str = format_tags_string($line["tags"], $id);
  2423. $tags_str_full = join(", ", $line["tags"]);
  2424. if (!$tags_str_full) $tags_str_full = __("no tags");
  2425. if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
  2426. $rv['content'] .= "<div class='postTags' style='float : right'>
  2427. <img src='images/tag.png'
  2428. class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
  2429. if (!$zoom_mode) {
  2430. $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
  2431. <a title=\"".__('Edit tags for this article')."\"
  2432. href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
  2433. $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
  2434. id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
  2435. position=\"below\">$tags_str_full</div>";
  2436. global $pluginhost;
  2437. foreach ($pluginhost->get_hooks($pluginhost::HOOK_ARTICLE_BUTTON) as $p) {
  2438. $rv['content'] .= $p->hook_article_button($line);
  2439. }
  2440. } else {
  2441. $tags_str = strip_tags($tags_str);
  2442. $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
  2443. }
  2444. $rv['content'] .= "</div>";
  2445. $rv['content'] .= "<div clear='both'>";
  2446. global $pluginhost;
  2447. foreach ($pluginhost->get_hooks($pluginhost::HOOK_ARTICLE_LEFT_BUTTON) as $p) {
  2448. $rv['content'] .= $p->hook_article_left_button($line);
  2449. }
  2450. $rv['content'] .= "$entry_comments</div>";
  2451. if ($line["orig_feed_id"]) {
  2452. $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
  2453. WHERE id = ".$line["orig_feed_id"]);
  2454. if (db_num_rows($tmp_result) != 0) {
  2455. $rv['content'] .= "<div clear='both'>";
  2456. $rv['content'] .= __("Originally from:");
  2457. $rv['content'] .= "&nbsp;";
  2458. $tmp_line = db_fetch_assoc($tmp_result);
  2459. $rv['content'] .= "<a target='_blank'
  2460. href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
  2461. $tmp_line['title'] . "</a>";
  2462. $rv['content'] .= "&nbsp;";
  2463. $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
  2464. $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.svg'></a>";
  2465. $rv['content'] .= "</div>";
  2466. }
  2467. }
  2468. $rv['content'] .= "</div>";
  2469. $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
  2470. if ($line['note']) {
  2471. $rv['content'] .= format_article_note($id, $line['note'], !$zoom_mode);
  2472. }
  2473. $rv['content'] .= "</div>";
  2474. $rv['content'] .= "<div class=\"postContent\">";
  2475. $rv['content'] .= $line["content"];
  2476. $rv['content'] .= format_article_enclosures($link, $id,
  2477. sql_bool_to_bool($line["always_display_enclosures"]),
  2478. $line["content"],
  2479. sql_bool_to_bool($line["hide_images"]));
  2480. $rv['content'] .= "</div>";
  2481. $rv['content'] .= "</div>";
  2482. }
  2483. if ($zoom_mode) {
  2484. $rv['content'] .= "
  2485. <div class='footer'>
  2486. <button onclick=\"return window.close()\">".
  2487. __("Close this window")."</button></div>";
  2488. $rv['content'] .= "</body></html>";
  2489. }
  2490. return $rv;
  2491. }
  2492. function print_checkpoint($n, $s) {
  2493. $ts = microtime(true);
  2494. echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
  2495. return $ts;
  2496. }
  2497. function sanitize_tag($tag) {
  2498. $tag = trim($tag);
  2499. $tag = mb_strtolower($tag, 'utf-8');
  2500. $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
  2501. // $tag = str_replace('"', "", $tag);
  2502. // $tag = str_replace("+", " ", $tag);
  2503. $tag = str_replace("technorati tag: ", "", $tag);
  2504. return $tag;
  2505. }
  2506. function get_self_url_prefix() {
  2507. if (strrpos(SELF_URL_PATH, "/") === strlen(SELF_URL_PATH)-1) {
  2508. return substr(SELF_URL_PATH, 0, strlen(SELF_URL_PATH)-1);
  2509. } else {
  2510. return SELF_URL_PATH;
  2511. }
  2512. }
  2513. /**
  2514. * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
  2515. *
  2516. * @return string The Mozilla Firefox feed adding URL.
  2517. */
  2518. function add_feed_url() {
  2519. //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
  2520. $url_path = get_self_url_prefix() .
  2521. "/public.php?op=subscribe&feed_url=%s";
  2522. return $url_path;
  2523. } // function add_feed_url
  2524. function encrypt_password($pass, $salt = '', $mode2 = false) {
  2525. if ($salt && $mode2) {
  2526. return "MODE2:" . hash('sha256', $salt . $pass);
  2527. } else if ($salt) {
  2528. return "SHA1X:" . sha1("$salt:$pass");
  2529. } else {
  2530. return "SHA1:" . sha1($pass);
  2531. }
  2532. } // function encrypt_password
  2533. function load_filters($link, $feed_id, $owner_uid, $action_id = false) {
  2534. $filters = array();
  2535. $cat_id = (int)getFeedCategory($link, $feed_id);
  2536. $result = db_query($link, "SELECT * FROM ttrss_filters2 WHERE
  2537. owner_uid = $owner_uid AND enabled = true ORDER BY order_id, title");
  2538. $check_cats = join(",", array_merge(
  2539. getParentCategories($link, $cat_id, $owner_uid),
  2540. array($cat_id)));
  2541. while ($line = db_fetch_assoc($result)) {
  2542. $filter_id = $line["id"];
  2543. $result2 = db_query($link, "SELECT
  2544. r.reg_exp, r.inverse, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
  2545. FROM ttrss_filters2_rules AS r,
  2546. ttrss_filter_types AS t
  2547. WHERE
  2548. (cat_id IS NULL OR cat_id IN ($check_cats)) AND
  2549. (feed_id IS NULL OR feed_id = '$feed_id') AND
  2550. filter_type = t.id AND filter_id = '$filter_id'");
  2551. $rules = array();
  2552. $actions = array();
  2553. while ($rule_line = db_fetch_assoc($result2)) {
  2554. # print_r($rule_line);
  2555. $rule = array();
  2556. $rule["reg_exp"] = $rule_line["reg_exp"];
  2557. $rule["type"] = $rule_line["type_name"];
  2558. $rule["inverse"] = sql_bool_to_bool($rule_line["inverse"]);
  2559. array_push($rules, $rule);
  2560. }
  2561. $result2 = db_query($link, "SELECT a.action_param,t.name AS type_name
  2562. FROM ttrss_filters2_actions AS a,
  2563. ttrss_filter_actions AS t
  2564. WHERE
  2565. action_id = t.id AND filter_id = '$filter_id'");
  2566. while ($action_line = db_fetch_assoc($result2)) {
  2567. # print_r($action_line);
  2568. $action = array();
  2569. $action["type"] = $action_line["type_name"];
  2570. $action["param"] = $action_line["action_param"];
  2571. array_push($actions, $action);
  2572. }
  2573. $filter = array();
  2574. $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
  2575. $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
  2576. $filter["rules"] = $rules;
  2577. $filter["actions"] = $actions;
  2578. if (count($rules) > 0 && count($actions) > 0) {
  2579. array_push($filters, $filter);
  2580. }
  2581. }
  2582. return $filters;
  2583. }
  2584. function get_score_pic($score) {
  2585. if ($score > 100) {
  2586. return "score_high.png";
  2587. } else if ($score > 0) {
  2588. return "score_half_high.png";
  2589. } else if ($score < -100) {
  2590. return "score_low.png";
  2591. } else if ($score < 0) {
  2592. return "score_half_low.png";
  2593. } else {
  2594. return "score_neutral.png";
  2595. }
  2596. }
  2597. function feed_has_icon($id) {
  2598. return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
  2599. }
  2600. function init_connection($link) {
  2601. if ($link) {
  2602. if (DB_TYPE == "pgsql") {
  2603. pg_query($link, "set client_encoding = 'UTF-8'");
  2604. pg_set_client_encoding("UNICODE");
  2605. pg_query($link, "set datestyle = 'ISO, european'");
  2606. pg_query($link, "set TIME ZONE 0");
  2607. } else {
  2608. db_query($link, "SET time_zone = '+0:0'");
  2609. if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) {
  2610. db_query($link, "SET NAMES " . MYSQL_CHARSET);
  2611. }
  2612. }
  2613. global $pluginhost;
  2614. $pluginhost = new PluginHost($link);
  2615. $pluginhost->load(PLUGINS, $pluginhost::KIND_ALL);
  2616. return true;
  2617. } else {
  2618. print "Unable to connect to database:" . db_last_error();
  2619. return false;
  2620. }
  2621. }
  2622. function format_tags_string($tags, $id) {
  2623. $tags_str = "";
  2624. $tags_nolinks_str = "";
  2625. $num_tags = 0;
  2626. $tag_limit = 6;
  2627. $formatted_tags = array();
  2628. foreach ($tags as $tag) {
  2629. $num_tags++;
  2630. $tag_escaped = str_replace("'", "\\'", $tag);
  2631. if (mb_strlen($tag) > 30) {
  2632. $tag = truncate_string($tag, 30);
  2633. }
  2634. $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
  2635. array_push($formatted_tags, $tag_str);
  2636. $tmp_tags_str = implode(", ", $formatted_tags);
  2637. if ($num_tags == $tag_limit || mb_strlen($tmp_tags_str) > 150) {
  2638. break;
  2639. }
  2640. }
  2641. $tags_str = implode(", ", $formatted_tags);
  2642. if ($num_tags < count($tags)) {
  2643. $tags_str .= ", &hellip;";
  2644. }
  2645. if ($num_tags == 0) {
  2646. $tags_str = __("no tags");
  2647. }
  2648. return $tags_str;
  2649. }
  2650. function format_article_labels($labels, $id) {
  2651. $labels_str = "";
  2652. foreach ($labels as $l) {
  2653. $labels_str .= sprintf("<span class='hlLabelRef'
  2654. style='color : %s; background-color : %s'>%s</span>",
  2655. $l[2], $l[3], $l[1]);
  2656. }
  2657. return $labels_str;
  2658. }
  2659. function format_article_note($id, $note, $allow_edit = true) {
  2660. $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
  2661. <div class='noteEdit' onclick=\"editArticleNote($id)\">".
  2662. ($allow_edit ? __('(edit note)') : "")."</div>$note</div>";
  2663. return $str;
  2664. }
  2665. function get_feed_category($link, $feed_cat, $parent_cat_id = false) {
  2666. if ($parent_cat_id) {
  2667. $parent_qpart = "parent_cat = '$parent_cat_id'";
  2668. $parent_insert = "'$parent_cat_id'";
  2669. } else {
  2670. $parent_qpart = "parent_cat IS NULL";
  2671. $parent_insert = "NULL";
  2672. }
  2673. $result = db_query($link,
  2674. "SELECT id FROM ttrss_feed_categories
  2675. WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
  2676. if (db_num_rows($result) == 0) {
  2677. return false;
  2678. } else {
  2679. return db_fetch_result($result, 0, "id");
  2680. }
  2681. }
  2682. function add_feed_category($link, $feed_cat, $parent_cat_id = false) {
  2683. if (!$feed_cat) return false;
  2684. db_query($link, "BEGIN");
  2685. if ($parent_cat_id) {
  2686. $parent_qpart = "parent_cat = '$parent_cat_id'";
  2687. $parent_insert = "'$parent_cat_id'";
  2688. } else {
  2689. $parent_qpart = "parent_cat IS NULL";
  2690. $parent_insert = "NULL";
  2691. }
  2692. $feed_cat = mb_substr($feed_cat, 0, 250);
  2693. $result = db_query($link,
  2694. "SELECT id FROM ttrss_feed_categories
  2695. WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
  2696. if (db_num_rows($result) == 0) {
  2697. $result = db_query($link,
  2698. "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
  2699. VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
  2700. db_query($link, "COMMIT");
  2701. return true;
  2702. }
  2703. return false;
  2704. }
  2705. function getArticleFeed($link, $id) {
  2706. $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
  2707. WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
  2708. if (db_num_rows($result) != 0) {
  2709. return db_fetch_result($result, 0, "feed_id");
  2710. } else {
  2711. return 0;
  2712. }
  2713. }
  2714. /**
  2715. * Fixes incomplete URLs by prepending "http://".
  2716. * Also replaces feed:// with http://, and
  2717. * prepends a trailing slash if the url is a domain name only.
  2718. *
  2719. * @param string $url Possibly incomplete URL
  2720. *
  2721. * @return string Fixed URL.
  2722. */
  2723. function fix_url($url) {
  2724. if (strpos($url, '://') === false) {
  2725. $url = 'http://' . $url;
  2726. } else if (substr($url, 0, 5) == 'feed:') {
  2727. $url = 'http:' . substr($url, 5);
  2728. }
  2729. //prepend slash if the URL has no slash in it
  2730. // "http://www.example" -> "http://www.example/"
  2731. if (strpos($url, '/', strpos($url, ':') + 3) === false) {
  2732. $url .= '/';
  2733. }
  2734. if ($url != "http:///")
  2735. return $url;
  2736. else
  2737. return '';
  2738. }
  2739. function validate_feed_url($url) {
  2740. $parts = parse_url($url);
  2741. return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
  2742. }
  2743. function get_article_enclosures($link, $id) {
  2744. $query = "SELECT * FROM ttrss_enclosures
  2745. WHERE post_id = '$id' AND content_url != ''";
  2746. $rv = array();
  2747. $result = db_query($link, $query);
  2748. if (db_num_rows($result) > 0) {
  2749. while ($line = db_fetch_assoc($result)) {
  2750. array_push($rv, $line);
  2751. }
  2752. }
  2753. return $rv;
  2754. }
  2755. function save_email_address($link, $email) {
  2756. // FIXME: implement persistent storage of emails
  2757. if (!$_SESSION['stored_emails'])
  2758. $_SESSION['stored_emails'] = array();
  2759. if (!in_array($email, $_SESSION['stored_emails']))
  2760. array_push($_SESSION['stored_emails'], $email);
  2761. }
  2762. function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
  2763. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  2764. $sql_is_cat = bool_to_sql_bool($is_cat);
  2765. $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
  2766. WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
  2767. AND owner_uid = " . $owner_uid);
  2768. if (db_num_rows($result) == 1) {
  2769. return db_fetch_result($result, 0, "access_key");
  2770. } else {
  2771. $key = db_escape_string($link, sha1(uniqid(rand(), true)));
  2772. $result = db_query($link, "INSERT INTO ttrss_access_keys
  2773. (access_key, feed_id, is_cat, owner_uid)
  2774. VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
  2775. return $key;
  2776. }
  2777. return false;
  2778. }
  2779. function get_feeds_from_html($url, $content)
  2780. {
  2781. $url = fix_url($url);
  2782. $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
  2783. libxml_use_internal_errors(true);
  2784. $doc = new DOMDocument();
  2785. $doc->loadHTML($content);
  2786. $xpath = new DOMXPath($doc);
  2787. $entries = $xpath->query('/html/head/link[@rel="alternate"]');
  2788. $feedUrls = array();
  2789. foreach ($entries as $entry) {
  2790. if ($entry->hasAttribute('href')) {
  2791. $title = $entry->getAttribute('title');
  2792. if ($title == '') {
  2793. $title = $entry->getAttribute('type');
  2794. }
  2795. $feedUrl = rewrite_relative_url(
  2796. $baseUrl, $entry->getAttribute('href')
  2797. );
  2798. $feedUrls[$feedUrl] = $title;
  2799. }
  2800. }
  2801. return $feedUrls;
  2802. }
  2803. function is_html($content) {
  2804. return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 20)) !== 0;
  2805. }
  2806. function url_is_html($url, $login = false, $pass = false) {
  2807. return is_html(fetch_file_contents($url, false, $login, $pass));
  2808. }
  2809. function print_label_select($link, $name, $value, $attributes = "") {
  2810. $result = db_query($link, "SELECT caption FROM ttrss_labels2
  2811. WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
  2812. print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
  2813. "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
  2814. while ($line = db_fetch_assoc($result)) {
  2815. $issel = ($line["caption"] == $value) ? "selected=\"1\"" : "";
  2816. print "<option value=\"".htmlspecialchars($line["caption"])."\"
  2817. $issel>" . htmlspecialchars($line["caption"]) . "</option>";
  2818. }
  2819. # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
  2820. print "</select>";
  2821. }
  2822. function format_article_enclosures($link, $id, $always_display_enclosures,
  2823. $article_content, $hide_images = false) {
  2824. $result = get_article_enclosures($link, $id);
  2825. $rv = '';
  2826. if (count($result) > 0) {
  2827. $entries_html = array();
  2828. $entries = array();
  2829. $entries_inline = array();
  2830. foreach ($result as $line) {
  2831. $url = $line["content_url"];
  2832. $ctype = $line["content_type"];
  2833. if (!$ctype) $ctype = __("unknown type");
  2834. $filename = substr($url, strrpos($url, "/")+1);
  2835. $player = format_inline_player($link, $url, $ctype);
  2836. if ($player) array_push($entries_inline, $player);
  2837. # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
  2838. # $filename . " (" . $ctype . ")" . "</a>";
  2839. $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
  2840. dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
  2841. array_push($entries_html, $entry);
  2842. $entry = array();
  2843. $entry["type"] = $ctype;
  2844. $entry["filename"] = $filename;
  2845. $entry["url"] = $url;
  2846. array_push($entries, $entry);
  2847. }
  2848. if ($_SESSION['uid'] && !get_pref($link, "STRIP_IMAGES") && !$_SESSION["bw_limit"]) {
  2849. if ($always_display_enclosures ||
  2850. !preg_match("/<img/i", $article_content)) {
  2851. foreach ($entries as $entry) {
  2852. if (preg_match("/image/", $entry["type"]) ||
  2853. preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
  2854. if (!$hide_images) {
  2855. $rv .= "<p><img
  2856. alt=\"".htmlspecialchars($entry["filename"])."\"
  2857. src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
  2858. } else {
  2859. $rv .= "<p><a target=\"_blank\"
  2860. href=\"".htmlspecialchars($entry["url"])."\"
  2861. >" .htmlspecialchars($entry["url"]) . "</a></p>";
  2862. }
  2863. }
  2864. }
  2865. }
  2866. }
  2867. if (count($entries_inline) > 0) {
  2868. $rv .= "<hr clear='both'/>";
  2869. foreach ($entries_inline as $entry) { $rv .= $entry; };
  2870. $rv .= "<hr clear='both'/>";
  2871. }
  2872. $rv .= "<select class=\"attachments\" onchange=\"openSelectedAttachment(this)\">".
  2873. "<option value=''>" . __('Attachments')."</option>";
  2874. foreach ($entries as $entry) {
  2875. $rv .= "<option value=\"".htmlspecialchars($entry["url"])."\">" . htmlspecialchars($entry["filename"]) . "</option>";
  2876. };
  2877. $rv .= "</select>";
  2878. }
  2879. return $rv;
  2880. }
  2881. function getLastArticleId($link) {
  2882. $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
  2883. WHERE owner_uid = " . $_SESSION["uid"]);
  2884. if (db_num_rows($result) == 1) {
  2885. return db_fetch_result($result, 0, "id");
  2886. } else {
  2887. return -1;
  2888. }
  2889. }
  2890. function build_url($parts) {
  2891. return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
  2892. }
  2893. /**
  2894. * Converts a (possibly) relative URL to a absolute one.
  2895. *
  2896. * @param string $url Base URL (i.e. from where the document is)
  2897. * @param string $rel_url Possibly relative URL in the document
  2898. *
  2899. * @return string Absolute URL
  2900. */
  2901. function rewrite_relative_url($url, $rel_url) {
  2902. if (strpos($rel_url, "magnet:") === 0) {
  2903. return $rel_url;
  2904. } else if (strpos($rel_url, "://") !== false) {
  2905. return $rel_url;
  2906. } else if (strpos($rel_url, "//") === 0) {
  2907. # protocol-relative URL (rare but they exist)
  2908. return $rel_url;
  2909. } else if (strpos($rel_url, "/") === 0)
  2910. {
  2911. $parts = parse_url($url);
  2912. $parts['path'] = $rel_url;
  2913. return build_url($parts);
  2914. } else {
  2915. $parts = parse_url($url);
  2916. if (!isset($parts['path'])) {
  2917. $parts['path'] = '/';
  2918. }
  2919. $dir = $parts['path'];
  2920. if (substr($dir, -1) !== '/') {
  2921. $dir = dirname($parts['path']);
  2922. $dir !== '/' && $dir .= '/';
  2923. }
  2924. $parts['path'] = $dir . $rel_url;
  2925. return build_url($parts);
  2926. }
  2927. }
  2928. function sphinx_search($query, $offset = 0, $limit = 30) {
  2929. require_once 'lib/sphinxapi.php';
  2930. $sphinxClient = new SphinxClient();
  2931. $sphinxClient->SetServer('localhost', 9312);
  2932. $sphinxClient->SetConnectTimeout(1);
  2933. $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
  2934. 'feed_title' => 20));
  2935. $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2);
  2936. $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
  2937. $sphinxClient->SetLimits($offset, $limit, 1000);
  2938. $sphinxClient->SetArrayResult(false);
  2939. $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
  2940. $result = $sphinxClient->Query($query, SPHINX_INDEX);
  2941. $ids = array();
  2942. if (is_array($result['matches'])) {
  2943. foreach (array_keys($result['matches']) as $int_id) {
  2944. $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
  2945. array_push($ids, $ref_id);
  2946. }
  2947. }
  2948. return $ids;
  2949. }
  2950. function cleanup_tags($link, $days = 14, $limit = 1000) {
  2951. if (DB_TYPE == "pgsql") {
  2952. $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
  2953. } else if (DB_TYPE == "mysql") {
  2954. $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
  2955. }
  2956. $tags_deleted = 0;
  2957. while ($limit > 0) {
  2958. $limit_part = 500;
  2959. $query = "SELECT ttrss_tags.id AS id
  2960. FROM ttrss_tags, ttrss_user_entries, ttrss_entries
  2961. WHERE post_int_id = int_id AND $interval_query AND
  2962. ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
  2963. $result = db_query($link, $query);
  2964. $ids = array();
  2965. while ($line = db_fetch_assoc($result)) {
  2966. array_push($ids, $line['id']);
  2967. }
  2968. if (count($ids) > 0) {
  2969. $ids = join(",", $ids);
  2970. $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
  2971. $tags_deleted += db_affected_rows($link, $tmp_result);
  2972. } else {
  2973. break;
  2974. }
  2975. $limit -= $limit_part;
  2976. }
  2977. return $tags_deleted;
  2978. }
  2979. function print_user_stylesheet($link) {
  2980. $value = get_pref($link, 'USER_STYLESHEET');
  2981. if ($value) {
  2982. print "<style type=\"text/css\">";
  2983. print str_replace("<br/>", "\n", $value);
  2984. print "</style>";
  2985. }
  2986. }
  2987. function rewrite_urls($html) {
  2988. libxml_use_internal_errors(true);
  2989. $charset_hack = '<head>
  2990. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  2991. </head>';
  2992. $doc = new DOMDocument();
  2993. $doc->loadHTML($charset_hack . $html);
  2994. $xpath = new DOMXPath($doc);
  2995. $entries = $xpath->query('//*/text()');
  2996. foreach ($entries as $entry) {
  2997. if (strstr($entry->wholeText, "://") !== false) {
  2998. $text = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
  2999. "<a target=\"_blank\" href=\"\\1\">\\1</a>", $entry->wholeText);
  3000. if ($text != $entry->wholeText) {
  3001. $cdoc = new DOMDocument();
  3002. $cdoc->loadHTML($charset_hack . $text);
  3003. foreach ($cdoc->childNodes as $cnode) {
  3004. $cnode = $doc->importNode($cnode, true);
  3005. if ($cnode) {
  3006. $entry->parentNode->insertBefore($cnode);
  3007. }
  3008. }
  3009. $entry->parentNode->removeChild($entry);
  3010. }
  3011. }
  3012. }
  3013. $node = $doc->getElementsByTagName('body')->item(0);
  3014. // http://tt-rss.org/forum/viewtopic.php?f=1&t=970
  3015. if ($node)
  3016. return $doc->saveXML($node);
  3017. else
  3018. return $html;
  3019. }
  3020. function filter_to_sql($link, $filter, $owner_uid) {
  3021. $query = array();
  3022. if (DB_TYPE == "pgsql")
  3023. $reg_qpart = "~";
  3024. else
  3025. $reg_qpart = "REGEXP";
  3026. foreach ($filter["rules"] AS $rule) {
  3027. $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
  3028. $rule['reg_exp']) !== FALSE;
  3029. if ($regexp_valid) {
  3030. $rule['reg_exp'] = db_escape_string($link, $rule['reg_exp']);
  3031. switch ($rule["type"]) {
  3032. case "title":
  3033. $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
  3034. $rule['reg_exp'] . "')";
  3035. break;
  3036. case "content":
  3037. $qpart = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
  3038. $rule['reg_exp'] . "')";
  3039. break;
  3040. case "both":
  3041. $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
  3042. $rule['reg_exp'] . "') OR LOWER(" .
  3043. "ttrss_entries.content) $reg_qpart LOWER('" . $rule['reg_exp'] . "')";
  3044. break;
  3045. case "tag":
  3046. $qpart = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
  3047. $rule['reg_exp'] . "')";
  3048. break;
  3049. case "link":
  3050. $qpart = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
  3051. $rule['reg_exp'] . "')";
  3052. break;
  3053. case "author":
  3054. $qpart = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
  3055. $rule['reg_exp'] . "')";
  3056. break;
  3057. }
  3058. if (isset($rule['inverse'])) $qpart = "NOT ($qpart)";
  3059. if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
  3060. $qpart .= " AND feed_id = " . db_escape_string($link, $rule["feed_id"]);
  3061. }
  3062. if (isset($rule["cat_id"])) {
  3063. if ($rule["cat_id"] > 0) {
  3064. $children = getChildCategories($link, $rule["cat_id"], $owner_uid);
  3065. array_push($children, $rule["cat_id"]);
  3066. $children = join(",", $children);
  3067. $cat_qpart = "cat_id IN ($children)";
  3068. } else {
  3069. $cat_qpart = "cat_id IS NULL";
  3070. }
  3071. $qpart .= " AND $cat_qpart";
  3072. }
  3073. array_push($query, "($qpart)");
  3074. }
  3075. }
  3076. if (count($query) > 0) {
  3077. $fullquery = "(" . join($filter["match_any_rule"] ? "OR" : "AND", $query) . ")";
  3078. } else {
  3079. $fullquery = "(false)";
  3080. }
  3081. if ($filter['inverse']) $fullquery = "(NOT $fullquery)";
  3082. return $fullquery;
  3083. }
  3084. if (!function_exists('gzdecode')) {
  3085. function gzdecode($string) { // no support for 2nd argument
  3086. return file_get_contents('compress.zlib://data:who/cares;base64,'.
  3087. base64_encode($string));
  3088. }
  3089. }
  3090. function get_random_bytes($length) {
  3091. if (function_exists('openssl_random_pseudo_bytes')) {
  3092. return openssl_random_pseudo_bytes($length);
  3093. } else {
  3094. $output = "";
  3095. for ($i = 0; $i < $length; $i++)
  3096. $output .= chr(mt_rand(0, 255));
  3097. return $output;
  3098. }
  3099. }
  3100. function read_stdin() {
  3101. $fp = fopen("php://stdin", "r");
  3102. if ($fp) {
  3103. $line = trim(fgets($fp));
  3104. fclose($fp);
  3105. return $line;
  3106. }
  3107. return null;
  3108. }
  3109. function tmpdirname($path, $prefix) {
  3110. // Use PHP's tmpfile function to create a temporary
  3111. // directory name. Delete the file and keep the name.
  3112. $tempname = tempnam($path,$prefix);
  3113. if (!$tempname)
  3114. return false;
  3115. if (!unlink($tempname))
  3116. return false;
  3117. return $tempname;
  3118. }
  3119. function getFeedCategory($link, $feed) {
  3120. $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
  3121. WHERE id = '$feed'");
  3122. if (db_num_rows($result) > 0) {
  3123. return db_fetch_result($result, 0, "cat_id");
  3124. } else {
  3125. return false;
  3126. }
  3127. }
  3128. function implements_interface($class, $interface) {
  3129. return in_array($interface, class_implements($class));
  3130. }
  3131. function geturl($url){
  3132. (function_exists('curl_init')) ? '' : die('cURL Must be installed for geturl function to work. Ask your host to enable it or uncomment extension=php_curl.dll in php.ini');
  3133. $curl = curl_init();
  3134. $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
  3135. $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
  3136. $header[] = "Cache-Control: max-age=0";
  3137. $header[] = "Connection: keep-alive";
  3138. $header[] = "Keep-Alive: 300";
  3139. $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
  3140. $header[] = "Accept-Language: en-us,en;q=0.5";
  3141. $header[] = "Pragma: ";
  3142. curl_setopt($curl, CURLOPT_URL, $url);
  3143. curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0 Firefox/5.0');
  3144. curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  3145. curl_setopt($curl, CURLOPT_HEADER, true);
  3146. curl_setopt($curl, CURLOPT_REFERER, $url);
  3147. curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
  3148. curl_setopt($curl, CURLOPT_AUTOREFERER, true);
  3149. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  3150. //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); //CURLOPT_FOLLOWLOCATION Disabled...
  3151. curl_setopt($curl, CURLOPT_TIMEOUT, 60);
  3152. $html = curl_exec($curl);
  3153. $status = curl_getinfo($curl);
  3154. curl_close($curl);
  3155. if($status['http_code']!=200){
  3156. if($status['http_code'] == 301 || $status['http_code'] == 302) {
  3157. list($header) = explode("\r\n\r\n", $html, 2);
  3158. $matches = array();
  3159. preg_match("/(Location:|URI:)[^(\n)]*/", $header, $matches);
  3160. $url = trim(str_replace($matches[1],"",$matches[0]));
  3161. $url_parsed = parse_url($url);
  3162. return (isset($url_parsed))? geturl($url, $referer):'';
  3163. }
  3164. $oline='';
  3165. foreach($status as $key=>$eline){$oline.='['.$key.']'.$eline.' ';}
  3166. $line =$oline." \r\n ".$url."\r\n-----------------\r\n";
  3167. # $handle = @fopen('./curl.error.log', 'a');
  3168. # fwrite($handle, $line);
  3169. return FALSE;
  3170. }
  3171. return $url;
  3172. }
  3173. function get_minified_js($files) {
  3174. require_once 'lib/jshrink/Minifier.php';
  3175. $rv = '';
  3176. foreach ($files as $js) {
  3177. if (!isset($_GET['debug'])) {
  3178. $cached_file = CACHE_DIR . "/js/$js.js";
  3179. if (file_exists($cached_file) &&
  3180. is_readable($cached_file) &&
  3181. filemtime($cached_file) >= filemtime("js/$js.js")) {
  3182. $rv .= file_get_contents($cached_file);
  3183. } else {
  3184. $minified = JShrink\Minifier::minify(file_get_contents("js/$js.js"));
  3185. file_put_contents($cached_file, $minified);
  3186. $rv .= $minified;
  3187. }
  3188. } else {
  3189. $rv .= file_get_contents("js/$js.js");
  3190. }
  3191. }
  3192. return $rv;
  3193. }
  3194. function stylesheet_tag($filename) {
  3195. $timestamp = filemtime($filename);
  3196. echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"$filename?$timestamp\"/>\n";
  3197. }
  3198. function javascript_tag($filename) {
  3199. $query = "";
  3200. if (!(strpos($filename, "?") === FALSE)) {
  3201. $query = substr($filename, strpos($filename, "?")+1);
  3202. $filename = substr($filename, 0, strpos($filename, "?"));
  3203. }
  3204. $timestamp = filemtime($filename);
  3205. if ($query) $timestamp .= "&$query";
  3206. echo "<script type=\"text/javascript\" charset=\"utf-8\" src=\"$filename?$timestamp\"></script>\n";
  3207. }
  3208. function calculate_dep_timestamp() {
  3209. $files = array_merge(glob("js/*.js"), glob("*.css"));
  3210. $max_ts = -1;
  3211. foreach ($files as $file) {
  3212. if (filemtime($file) > $max_ts) $max_ts = filemtime($file);
  3213. }
  3214. return $max_ts;
  3215. }
  3216. function T_js_decl($s1, $s2) {
  3217. if ($s1 && $s2) {
  3218. $s1 = preg_replace("/\n/", "", $s1);
  3219. $s2 = preg_replace("/\n/", "", $s2);
  3220. $s1 = preg_replace("/\"/", "\\\"", $s1);
  3221. $s2 = preg_replace("/\"/", "\\\"", $s2);
  3222. return "T_messages[\"$s1\"] = \"$s2\";\n";
  3223. }
  3224. }
  3225. function init_js_translations() {
  3226. print 'var T_messages = new Object();
  3227. function __(msg) {
  3228. if (T_messages[msg]) {
  3229. return T_messages[msg];
  3230. } else {
  3231. return msg;
  3232. }
  3233. }
  3234. function ngettext(msg1, msg2, n) {
  3235. return (parseInt(n) > 1) ? msg2 : msg1;
  3236. }';
  3237. $l10n = _get_reader();
  3238. for ($i = 0; $i < $l10n->total; $i++) {
  3239. $orig = $l10n->get_original_string($i);
  3240. $translation = __($orig);
  3241. print T_js_decl($orig, $translation);
  3242. }
  3243. }
  3244. function label_to_feed_id($label) {
  3245. return LABEL_BASE_INDEX - 1 - abs($label);
  3246. }
  3247. function feed_to_label_id($feed) {
  3248. return LABEL_BASE_INDEX - 1 + abs($feed);
  3249. }
  3250. ?>