functions.php 113 KB

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