functions.php 112 KB

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