functions.php 114 KB

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