functions.php 118 KB

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