functions.php 115 KB

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