functions.php 112 KB

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