functions.php 115 KB

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