functions.php 117 KB

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