functions.php 113 KB

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