functions.php 144 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487
  1. <?php
  2. define('EXPECTED_CONFIG_VERSION', 25);
  3. define('SCHEMA_VERSION', 94);
  4. function __autoload($class) {
  5. $file = "classes/".strtolower(basename($class)).".php";
  6. if (file_exists($file)) {
  7. require $file;
  8. }
  9. }
  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. if (DB_TYPE == "pgsql") {
  19. define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
  20. } else {
  21. define('SUBSTRING_FOR_DATE', 'SUBSTRING');
  22. }
  23. define('THEME_VERSION_REQUIRED', 1.1);
  24. /**
  25. * Return available translations names.
  26. *
  27. * @access public
  28. * @return array A array of available translations.
  29. */
  30. function get_translations() {
  31. $tr = array(
  32. "auto" => "Detect automatically",
  33. "ca_CA" => "Català",
  34. "en_US" => "English",
  35. "es_ES" => "Español",
  36. "de_DE" => "Deutsch",
  37. "fr_FR" => "Français",
  38. "hu_HU" => "Magyar (Hungarian)",
  39. "it_IT" => "Italiano",
  40. "ja_JP" => "日本語 (Japanese)",
  41. "nb_NO" => "Norwegian bokmål",
  42. "ru_RU" => "Русский",
  43. "pt_BR" => "Portuguese/Brazil",
  44. "zh_CN" => "Simplified Chinese");
  45. return $tr;
  46. }
  47. require_once "lib/accept-to-gettext.php";
  48. require_once "lib/gettext/gettext.inc";
  49. function startup_gettext() {
  50. # Get locale from Accept-Language header
  51. $lang = al2gt(array_keys(get_translations()), "text/html");
  52. if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
  53. $lang = _TRANSLATION_OVERRIDE_DEFAULT;
  54. }
  55. if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
  56. $lang = $_COOKIE["ttrss_lang"];
  57. }
  58. /* In login action of mobile version */
  59. if ($_POST["language"] && defined('MOBILE_VERSION')) {
  60. $lang = $_POST["language"];
  61. $_COOKIE["ttrss_lang"] = $lang;
  62. }
  63. if ($lang) {
  64. if (defined('LC_MESSAGES')) {
  65. _setlocale(LC_MESSAGES, $lang);
  66. } else if (defined('LC_ALL')) {
  67. _setlocale(LC_ALL, $lang);
  68. }
  69. if (defined('MOBILE_VERSION')) {
  70. _bindtextdomain("messages", "../locale");
  71. } else {
  72. _bindtextdomain("messages", "locale");
  73. }
  74. _textdomain("messages");
  75. _bind_textdomain_codeset("messages", "UTF-8");
  76. }
  77. }
  78. startup_gettext();
  79. require_once 'db-prefs.php';
  80. require_once 'version.php';
  81. define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
  82. define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
  83. define('MAGPIE_USER_AGENT', SELF_USER_AGENT);
  84. ini_set('user_agent', SELF_USER_AGENT);
  85. require_once 'lib/pubsubhubbub/publisher.php';
  86. $purifier = false;
  87. $tz_offset = -1;
  88. $utc_tz = new DateTimeZone('UTC');
  89. $schema_version = false;
  90. /**
  91. * Print a timestamped debug message.
  92. *
  93. * @param string $msg The debug message.
  94. * @return void
  95. */
  96. function _debug($msg) {
  97. if (defined('QUIET') && QUIET) {
  98. return;
  99. }
  100. $ts = strftime("%H:%M:%S", time());
  101. if (function_exists('posix_getpid')) {
  102. $ts = "$ts/" . posix_getpid();
  103. }
  104. print "[$ts] $msg\n";
  105. } // function _debug
  106. /**
  107. * Purge a feed old posts.
  108. *
  109. * @param mixed $link A database connection.
  110. * @param mixed $feed_id The id of the purged feed.
  111. * @param mixed $purge_interval Olderness of purged posts.
  112. * @param boolean $debug Set to True to enable the debug. False by default.
  113. * @access public
  114. * @return void
  115. */
  116. function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
  117. if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
  118. $rows = -1;
  119. $result = db_query($link,
  120. "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
  121. $owner_uid = false;
  122. if (db_num_rows($result) == 1) {
  123. $owner_uid = db_fetch_result($result, 0, "owner_uid");
  124. }
  125. if ($purge_interval == -1 || !$purge_interval) {
  126. if ($owner_uid) {
  127. ccache_update($link, $feed_id, $owner_uid);
  128. }
  129. return;
  130. }
  131. if (!$owner_uid) return;
  132. if (FORCE_ARTICLE_PURGE == 0) {
  133. $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
  134. $owner_uid, false);
  135. } else {
  136. $purge_unread = true;
  137. $purge_interval = FORCE_ARTICLE_PURGE;
  138. }
  139. if (!$purge_unread) $query_limit = " unread = false AND ";
  140. if (DB_TYPE == "pgsql") {
  141. $pg_version = get_pgsql_version($link);
  142. if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
  143. $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
  144. ttrss_entries.id = ref_id AND
  145. marked = false AND
  146. feed_id = '$feed_id' AND
  147. $query_limit
  148. ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
  149. } else {
  150. $result = db_query($link, "DELETE FROM ttrss_user_entries
  151. USING ttrss_entries
  152. WHERE ttrss_entries.id = ref_id AND
  153. marked = false AND
  154. feed_id = '$feed_id' AND
  155. $query_limit
  156. ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
  157. }
  158. $rows = pg_affected_rows($result);
  159. } else {
  160. /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
  161. marked = false AND feed_id = '$feed_id' AND
  162. (SELECT date_updated FROM ttrss_entries WHERE
  163. id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
  164. $result = db_query($link, "DELETE FROM ttrss_user_entries
  165. USING ttrss_user_entries, ttrss_entries
  166. WHERE ttrss_entries.id = ref_id AND
  167. marked = false AND
  168. feed_id = '$feed_id' AND
  169. $query_limit
  170. ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
  171. $rows = mysql_affected_rows($link);
  172. }
  173. ccache_update($link, $feed_id, $owner_uid);
  174. if ($debug) {
  175. _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
  176. }
  177. } // function purge_feed
  178. function feed_purge_interval($link, $feed_id) {
  179. $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
  180. WHERE id = '$feed_id'");
  181. if (db_num_rows($result) == 1) {
  182. $purge_interval = db_fetch_result($result, 0, "purge_interval");
  183. $owner_uid = db_fetch_result($result, 0, "owner_uid");
  184. if ($purge_interval == 0) $purge_interval = get_pref($link,
  185. 'PURGE_OLD_DAYS', $owner_uid);
  186. return $purge_interval;
  187. } else {
  188. return -1;
  189. }
  190. }
  191. function purge_orphans($link, $do_output = false) {
  192. // purge orphaned posts in main content table
  193. $result = db_query($link, "DELETE FROM ttrss_entries WHERE
  194. (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
  195. if ($do_output) {
  196. $rows = db_affected_rows($link, $result);
  197. _debug("Purged $rows orphaned posts.");
  198. }
  199. }
  200. function get_feed_update_interval($link, $feed_id) {
  201. $result = db_query($link, "SELECT owner_uid, update_interval FROM
  202. ttrss_feeds WHERE id = '$feed_id'");
  203. if (db_num_rows($result) == 1) {
  204. $update_interval = db_fetch_result($result, 0, "update_interval");
  205. $owner_uid = db_fetch_result($result, 0, "owner_uid");
  206. if ($update_interval != 0) {
  207. return $update_interval;
  208. } else {
  209. return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
  210. }
  211. } else {
  212. return -1;
  213. }
  214. }
  215. function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
  216. $login = urlencode($login);
  217. $pass = urlencode($pass);
  218. if (function_exists('curl_init') && !ini_get("open_basedir")) {
  219. $ch = curl_init($url);
  220. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
  221. curl_setopt($ch, CURLOPT_TIMEOUT, 45);
  222. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  223. curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
  224. curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
  225. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  226. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  227. curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  228. curl_setopt($ch, CURLOPT_USERAGENT, SELF_USER_AGENT);
  229. curl_setopt($ch, CURLOPT_ENCODING , "gzip");
  230. if ($post_query) {
  231. curl_setopt($ch, CURLOPT_POST, true);
  232. curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
  233. }
  234. if ($login && $pass)
  235. curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
  236. $contents = @curl_exec($ch);
  237. if ($contents === false) {
  238. curl_close($ch);
  239. return false;
  240. }
  241. $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  242. $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
  243. curl_close($ch);
  244. if ($http_code != 200 || $type && strpos($content_type, "$type") === false) {
  245. return false;
  246. }
  247. return $contents;
  248. } else {
  249. if ($login && $pass ){
  250. $url_parts = array();
  251. preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
  252. if ($url_parts[1] && $url_parts[2]) {
  253. $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
  254. }
  255. }
  256. return @file_get_contents($url);
  257. }
  258. }
  259. /**
  260. * Try to determine the favicon URL for a feed.
  261. * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
  262. * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
  263. *
  264. * @param string $url A feed or page URL
  265. * @access public
  266. * @return mixed The favicon URL, or false if none was found.
  267. */
  268. function get_favicon_url($url) {
  269. $favicon_url = false;
  270. if ($html = @fetch_file_contents($url)) {
  271. libxml_use_internal_errors(true);
  272. $doc = new DOMDocument();
  273. $doc->loadHTML($html);
  274. $xpath = new DOMXPath($doc);
  275. $base = $xpath->query('/html/head/base');
  276. foreach ($base as $b) {
  277. $url = $b->getAttribute("href");
  278. break;
  279. }
  280. $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
  281. if (count($entries) > 0) {
  282. foreach ($entries as $entry) {
  283. $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
  284. break;
  285. }
  286. }
  287. }
  288. if (!$favicon_url)
  289. $favicon_url = rewrite_relative_url($url, "/favicon.ico");
  290. return $favicon_url;
  291. } // function get_favicon_url
  292. function check_feed_favicon($site_url, $feed, $link) {
  293. # print "FAVICON [$site_url]: $favicon_url\n";
  294. $icon_file = ICONS_DIR . "/$feed.ico";
  295. if (!file_exists($icon_file)) {
  296. $favicon_url = get_favicon_url($site_url);
  297. if ($favicon_url) {
  298. // Limiting to "image" type misses those served with text/plain
  299. $contents = fetch_file_contents($favicon_url); // , "image");
  300. if ($contents) {
  301. // Crude image type matching.
  302. // Patterns gleaned from the file(1) source code.
  303. if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
  304. // 0 string \000\000\001\000 MS Windows icon resource
  305. //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
  306. }
  307. elseif (preg_match('/^GIF8/', $contents)) {
  308. // 0 string GIF8 GIF image data
  309. //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
  310. }
  311. elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
  312. // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
  313. //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
  314. }
  315. elseif (preg_match('/^\xff\xd8/', $contents)) {
  316. // 0 beshort 0xffd8 JPEG image data
  317. //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
  318. }
  319. else {
  320. //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
  321. $contents = "";
  322. }
  323. }
  324. if ($contents) {
  325. $fp = @fopen($icon_file, "w");
  326. if ($fp) {
  327. fwrite($fp, $contents);
  328. fclose($fp);
  329. chmod($icon_file, 0644);
  330. }
  331. }
  332. }
  333. }
  334. }
  335. function print_select($id, $default, $values, $attributes = "") {
  336. print "<select name=\"$id\" id=\"$id\" $attributes>";
  337. foreach ($values as $v) {
  338. if ($v == $default)
  339. $sel = "selected=\"1\"";
  340. else
  341. $sel = "";
  342. print "<option value=\"$v\" $sel>$v</option>";
  343. }
  344. print "</select>";
  345. }
  346. function print_select_hash($id, $default, $values, $attributes = "") {
  347. print "<select name=\"$id\" id='$id' $attributes>";
  348. foreach (array_keys($values) as $v) {
  349. if ($v == $default)
  350. $sel = 'selected="selected"';
  351. else
  352. $sel = "";
  353. print "<option $sel value=\"$v\">".$values[$v]."</option>";
  354. }
  355. print "</select>";
  356. }
  357. function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
  358. $matches = array();
  359. if ($filters["title"]) {
  360. foreach ($filters["title"] as $filter) {
  361. $reg_exp = $filter["reg_exp"];
  362. $inverse = $filter["inverse"];
  363. if ((!$inverse && @preg_match("/$reg_exp/i", $title)) ||
  364. ($inverse && !@preg_match("/$reg_exp/i", $title))) {
  365. array_push($matches, array($filter["action"], $filter["action_param"]));
  366. }
  367. }
  368. }
  369. if ($filters["content"]) {
  370. foreach ($filters["content"] as $filter) {
  371. $reg_exp = $filter["reg_exp"];
  372. $inverse = $filter["inverse"];
  373. if ((!$inverse && @preg_match("/$reg_exp/i", $content)) ||
  374. ($inverse && !@preg_match("/$reg_exp/i", $content))) {
  375. array_push($matches, array($filter["action"], $filter["action_param"]));
  376. }
  377. }
  378. }
  379. if ($filters["both"]) {
  380. foreach ($filters["both"] as $filter) {
  381. $reg_exp = $filter["reg_exp"];
  382. $inverse = $filter["inverse"];
  383. if ($inverse) {
  384. if (!@preg_match("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
  385. array_push($matches, array($filter["action"], $filter["action_param"]));
  386. }
  387. } else {
  388. if (@preg_match("/$reg_exp/i", $title) || preg_match("/$reg_exp/i", $content)) {
  389. array_push($matches, array($filter["action"], $filter["action_param"]));
  390. }
  391. }
  392. }
  393. }
  394. if ($filters["link"]) {
  395. $reg_exp = $filter["reg_exp"];
  396. foreach ($filters["link"] as $filter) {
  397. $reg_exp = $filter["reg_exp"];
  398. $inverse = $filter["inverse"];
  399. if ((!$inverse && @preg_match("/$reg_exp/i", $link)) ||
  400. ($inverse && !@preg_match("/$reg_exp/i", $link))) {
  401. array_push($matches, array($filter["action"], $filter["action_param"]));
  402. }
  403. }
  404. }
  405. if ($filters["date"]) {
  406. $reg_exp = $filter["reg_exp"];
  407. foreach ($filters["date"] as $filter) {
  408. $date_modifier = $filter["filter_param"];
  409. $inverse = $filter["inverse"];
  410. $check_timestamp = strtotime($filter["reg_exp"]);
  411. # no-op when timestamp doesn't parse to prevent misfires
  412. if ($check_timestamp) {
  413. $match_ok = false;
  414. if ($date_modifier == "before" && $timestamp < $check_timestamp ||
  415. $date_modifier == "after" && $timestamp > $check_timestamp) {
  416. $match_ok = true;
  417. }
  418. if ($inverse) $match_ok = !$match_ok;
  419. if ($match_ok) {
  420. array_push($matches, array($filter["action"], $filter["action_param"]));
  421. }
  422. }
  423. }
  424. }
  425. if ($filters["author"]) {
  426. foreach ($filters["author"] as $filter) {
  427. $reg_exp = $filter["reg_exp"];
  428. $inverse = $filter["inverse"];
  429. if ((!$inverse && @preg_match("/$reg_exp/i", $author)) ||
  430. ($inverse && !@preg_match("/$reg_exp/i", $author))) {
  431. array_push($matches, array($filter["action"], $filter["action_param"]));
  432. }
  433. }
  434. }
  435. if ($filters["tag"]) {
  436. $tag_string = join(",", $tags);
  437. foreach ($filters["tag"] as $filter) {
  438. $reg_exp = $filter["reg_exp"];
  439. $inverse = $filter["inverse"];
  440. if ((!$inverse && @preg_match("/$reg_exp/i", $tag_string)) ||
  441. ($inverse && !@preg_match("/$reg_exp/i", $tag_string))) {
  442. array_push($matches, array($filter["action"], $filter["action_param"]));
  443. }
  444. }
  445. }
  446. return $matches;
  447. }
  448. function find_article_filter($filters, $filter_name) {
  449. foreach ($filters as $f) {
  450. if ($f[0] == $filter_name) {
  451. return $f;
  452. };
  453. }
  454. return false;
  455. }
  456. function calculate_article_score($filters) {
  457. $score = 0;
  458. foreach ($filters as $f) {
  459. if ($f[0] == "score") {
  460. $score += $f[1];
  461. };
  462. }
  463. return $score;
  464. }
  465. function assign_article_to_labels($link, $id, $filters, $owner_uid) {
  466. foreach ($filters as $f) {
  467. if ($f[0] == "label") {
  468. label_add_article($link, $id, $f[1], $owner_uid);
  469. };
  470. }
  471. }
  472. function getmicrotime() {
  473. list($usec, $sec) = explode(" ",microtime());
  474. return ((float)$usec + (float)$sec);
  475. }
  476. function print_radio($id, $default, $true_is, $values, $attributes = "") {
  477. foreach ($values as $v) {
  478. if ($v == $default)
  479. $sel = "checked";
  480. else
  481. $sel = "";
  482. if ($v == $true_is) {
  483. $sel .= " value=\"1\"";
  484. } else {
  485. $sel .= " value=\"0\"";
  486. }
  487. print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
  488. type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
  489. }
  490. }
  491. function initialize_user_prefs($link, $uid, $profile = false) {
  492. $uid = db_escape_string($uid);
  493. if (!$profile) {
  494. $profile = "NULL";
  495. $profile_qpart = "AND profile IS NULL";
  496. } else {
  497. $profile_qpart = "AND profile = '$profile'";
  498. }
  499. if (get_schema_version($link) < 63) $profile_qpart = "";
  500. db_query($link, "BEGIN");
  501. $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
  502. $u_result = db_query($link, "SELECT pref_name
  503. FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
  504. $active_prefs = array();
  505. while ($line = db_fetch_assoc($u_result)) {
  506. array_push($active_prefs, $line["pref_name"]);
  507. }
  508. while ($line = db_fetch_assoc($result)) {
  509. if (array_search($line["pref_name"], $active_prefs) === FALSE) {
  510. // print "adding " . $line["pref_name"] . "<br>";
  511. if (get_schema_version($link) < 63) {
  512. db_query($link, "INSERT INTO ttrss_user_prefs
  513. (owner_uid,pref_name,value) VALUES
  514. ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
  515. } else {
  516. db_query($link, "INSERT INTO ttrss_user_prefs
  517. (owner_uid,pref_name,value, profile) VALUES
  518. ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
  519. }
  520. }
  521. }
  522. db_query($link, "COMMIT");
  523. }
  524. function get_ssl_certificate_id() {
  525. if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
  526. return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
  527. $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
  528. $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
  529. $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
  530. }
  531. return "";
  532. }
  533. function authenticate_user($link, $login, $password, $check_only = false) {
  534. if (!SINGLE_USER_MODE) {
  535. $user_id = false;
  536. $modules = explode(",", AUTH_MODULES);
  537. foreach ($modules as $module) {
  538. $module_class = "auth_$module";
  539. if (class_exists($module_class)) {
  540. $authenticator = new $module_class($link);
  541. $user_id = (int) $authenticator->authenticate($login, $password);
  542. if ($user_id) break;
  543. } else {
  544. print T_sprintf("Fatal: authentication module %s not found.", $module);
  545. die;
  546. }
  547. }
  548. if ($user_id && !$check_only) {
  549. $_SESSION["uid"] = $user_id;
  550. $result = db_query($link, "SELECT login,access_level,pwd_hash FROM ttrss_users
  551. WHERE id = '$user_id'");
  552. $_SESSION["name"] = db_fetch_result($result, 0, "login");
  553. $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
  554. $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
  555. db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
  556. $_SESSION["uid"]);
  557. $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
  558. $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
  559. $_SESSION["last_version_check"] = time();
  560. initialize_user_prefs($link, $_SESSION["uid"]);
  561. return true;
  562. }
  563. return false;
  564. } else {
  565. $_SESSION["uid"] = 1;
  566. $_SESSION["name"] = "admin";
  567. $_SESSION["access_level"] = 10;
  568. $_SESSION["hide_hello"] = true;
  569. $_SESSION["hide_logout"] = true;
  570. if (!$_SESSION["csrf_token"]) {
  571. $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
  572. }
  573. $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
  574. initialize_user_prefs($link, $_SESSION["uid"]);
  575. return true;
  576. }
  577. }
  578. function make_password($length = 8) {
  579. $password = "";
  580. $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
  581. $i = 0;
  582. while ($i < $length) {
  583. $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
  584. if (!strstr($password, $char)) {
  585. $password .= $char;
  586. $i++;
  587. }
  588. }
  589. return $password;
  590. }
  591. // this is called after user is created to initialize default feeds, labels
  592. // or whatever else
  593. // user preferences are checked on every login, not here
  594. function initialize_user($link, $uid) {
  595. db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
  596. values ('$uid', 'Tiny Tiny RSS: New Releases',
  597. 'http://tt-rss.org/releases.rss')");
  598. db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
  599. values ('$uid', 'Tiny Tiny RSS: Forum',
  600. 'http://tt-rss.org/forum/rss.php')");
  601. }
  602. function logout_user() {
  603. session_destroy();
  604. if (isset($_COOKIE[session_name()])) {
  605. setcookie(session_name(), '', time()-42000, '/');
  606. }
  607. }
  608. function validate_csrf($csrf_token) {
  609. return $csrf_token == $_SESSION['csrf_token'];
  610. }
  611. function validate_session($link) {
  612. if (SINGLE_USER_MODE) return true;
  613. $check_ip = $_SESSION['ip_address'];
  614. switch (SESSION_CHECK_ADDRESS) {
  615. case 0:
  616. $check_ip = '';
  617. break;
  618. case 1:
  619. $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
  620. break;
  621. case 2:
  622. $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
  623. $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
  624. break;
  625. };
  626. if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
  627. $_SESSION["login_error_msg"] =
  628. __("Session failed to validate (incorrect IP)");
  629. return false;
  630. }
  631. if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
  632. return false;
  633. if ($_SESSION["uid"]) {
  634. $result = db_query($link,
  635. "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
  636. $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
  637. if ($pwd_hash != $_SESSION["pwd_hash"]) {
  638. return false;
  639. }
  640. }
  641. /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
  642. //print_r($_SESSION);
  643. if (time() > $_SESSION["cookie_lifetime"]) {
  644. return false;
  645. }
  646. } */
  647. return true;
  648. }
  649. function login_sequence($link, $mobile = false) {
  650. $_SESSION["prefs_cache"] = array();
  651. if (!SINGLE_USER_MODE) {
  652. $login_action = $_POST["login_action"];
  653. # try to authenticate user if called from login form
  654. if ($login_action == "do_login") {
  655. $login = db_escape_string($_POST["login"]);
  656. $password = $_POST["password"];
  657. $remember_me = $_POST["remember_me"];
  658. if (authenticate_user($link, $login, $password)) {
  659. $_POST["password"] = "";
  660. $_SESSION["language"] = $_POST["language"];
  661. $_SESSION["ref_schema_version"] = get_schema_version($link, true);
  662. $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
  663. if ($_POST["profile"]) {
  664. $profile = db_escape_string($_POST["profile"]);
  665. $result = db_query($link, "SELECT id FROM ttrss_settings_profiles
  666. WHERE id = '$profile' AND owner_uid = " . $_SESSION["uid"]);
  667. if (db_num_rows($result) != 0) {
  668. $_SESSION["profile"] = $profile;
  669. $_SESSION["prefs_cache"] = array();
  670. }
  671. }
  672. if ($_REQUEST['return']) {
  673. header("Location: " . $_REQUEST['return']);
  674. } else {
  675. header("Location: " . $_SERVER["REQUEST_URI"]);
  676. }
  677. exit;
  678. return;
  679. } else {
  680. $_SESSION["login_error_msg"] = __("Incorrect username or password");
  681. }
  682. }
  683. if (!$_SESSION["uid"] || !validate_session($link)) {
  684. if (AUTH_AUTO_LOGIN && authenticate_user($link, null, null)) {
  685. $_SESSION["ref_schema_version"] = get_schema_version($link, true);
  686. } else {
  687. authenticate_user($link, null, null, true);
  688. render_login_form($link, $mobile);
  689. exit;
  690. }
  691. } else {
  692. /* bump login timestamp */
  693. db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
  694. $_SESSION["uid"]);
  695. if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME > 0) {
  696. setcookie("ttrss_lang", $_SESSION["language"],
  697. time() + SESSION_COOKIE_LIFETIME);
  698. }
  699. // try to remove possible duplicates from feed counter cache
  700. // ccache_cleanup($link, $_SESSION["uid"]);
  701. }
  702. } else {
  703. return authenticate_user($link, "admin", null);
  704. }
  705. }
  706. function truncate_string($str, $max_len, $suffix = '&hellip;') {
  707. if (mb_strlen($str, "utf-8") > $max_len - 3) {
  708. return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
  709. } else {
  710. return $str;
  711. }
  712. }
  713. function theme_image($link, $filename) {
  714. if ($link) {
  715. $theme_path = get_user_theme_path($link);
  716. if ($theme_path && is_file($theme_path.$filename)) {
  717. return $theme_path.$filename;
  718. } else {
  719. return $filename;
  720. }
  721. } else {
  722. return $filename;
  723. }
  724. }
  725. function get_user_theme($link) {
  726. if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
  727. $theme_name = get_pref($link, "_THEME_ID");
  728. if (is_dir("themes/$theme_name")) {
  729. return $theme_name;
  730. } else {
  731. return '';
  732. }
  733. } else {
  734. return '';
  735. }
  736. }
  737. function get_user_theme_path($link) {
  738. $theme_path = '';
  739. if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
  740. $theme_name = get_pref($link, "_THEME_ID");
  741. if ($theme_name && is_dir("themes/$theme_name")) {
  742. $theme_path = "themes/$theme_name/";
  743. } else {
  744. $theme_name = '';
  745. }
  746. } else {
  747. $theme_path = '';
  748. }
  749. if ($theme_path) {
  750. if (is_file("$theme_path/theme.ini")) {
  751. $ini = parse_ini_file("$theme_path/theme.ini", true);
  752. if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED) {
  753. return $theme_path;
  754. }
  755. }
  756. }
  757. return '';
  758. }
  759. function get_user_theme_options($link) {
  760. $t = get_user_theme_path($link);
  761. if ($t) {
  762. if (is_file("$t/theme.ini")) {
  763. $ini = parse_ini_file("$t/theme.ini", true);
  764. if ($ini['theme']['version']) {
  765. return $ini['theme']['options'];
  766. }
  767. }
  768. }
  769. return '';
  770. }
  771. function print_theme_includes($link) {
  772. $t = get_user_theme_path($link);
  773. $time = time();
  774. if ($t) {
  775. print "<link rel=\"stylesheet\" type=\"text/css\"
  776. href=\"$t/theme.css?$time \">";
  777. if (file_exists("$t/theme.js")) {
  778. print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
  779. </script>";
  780. }
  781. }
  782. }
  783. function get_all_themes() {
  784. $themes = glob("themes/*");
  785. asort($themes);
  786. $rv = array();
  787. foreach ($themes as $t) {
  788. if (is_file("$t/theme.ini")) {
  789. $ini = parse_ini_file("$t/theme.ini", true);
  790. if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED &&
  791. !$ini['theme']['disabled']) {
  792. $entry = array();
  793. $entry["path"] = $t;
  794. $entry["base"] = basename($t);
  795. $entry["name"] = $ini['theme']['name'];
  796. $entry["version"] = $ini['theme']['version'];
  797. $entry["author"] = $ini['theme']['author'];
  798. $entry["options"] = $ini['theme']['options'];
  799. array_push($rv, $entry);
  800. }
  801. }
  802. }
  803. return $rv;
  804. }
  805. function convert_timestamp($timestamp, $source_tz, $dest_tz) {
  806. try {
  807. $source_tz = new DateTimeZone($source_tz);
  808. } catch (Exception $e) {
  809. $source_tz = new DateTimeZone('UTC');
  810. }
  811. try {
  812. $dest_tz = new DateTimeZone($dest_tz);
  813. } catch (Exception $e) {
  814. $dest_tz = new DateTimeZone('UTC');
  815. }
  816. $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
  817. return $dt->format('U') + $dest_tz->getOffset($dt);
  818. }
  819. function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
  820. $no_smart_dt = false) {
  821. if (!$owner_uid) $owner_uid = $_SESSION['uid'];
  822. if (!$timestamp) $timestamp = '1970-01-01 0:00';
  823. global $utc_tz;
  824. global $tz_offset;
  825. # We store date in UTC internally
  826. $dt = new DateTime($timestamp, $utc_tz);
  827. if ($tz_offset == -1) {
  828. $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
  829. try {
  830. $user_tz = new DateTimeZone($user_tz_string);
  831. } catch (Exception $e) {
  832. $user_tz = $utc_tz;
  833. }
  834. $tz_offset = $user_tz->getOffset($dt);
  835. }
  836. $user_timestamp = $dt->format('U') + $tz_offset;
  837. if (!$no_smart_dt) {
  838. return smart_date_time($link, $user_timestamp,
  839. $tz_offset, $owner_uid);
  840. } else {
  841. if ($long)
  842. $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
  843. else
  844. $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
  845. return date($format, $user_timestamp);
  846. }
  847. }
  848. function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
  849. if (!$owner_uid) $owner_uid = $_SESSION['uid'];
  850. if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
  851. return date("G:i", $timestamp);
  852. } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
  853. $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
  854. return date($format, $timestamp);
  855. } else {
  856. $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
  857. return date($format, $timestamp);
  858. }
  859. }
  860. function sql_bool_to_bool($s) {
  861. if ($s == "t" || $s == "1" || $s == "true") {
  862. return true;
  863. } else {
  864. return false;
  865. }
  866. }
  867. function bool_to_sql_bool($s) {
  868. if ($s) {
  869. return "true";
  870. } else {
  871. return "false";
  872. }
  873. }
  874. // Session caching removed due to causing wrong redirects to upgrade
  875. // script when get_schema_version() is called on an obsolete session
  876. // created on a previous schema version.
  877. function get_schema_version($link, $nocache = false) {
  878. global $schema_version;
  879. if (!$schema_version) {
  880. $result = db_query($link, "SELECT schema_version FROM ttrss_version");
  881. $version = db_fetch_result($result, 0, "schema_version");
  882. $schema_version = $version;
  883. return $version;
  884. } else {
  885. return $schema_version;
  886. }
  887. }
  888. function sanity_check($link) {
  889. require_once 'errors.php';
  890. $error_code = 0;
  891. $schema_version = get_schema_version($link, true);
  892. if ($schema_version != SCHEMA_VERSION) {
  893. $error_code = 5;
  894. }
  895. if (DB_TYPE == "mysql") {
  896. $result = db_query($link, "SELECT true", false);
  897. if (db_num_rows($result) != 1) {
  898. $error_code = 10;
  899. }
  900. }
  901. if (db_escape_string("testTEST") != "testTEST") {
  902. $error_code = 12;
  903. }
  904. return array("code" => $error_code, "message" => $ERRORS[$error_code]);
  905. }
  906. function file_is_locked($filename) {
  907. if (function_exists('flock')) {
  908. $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
  909. if ($fp) {
  910. if (flock($fp, LOCK_EX | LOCK_NB)) {
  911. flock($fp, LOCK_UN);
  912. fclose($fp);
  913. return false;
  914. }
  915. fclose($fp);
  916. return true;
  917. } else {
  918. return false;
  919. }
  920. }
  921. return true; // consider the file always locked and skip the test
  922. }
  923. function make_lockfile($filename) {
  924. $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
  925. if (flock($fp, LOCK_EX | LOCK_NB)) {
  926. if (function_exists('posix_getpid')) {
  927. fwrite($fp, posix_getpid() . "\n");
  928. }
  929. return $fp;
  930. } else {
  931. return false;
  932. }
  933. }
  934. function make_stampfile($filename) {
  935. $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
  936. if (flock($fp, LOCK_EX | LOCK_NB)) {
  937. fwrite($fp, time() . "\n");
  938. flock($fp, LOCK_UN);
  939. fclose($fp);
  940. return true;
  941. } else {
  942. return false;
  943. }
  944. }
  945. function sql_random_function() {
  946. if (DB_TYPE == "mysql") {
  947. return "RAND()";
  948. } else {
  949. return "RANDOM()";
  950. }
  951. }
  952. function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false) {
  953. if (!$owner_uid) $owner_uid = $_SESSION['uid'];
  954. //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
  955. $ref_check_qpart = ($max_id &&
  956. !get_pref($link, 'REVERSE_HEADLINES')) ? "ref_id <= '$max_id'" : "true";
  957. if (is_numeric($feed)) {
  958. if ($cat_view) {
  959. if ($feed >= 0) {
  960. if ($feed > 0) {
  961. $cat_qpart = "cat_id = '$feed'";
  962. } else {
  963. $cat_qpart = "cat_id IS NULL";
  964. }
  965. $tmp_result = db_query($link, "SELECT id
  966. FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
  967. while ($tmp_line = db_fetch_assoc($tmp_result)) {
  968. $tmp_feed = $tmp_line["id"];
  969. db_query($link, "UPDATE ttrss_user_entries
  970. SET unread = false,last_read = NOW()
  971. WHERE feed_id = '$tmp_feed'
  972. AND $ref_check_qpart
  973. AND owner_uid = $owner_uid");
  974. }
  975. } else if ($feed == -2) {
  976. db_query($link, "UPDATE ttrss_user_entries
  977. SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
  978. FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
  979. AND $ref_check_qpart
  980. AND unread = true AND owner_uid = $owner_uid");
  981. }
  982. } else if ($feed > 0) {
  983. db_query($link, "UPDATE ttrss_user_entries
  984. SET unread = false,last_read = NOW()
  985. WHERE feed_id = '$feed'
  986. AND $ref_check_qpart
  987. AND owner_uid = $owner_uid");
  988. } else if ($feed < 0 && $feed > -10) { // special, like starred
  989. if ($feed == -1) {
  990. db_query($link, "UPDATE ttrss_user_entries
  991. SET unread = false,last_read = NOW()
  992. WHERE marked = true
  993. AND $ref_check_qpart
  994. AND owner_uid = $owner_uid");
  995. }
  996. if ($feed == -2) {
  997. db_query($link, "UPDATE ttrss_user_entries
  998. SET unread = false,last_read = NOW()
  999. WHERE published = true
  1000. AND $ref_check_qpart
  1001. AND owner_uid = $owner_uid");
  1002. }
  1003. if ($feed == -3) {
  1004. $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
  1005. if (DB_TYPE == "pgsql") {
  1006. $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
  1007. } else {
  1008. $match_part = "updated > DATE_SUB(NOW(),
  1009. INTERVAL $intl HOUR) ";
  1010. }
  1011. $result = db_query($link, "SELECT id FROM ttrss_entries,
  1012. ttrss_user_entries WHERE $match_part AND
  1013. unread = true AND
  1014. ttrss_user_entries.ref_id = ttrss_entries.id AND
  1015. owner_uid = $owner_uid");
  1016. $affected_ids = array();
  1017. while ($line = db_fetch_assoc($result)) {
  1018. array_push($affected_ids, $line["id"]);
  1019. }
  1020. catchupArticlesById($link, $affected_ids, 0);
  1021. }
  1022. if ($feed == -4) {
  1023. db_query($link, "UPDATE ttrss_user_entries
  1024. SET unread = false,last_read = NOW()
  1025. WHERE $ref_check_qpart AND owner_uid = $owner_uid");
  1026. }
  1027. } else if ($feed < -10) { // label
  1028. $label_id = -$feed - 11;
  1029. db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
  1030. SET unread = false, last_read = NOW()
  1031. WHERE label_id = '$label_id' AND unread = true
  1032. AND $ref_check_qpart
  1033. AND owner_uid = '$owner_uid' AND ref_id = article_id");
  1034. }
  1035. ccache_update($link, $feed, $owner_uid, $cat_view);
  1036. } else { // tag
  1037. db_query($link, "BEGIN");
  1038. $tag_name = db_escape_string($feed);
  1039. $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
  1040. WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
  1041. while ($line = db_fetch_assoc($result)) {
  1042. db_query($link, "UPDATE ttrss_user_entries SET
  1043. unread = false, last_read = NOW()
  1044. WHERE $ref_check_qpart AND int_id = " . $line["post_int_id"]);
  1045. }
  1046. db_query($link, "COMMIT");
  1047. }
  1048. }
  1049. function getAllCounters($link, $omode = "flc", $active_feed = false) {
  1050. if (!$omode) $omode = "flc";
  1051. $data = getGlobalCounters($link);
  1052. $data = array_merge($data, getVirtCounters($link));
  1053. if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
  1054. if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
  1055. if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
  1056. if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
  1057. return $data;
  1058. }
  1059. function getCategoryTitle($link, $cat_id) {
  1060. if ($cat_id == -1) {
  1061. return __("Special");
  1062. } else if ($cat_id == -2) {
  1063. return __("Labels");
  1064. } else {
  1065. $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
  1066. id = '$cat_id'");
  1067. if (db_num_rows($result) == 1) {
  1068. return db_fetch_result($result, 0, "title");
  1069. } else {
  1070. return "Uncategorized";
  1071. }
  1072. }
  1073. }
  1074. function getCategoryCounters($link) {
  1075. $ret_arr = array();
  1076. /* Labels category */
  1077. $cv = array("id" => -2, "kind" => "cat",
  1078. "counter" => getCategoryUnread($link, -2));
  1079. array_push($ret_arr, $cv);
  1080. $result = db_query($link, "SELECT id AS cat_id, value AS unread,
  1081. (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
  1082. WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
  1083. FROM ttrss_feed_categories, ttrss_cat_counters_cache
  1084. WHERE ttrss_cat_counters_cache.feed_id = id AND
  1085. ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
  1086. ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
  1087. while ($line = db_fetch_assoc($result)) {
  1088. $line["cat_id"] = (int) $line["cat_id"];
  1089. if ($line["num_children"] > 0) {
  1090. $child_counter = getCategoryChildrenUnread($link, $line["cat_id"], $_SESSION["uid"]);
  1091. } else {
  1092. $child_counter = 0;
  1093. }
  1094. $cv = array("id" => $line["cat_id"], "kind" => "cat",
  1095. "child_counter" => $child_counter,
  1096. "counter" => $line["unread"]);
  1097. array_push($ret_arr, $cv);
  1098. }
  1099. /* Special case: NULL category doesn't actually exist in the DB */
  1100. $cv = array("id" => 0, "kind" => "cat",
  1101. "counter" => ccache_find($link, 0, $_SESSION["uid"], true));
  1102. array_push($ret_arr, $cv);
  1103. return $ret_arr;
  1104. }
  1105. // only accepts real cats (>= 0)
  1106. function getCategoryChildrenUnread($link, $cat, $owner_uid = false) {
  1107. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  1108. $result = db_query($link, "SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
  1109. AND owner_uid = $owner_uid");
  1110. $unread = 0;
  1111. while ($line = db_fetch_assoc($result)) {
  1112. $unread += getCategoryUnread($link, $line["id"], $owner_uid);
  1113. $unread += getCategoryChildrenUnread($link, $line["id"], $owner_uid);
  1114. }
  1115. return $unread;
  1116. }
  1117. function getCategoryUnread($link, $cat, $owner_uid = false) {
  1118. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  1119. if ($cat >= 0) {
  1120. if ($cat != 0) {
  1121. $cat_query = "cat_id = '$cat'";
  1122. } else {
  1123. $cat_query = "cat_id IS NULL";
  1124. }
  1125. $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
  1126. AND owner_uid = " . $owner_uid);
  1127. $cat_feeds = array();
  1128. while ($line = db_fetch_assoc($result)) {
  1129. array_push($cat_feeds, "feed_id = " . $line["id"]);
  1130. }
  1131. if (count($cat_feeds) == 0) return 0;
  1132. $match_part = implode(" OR ", $cat_feeds);
  1133. $result = db_query($link, "SELECT COUNT(int_id) AS unread
  1134. FROM ttrss_user_entries
  1135. WHERE unread = true AND ($match_part)
  1136. AND owner_uid = " . $owner_uid);
  1137. $unread = 0;
  1138. # this needs to be rewritten
  1139. while ($line = db_fetch_assoc($result)) {
  1140. $unread += $line["unread"];
  1141. }
  1142. return $unread;
  1143. } else if ($cat == -1) {
  1144. return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3) + getFeedUnread($link, 0);
  1145. } else if ($cat == -2) {
  1146. $result = db_query($link, "
  1147. SELECT COUNT(unread) AS unread FROM
  1148. ttrss_user_entries, ttrss_user_labels2
  1149. WHERE article_id = ref_id AND unread = true
  1150. AND ttrss_user_entries.owner_uid = '$owner_uid'");
  1151. $unread = db_fetch_result($result, 0, "unread");
  1152. return $unread;
  1153. }
  1154. }
  1155. function getFeedUnread($link, $feed, $is_cat = false) {
  1156. return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
  1157. }
  1158. function getLabelUnread($link, $label_id, $owner_uid = false) {
  1159. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  1160. $result = db_query($link, "SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
  1161. WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
  1162. if (db_num_rows($result) != 0) {
  1163. return db_fetch_result($result, 0, "unread");
  1164. } else {
  1165. return 0;
  1166. }
  1167. }
  1168. function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
  1169. $owner_uid = false) {
  1170. $n_feed = (int) $feed;
  1171. $need_entries = false;
  1172. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  1173. if ($unread_only) {
  1174. $unread_qpart = "unread = true";
  1175. } else {
  1176. $unread_qpart = "true";
  1177. }
  1178. if ($is_cat) {
  1179. return getCategoryUnread($link, $n_feed, $owner_uid);
  1180. } if ($feed != "0" && $n_feed == 0) {
  1181. $feed = db_escape_string($feed);
  1182. $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
  1183. FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
  1184. AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
  1185. WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
  1186. return db_fetch_result($result, 0, "count");
  1187. } else if ($n_feed == -1) {
  1188. $match_part = "marked = true";
  1189. } else if ($n_feed == -2) {
  1190. $match_part = "published = true";
  1191. } else if ($n_feed == -3) {
  1192. $match_part = "unread = true AND score >= 0";
  1193. $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
  1194. if (DB_TYPE == "pgsql") {
  1195. $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
  1196. } else {
  1197. $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
  1198. }
  1199. $need_entries = true;
  1200. } else if ($n_feed == -4) {
  1201. $match_part = "true";
  1202. } else if ($n_feed >= 0) {
  1203. if ($n_feed != 0) {
  1204. $match_part = "feed_id = '$n_feed'";
  1205. } else {
  1206. $match_part = "feed_id IS NULL";
  1207. }
  1208. } else if ($feed < -10) {
  1209. $label_id = -$feed - 11;
  1210. return getLabelUnread($link, $label_id, $owner_uid);
  1211. }
  1212. if ($match_part) {
  1213. if ($need_entries) {
  1214. $from_qpart = "ttrss_user_entries,ttrss_entries";
  1215. $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
  1216. } else {
  1217. $from_qpart = "ttrss_user_entries";
  1218. }
  1219. $query = "SELECT count(int_id) AS unread
  1220. FROM $from_qpart WHERE
  1221. $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
  1222. //echo "[$feed/$query]\n";
  1223. $result = db_query($link, $query);
  1224. } else {
  1225. $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
  1226. FROM ttrss_tags,ttrss_user_entries,ttrss_entries
  1227. WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
  1228. AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
  1229. }
  1230. $unread = db_fetch_result($result, 0, "unread");
  1231. return $unread;
  1232. }
  1233. function getGlobalUnread($link, $user_id = false) {
  1234. if (!$user_id) {
  1235. $user_id = $_SESSION["uid"];
  1236. }
  1237. $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
  1238. WHERE owner_uid = '$user_id' AND feed_id > 0");
  1239. $c_id = db_fetch_result($result, 0, "c_id");
  1240. return $c_id;
  1241. }
  1242. function getGlobalCounters($link, $global_unread = -1) {
  1243. $ret_arr = array();
  1244. if ($global_unread == -1) {
  1245. $global_unread = getGlobalUnread($link);
  1246. }
  1247. $cv = array("id" => "global-unread",
  1248. "counter" => $global_unread);
  1249. array_push($ret_arr, $cv);
  1250. $result = db_query($link, "SELECT COUNT(id) AS fn FROM
  1251. ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
  1252. $subscribed_feeds = db_fetch_result($result, 0, "fn");
  1253. $cv = array("id" => "subscribed-feeds",
  1254. "counter" => $subscribed_feeds);
  1255. array_push($ret_arr, $cv);
  1256. return $ret_arr;
  1257. }
  1258. function getTagCounters($link) {
  1259. $ret_arr = array();
  1260. $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
  1261. FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
  1262. AND ref_id = id AND unread = true)) AS count FROM ttrss_tags
  1263. WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
  1264. ORDER BY count DESC LIMIT 55");
  1265. $tags = array();
  1266. while ($line = db_fetch_assoc($result)) {
  1267. $tags[$line["tag_name"]] += $line["count"];
  1268. }
  1269. foreach (array_keys($tags) as $tag) {
  1270. $unread = $tags[$tag];
  1271. $tag = htmlspecialchars($tag);
  1272. $cv = array("id" => $tag,
  1273. "kind" => "tag",
  1274. "counter" => $unread);
  1275. array_push($ret_arr, $cv);
  1276. }
  1277. return $ret_arr;
  1278. }
  1279. function getVirtCounters($link) {
  1280. $ret_arr = array();
  1281. for ($i = 0; $i >= -4; $i--) {
  1282. $count = getFeedUnread($link, $i);
  1283. $cv = array("id" => $i,
  1284. "counter" => $count);
  1285. // if (get_pref($link, 'EXTENDED_FEEDLIST'))
  1286. // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
  1287. array_push($ret_arr, $cv);
  1288. }
  1289. return $ret_arr;
  1290. }
  1291. function getLabelCounters($link, $descriptions = false) {
  1292. $ret_arr = array();
  1293. $owner_uid = $_SESSION["uid"];
  1294. $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
  1295. WHERE owner_uid = '$owner_uid'");
  1296. while ($line = db_fetch_assoc($result)) {
  1297. $id = -$line["id"] - 11;
  1298. $label_name = $line["caption"];
  1299. $count = getFeedUnread($link, $id);
  1300. $cv = array("id" => $id,
  1301. "counter" => $count);
  1302. if ($descriptions)
  1303. $cv["description"] = $label_name;
  1304. // if (get_pref($link, 'EXTENDED_FEEDLIST'))
  1305. // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
  1306. array_push($ret_arr, $cv);
  1307. }
  1308. return $ret_arr;
  1309. }
  1310. function getFeedCounters($link, $active_feed = false) {
  1311. $ret_arr = array();
  1312. $query = "SELECT ttrss_feeds.id,
  1313. ttrss_feeds.title,
  1314. ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
  1315. last_error, value AS count
  1316. FROM ttrss_feeds, ttrss_counters_cache
  1317. WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
  1318. AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
  1319. AND ttrss_counters_cache.feed_id = id";
  1320. $result = db_query($link, $query);
  1321. $fctrs_modified = false;
  1322. while ($line = db_fetch_assoc($result)) {
  1323. $id = $line["id"];
  1324. $count = $line["count"];
  1325. $last_error = htmlspecialchars($line["last_error"]);
  1326. $last_updated = make_local_datetime($link, $line['last_updated'], false);
  1327. $has_img = feed_has_icon($id);
  1328. if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
  1329. $last_updated = '';
  1330. $cv = array("id" => $id,
  1331. "updated" => $last_updated,
  1332. "counter" => $count,
  1333. "has_img" => (int) $has_img);
  1334. if ($last_error)
  1335. $cv["error"] = $last_error;
  1336. // if (get_pref($link, 'EXTENDED_FEEDLIST'))
  1337. // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
  1338. if ($active_feed && $id == $active_feed)
  1339. $cv["title"] = truncate_string($line["title"], 30);
  1340. array_push($ret_arr, $cv);
  1341. }
  1342. return $ret_arr;
  1343. }
  1344. function get_pgsql_version($link) {
  1345. $result = db_query($link, "SELECT version() AS version");
  1346. $version = explode(" ", db_fetch_result($result, 0, "version"));
  1347. return $version[1];
  1348. }
  1349. /**
  1350. * @return integer Status code:
  1351. * 0 - OK, Feed already exists
  1352. * 1 - OK, Feed added
  1353. * 2 - Invalid URL
  1354. * 3 - URL content is HTML, no feeds available
  1355. * 4 - URL content is HTML which contains multiple feeds.
  1356. * Here you should call extractfeedurls in rpc-backend
  1357. * to get all possible feeds.
  1358. * 5 - Couldn't download the URL content.
  1359. */
  1360. function subscribe_to_feed($link, $url, $cat_id = 0,
  1361. $auth_login = '', $auth_pass = '', $need_auth = false) {
  1362. require_once "include/rssfuncs.php";
  1363. $url = fix_url($url);
  1364. if (!$url || !validate_feed_url($url)) return 2;
  1365. $update_method = 0;
  1366. $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
  1367. WHERE id = ".$_SESSION['uid']);
  1368. $has_oauth = db_fetch_result($result, 0, 'twitter_oauth');
  1369. if (!$need_auth || !$has_oauth || strpos($url, '://api.twitter.com') === false) {
  1370. if (!fetch_file_contents($url, false, $auth_login, $auth_pass)) return 5;
  1371. if (url_is_html($url, $auth_login, $auth_pass)) {
  1372. $feedUrls = get_feeds_from_html($url, $auth_login, $auth_pass);
  1373. if (count($feedUrls) == 0) {
  1374. return 3;
  1375. } else if (count($feedUrls) > 1) {
  1376. return 4;
  1377. }
  1378. //use feed url as new URL
  1379. $url = key($feedUrls);
  1380. }
  1381. } else {
  1382. if (!fetch_twitter_rss($link, $url, $_SESSION['uid']))
  1383. return 5;
  1384. $update_method = 3;
  1385. }
  1386. if ($cat_id == "0" || !$cat_id) {
  1387. $cat_qpart = "NULL";
  1388. } else {
  1389. $cat_qpart = "'$cat_id'";
  1390. }
  1391. $result = db_query($link,
  1392. "SELECT id FROM ttrss_feeds
  1393. WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
  1394. if (db_num_rows($result) == 0) {
  1395. $result = db_query($link,
  1396. "INSERT INTO ttrss_feeds
  1397. (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
  1398. VALUES ('".$_SESSION["uid"]."', '$url',
  1399. '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
  1400. $result = db_query($link,
  1401. "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
  1402. AND owner_uid = " . $_SESSION["uid"]);
  1403. $feed_id = db_fetch_result($result, 0, "id");
  1404. if ($feed_id) {
  1405. update_rss_feed($link, $feed_id, true);
  1406. }
  1407. return 1;
  1408. } else {
  1409. return 0;
  1410. }
  1411. }
  1412. function print_feed_select($link, $id, $default_id = "",
  1413. $attributes = "", $include_all_feeds = true) {
  1414. print "<select id=\"$id\" name=\"$id\" $attributes>";
  1415. if ($include_all_feeds) {
  1416. print "<option value=\"0\">".__('All feeds')."</option>";
  1417. }
  1418. $result = db_query($link, "SELECT id,title FROM ttrss_feeds
  1419. WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
  1420. if (db_num_rows($result) > 0 && $include_all_feeds) {
  1421. print "<option disabled>--------</option>";
  1422. }
  1423. while ($line = db_fetch_assoc($result)) {
  1424. if ($line["id"] == $default_id) {
  1425. $is_selected = "selected=\"1\"";
  1426. } else {
  1427. $is_selected = "";
  1428. }
  1429. $title = truncate_string(htmlspecialchars($line["title"]), 40);
  1430. printf("<option $is_selected value='%d'>%s</option>",
  1431. $line["id"], $title);
  1432. }
  1433. print "</select>";
  1434. }
  1435. function print_feed_cat_select($link, $id, $default_id,
  1436. $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
  1437. if (!$root_id) {
  1438. print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
  1439. }
  1440. if ($root_id)
  1441. $parent_qpart = "parent_cat = '$root_id'";
  1442. else
  1443. $parent_qpart = "parent_cat IS NULL";
  1444. $result = db_query($link, "SELECT id,title,
  1445. (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
  1446. c2.parent_cat = ttrss_feed_categories.id) AS num_children
  1447. FROM ttrss_feed_categories
  1448. WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
  1449. while ($line = db_fetch_assoc($result)) {
  1450. if ($line["id"] == $default_id) {
  1451. $is_selected = "selected=\"1\"";
  1452. } else {
  1453. $is_selected = "";
  1454. }
  1455. for ($i = 0; $i < $nest_level; $i++)
  1456. $line["title"] = " - " . $line["title"];
  1457. if ($line["title"])
  1458. printf("<option $is_selected value='%d'>%s</option>",
  1459. $line["id"], htmlspecialchars($line["title"]));
  1460. if ($line["num_children"] > 0)
  1461. print_feed_cat_select($link, $id, $default_id, $attributes,
  1462. $include_all_cats, $line["id"], $nest_level+1);
  1463. }
  1464. if (!$root_id) {
  1465. if ($include_all_cats) {
  1466. if (db_num_rows($result) > 0) {
  1467. print "<option disabled=\"1\">--------</option>";
  1468. }
  1469. if ($default_id == 0) {
  1470. $is_selected = "selected=\"1\"";
  1471. } else {
  1472. $is_selected = "";
  1473. }
  1474. print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
  1475. }
  1476. print "</select>";
  1477. }
  1478. }
  1479. function checkbox_to_sql_bool($val) {
  1480. return ($val == "on") ? "true" : "false";
  1481. }
  1482. function getFeedCatTitle($link, $id) {
  1483. if ($id == -1) {
  1484. return __("Special");
  1485. } else if ($id < -10) {
  1486. return __("Labels");
  1487. } else if ($id > 0) {
  1488. $result = db_query($link, "SELECT ttrss_feed_categories.title
  1489. FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
  1490. cat_id = ttrss_feed_categories.id");
  1491. if (db_num_rows($result) == 1) {
  1492. return db_fetch_result($result, 0, "title");
  1493. } else {
  1494. return __("Uncategorized");
  1495. }
  1496. } else {
  1497. return "getFeedCatTitle($id) failed";
  1498. }
  1499. }
  1500. function getFeedIcon($id) {
  1501. switch ($id) {
  1502. case 0:
  1503. return "images/archive.png";
  1504. break;
  1505. case -1:
  1506. return "images/mark_set.png";
  1507. break;
  1508. case -2:
  1509. return "images/pub_set.png";
  1510. break;
  1511. case -3:
  1512. return "images/fresh.png";
  1513. break;
  1514. case -4:
  1515. return "images/tag.png";
  1516. break;
  1517. default:
  1518. if ($id < -10) {
  1519. return "images/label.png";
  1520. } else {
  1521. if (file_exists(ICONS_DIR . "/$id.ico"))
  1522. return ICONS_URL . "/$id.ico";
  1523. }
  1524. break;
  1525. }
  1526. }
  1527. function getFeedTitle($link, $id) {
  1528. if ($id == -1) {
  1529. return __("Starred articles");
  1530. } else if ($id == -2) {
  1531. return __("Published articles");
  1532. } else if ($id == -3) {
  1533. return __("Fresh articles");
  1534. } else if ($id == -4) {
  1535. return __("All articles");
  1536. } else if ($id === 0 || $id === "0") {
  1537. return __("Archived articles");
  1538. } else if ($id < -10) {
  1539. $label_id = -$id - 11;
  1540. $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
  1541. if (db_num_rows($result) == 1) {
  1542. return db_fetch_result($result, 0, "caption");
  1543. } else {
  1544. return "Unknown label ($label_id)";
  1545. }
  1546. } else if (is_numeric($id) && $id > 0) {
  1547. $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
  1548. if (db_num_rows($result) == 1) {
  1549. return db_fetch_result($result, 0, "title");
  1550. } else {
  1551. return "Unknown feed ($id)";
  1552. }
  1553. } else {
  1554. return $id;
  1555. }
  1556. }
  1557. function make_init_params($link) {
  1558. $params = array();
  1559. $params["theme"] = get_user_theme($link);
  1560. $params["theme_options"] = get_user_theme_options($link);
  1561. $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
  1562. $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
  1563. $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
  1564. $params["sign_info"] = theme_image($link, "images/sign_info.png");
  1565. foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
  1566. "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
  1567. "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
  1568. "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
  1569. $params[strtolower($param)] = (int) get_pref($link, $param);
  1570. }
  1571. $params["icons_url"] = ICONS_URL;
  1572. $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME;
  1573. $params["default_include_children"] = get_pref($link, "_DEFAULT_INCLUDE_CHILDREN");
  1574. $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
  1575. $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
  1576. $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
  1577. $params["bw_limit"] = (int) $_SESSION["bw_limit"];
  1578. $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
  1579. ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
  1580. $max_feed_id = db_fetch_result($result, 0, "mid");
  1581. $num_feeds = db_fetch_result($result, 0, "nf");
  1582. $params["max_feed_id"] = (int) $max_feed_id;
  1583. $params["num_feeds"] = (int) $num_feeds;
  1584. $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
  1585. $params["csrf_token"] = $_SESSION["csrf_token"];
  1586. return $params;
  1587. }
  1588. function make_runtime_info($link) {
  1589. $data = array();
  1590. $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
  1591. ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
  1592. $max_feed_id = db_fetch_result($result, 0, "mid");
  1593. $num_feeds = db_fetch_result($result, 0, "nf");
  1594. $data["max_feed_id"] = (int) $max_feed_id;
  1595. $data["num_feeds"] = (int) $num_feeds;
  1596. $data['last_article_id'] = getLastArticleId($link);
  1597. $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
  1598. if (file_exists(LOCK_DIRECTORY . "/update_daemon.lock")) {
  1599. $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
  1600. if (time() - $_SESSION["daemon_stamp_check"] > 30) {
  1601. $stamp = (int) @file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp");
  1602. if ($stamp) {
  1603. $stamp_delta = time() - $stamp;
  1604. if ($stamp_delta > 1800) {
  1605. $stamp_check = 0;
  1606. } else {
  1607. $stamp_check = 1;
  1608. $_SESSION["daemon_stamp_check"] = time();
  1609. }
  1610. $data['daemon_stamp_ok'] = $stamp_check;
  1611. $stamp_fmt = date("Y.m.d, G:i", $stamp);
  1612. $data['daemon_stamp'] = $stamp_fmt;
  1613. }
  1614. }
  1615. }
  1616. if ($_SESSION["last_version_check"] + 86400 + rand(-1000, 1000) < time()) {
  1617. $new_version_details = @check_for_update($link);
  1618. $data['new_version_available'] = (int) ($new_version_details != false);
  1619. $_SESSION["last_version_check"] = time();
  1620. }
  1621. return $data;
  1622. }
  1623. function search_to_sql($link, $search, $match_on) {
  1624. $search_query_part = "";
  1625. $keywords = explode(" ", $search);
  1626. $query_keywords = array();
  1627. foreach ($keywords as $k) {
  1628. if (strpos($k, "-") === 0) {
  1629. $k = substr($k, 1);
  1630. $not = "NOT";
  1631. } else {
  1632. $not = "";
  1633. }
  1634. $commandpair = explode(":", mb_strtolower($k), 2);
  1635. if ($commandpair[0] == "note" && $commandpair[1]) {
  1636. if ($commandpair[1] == "true")
  1637. array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
  1638. else
  1639. array_push($query_keywords, "($not (note IS NULL OR note = ''))");
  1640. } else if ($commandpair[0] == "star" && $commandpair[1]) {
  1641. if ($commandpair[1] == "true")
  1642. array_push($query_keywords, "($not (marked = true))");
  1643. else
  1644. array_push($query_keywords, "($not (marked = false))");
  1645. } else if ($commandpair[0] == "pub" && $commandpair[1]) {
  1646. if ($commandpair[1] == "true")
  1647. array_push($query_keywords, "($not (published = true))");
  1648. else
  1649. array_push($query_keywords, "($not (published = false))");
  1650. } else if (strpos($k, "@") === 0) {
  1651. $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
  1652. $orig_ts = strtotime(substr($k, 1));
  1653. $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
  1654. //$k = date("Y-m-d", strtotime(substr($k, 1)));
  1655. array_push($query_keywords, "(".SUBSTRING_FOR_DATE."(updated,1,LENGTH('$k')) $not = '$k')");
  1656. } else if ($match_on == "both") {
  1657. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
  1658. OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  1659. } else if ($match_on == "title") {
  1660. array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
  1661. } else if ($match_on == "content") {
  1662. array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
  1663. }
  1664. }
  1665. $search_query_part = implode("AND", $query_keywords);
  1666. return $search_query_part;
  1667. }
  1668. function getChildCategories($link, $cat, $owner_uid) {
  1669. $rv = array();
  1670. $result = db_query($link, "SELECT id FROM ttrss_feed_categories
  1671. WHERE parent_cat = '$cat' AND owner_uid = $owner_uid");
  1672. while ($line = db_fetch_assoc($result)) {
  1673. array_push($rv, $line["id"]);
  1674. $rv = array_merge($rv, getChildCategories($link, $line["id"], $owner_uid));
  1675. }
  1676. return $rv;
  1677. }
  1678. function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0, $filter = false, $since_id = 0, $include_children = false) {
  1679. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  1680. $ext_tables_part = "";
  1681. if ($search) {
  1682. if (SPHINX_ENABLED) {
  1683. $ids = join(",", @sphinx_search($search, 0, 500));
  1684. if ($ids)
  1685. $search_query_part = "ref_id IN ($ids) AND ";
  1686. else
  1687. $search_query_part = "ref_id = -1 AND ";
  1688. } else {
  1689. $search_query_part = search_to_sql($link, $search, $match_on);
  1690. $search_query_part .= " AND ";
  1691. }
  1692. } else {
  1693. $search_query_part = "";
  1694. }
  1695. if ($filter) {
  1696. $filter_query_part = filter_to_sql($filter);
  1697. } else {
  1698. $filter_query_part = "";
  1699. }
  1700. if ($since_id) {
  1701. $since_id_part = "ttrss_entries.id > $since_id AND ";
  1702. } else {
  1703. $since_id_part = "";
  1704. }
  1705. $view_query_part = "";
  1706. if ($view_mode == "adaptive" || $view_query_part == "noscores") {
  1707. if ($search) {
  1708. $view_query_part = " ";
  1709. } else if ($feed != -1) {
  1710. $unread = getFeedUnread($link, $feed, $cat_view);
  1711. if ($cat_view && $feed > 0 && $include_children)
  1712. $unread += getCategoryChildrenUnread($link, $feed);
  1713. if ($unread > 0) {
  1714. $view_query_part = " unread = true AND ";
  1715. }
  1716. }
  1717. }
  1718. if ($view_mode == "marked") {
  1719. $view_query_part = " marked = true AND ";
  1720. }
  1721. if ($view_mode == "published") {
  1722. $view_query_part = " published = true AND ";
  1723. }
  1724. if ($view_mode == "unread") {
  1725. $view_query_part = " unread = true AND ";
  1726. }
  1727. if ($view_mode == "updated") {
  1728. $view_query_part = " (last_read is null and unread = false) AND ";
  1729. }
  1730. if ($limit > 0) {
  1731. $limit_query_part = "LIMIT " . $limit;
  1732. }
  1733. $vfeed_query_part = "";
  1734. // override query strategy and enable feed display when searching globally
  1735. if ($search && $search_mode == "all_feeds") {
  1736. $query_strategy_part = "ttrss_entries.id > 0";
  1737. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1738. /* tags */
  1739. } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
  1740. $query_strategy_part = "ttrss_entries.id > 0";
  1741. $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
  1742. id = feed_id) as feed_title,";
  1743. } else if ($feed > 0 && $search && $search_mode == "this_cat") {
  1744. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1745. $tmp_result = false;
  1746. if ($cat_view) {
  1747. $tmp_result = db_query($link, "SELECT id
  1748. FROM ttrss_feeds WHERE cat_id = '$feed'");
  1749. } else {
  1750. $tmp_result = db_query($link, "SELECT id
  1751. FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
  1752. WHERE id = '$feed') AND id != '$feed'");
  1753. }
  1754. $cat_siblings = array();
  1755. if (db_num_rows($tmp_result) > 0) {
  1756. while ($p = db_fetch_assoc($tmp_result)) {
  1757. array_push($cat_siblings, "feed_id = " . $p["id"]);
  1758. }
  1759. $query_strategy_part = sprintf("(feed_id = %d OR %s)",
  1760. $feed, implode(" OR ", $cat_siblings));
  1761. } else {
  1762. $query_strategy_part = "ttrss_entries.id > 0";
  1763. }
  1764. } else if ($feed > 0) {
  1765. if ($cat_view) {
  1766. if ($feed > 0) {
  1767. if ($include_children) {
  1768. # sub-cats
  1769. $subcats = getChildCategories($link, $feed, $owner_uid);
  1770. if (count($subcats) == 0) {
  1771. $query_strategy_part = "cat_id = '$feed'";
  1772. } else {
  1773. array_push($subcats, $feed);
  1774. $query_strategy_part = "cat_id IN (".
  1775. implode(",", $subcats).")";
  1776. }
  1777. } else {
  1778. $query_strategy_part = "cat_id = '$feed'";
  1779. }
  1780. } else {
  1781. $query_strategy_part = "cat_id IS NULL";
  1782. }
  1783. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1784. } else {
  1785. $query_strategy_part = "feed_id = '$feed'";
  1786. }
  1787. } else if ($feed == 0 && !$cat_view) { // archive virtual feed
  1788. $query_strategy_part = "feed_id IS NULL";
  1789. } else if ($feed == 0 && $cat_view) { // uncategorized
  1790. $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
  1791. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1792. } else if ($feed == -1) { // starred virtual feed
  1793. $query_strategy_part = "marked = true";
  1794. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1795. } else if ($feed == -2) { // published virtual feed OR labels category
  1796. if (!$cat_view) {
  1797. $query_strategy_part = "published = true";
  1798. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1799. } else {
  1800. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1801. $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
  1802. $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
  1803. ttrss_user_labels2.article_id = ref_id";
  1804. }
  1805. } else if ($feed == -3) { // fresh virtual feed
  1806. $query_strategy_part = "unread = true AND score >= 0";
  1807. $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
  1808. if (DB_TYPE == "pgsql") {
  1809. $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
  1810. } else {
  1811. $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
  1812. }
  1813. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1814. } else if ($feed == -4) { // all articles virtual feed
  1815. $query_strategy_part = "true";
  1816. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1817. } else if ($feed <= -10) { // labels
  1818. $label_id = -$feed - 11;
  1819. $query_strategy_part = "label_id = '$label_id' AND
  1820. ttrss_labels2.id = ttrss_user_labels2.label_id AND
  1821. ttrss_user_labels2.article_id = ref_id";
  1822. $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
  1823. $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
  1824. } else {
  1825. $query_strategy_part = "id > 0"; // dumb
  1826. }
  1827. if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
  1828. $date_sort_field = "updated";
  1829. } else {
  1830. $date_sort_field = "date_entered";
  1831. }
  1832. if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
  1833. $order_by = "$date_sort_field";
  1834. } else {
  1835. $order_by = "$date_sort_field DESC";
  1836. }
  1837. if ($view_mode != "noscores") {
  1838. $order_by = "score DESC, $order_by";
  1839. }
  1840. if ($override_order) {
  1841. $order_by = $override_order;
  1842. }
  1843. $feed_title = "";
  1844. if ($search) {
  1845. $feed_title = "Search results";
  1846. } else {
  1847. if ($cat_view) {
  1848. $feed_title = getCategoryTitle($link, $feed);
  1849. } else {
  1850. if (is_numeric($feed) && $feed > 0) {
  1851. $result = db_query($link, "SELECT title,site_url,last_error
  1852. FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
  1853. $feed_title = db_fetch_result($result, 0, "title");
  1854. $feed_site_url = db_fetch_result($result, 0, "site_url");
  1855. $last_error = db_fetch_result($result, 0, "last_error");
  1856. } else {
  1857. $feed_title = getFeedTitle($link, $feed);
  1858. }
  1859. }
  1860. }
  1861. $content_query_part = "content as content_preview,";
  1862. if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
  1863. if ($feed >= 0) {
  1864. $feed_kind = "Feeds";
  1865. } else {
  1866. $feed_kind = "Labels";
  1867. }
  1868. if ($limit_query_part) {
  1869. $offset_query_part = "OFFSET $offset";
  1870. }
  1871. if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
  1872. if (!$override_order) {
  1873. $order_by = "ttrss_feeds.title, $order_by";
  1874. }
  1875. }
  1876. if ($feed != "0") {
  1877. $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
  1878. $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
  1879. } else {
  1880. $from_qpart = "ttrss_entries,ttrss_user_entries$ext_tables_part
  1881. LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
  1882. }
  1883. $query = "SELECT DISTINCT
  1884. date_entered,
  1885. guid,
  1886. ttrss_entries.id,ttrss_entries.title,
  1887. updated,
  1888. label_cache,
  1889. tag_cache,
  1890. always_display_enclosures,
  1891. site_url,
  1892. note,
  1893. num_comments,
  1894. comments,
  1895. int_id,
  1896. unread,feed_id,marked,published,link,last_read,orig_feed_id,
  1897. ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
  1898. $vfeed_query_part
  1899. $content_query_part
  1900. ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
  1901. author,score
  1902. FROM
  1903. $from_qpart
  1904. WHERE
  1905. $feed_check_qpart
  1906. ttrss_user_entries.ref_id = ttrss_entries.id AND
  1907. ttrss_user_entries.owner_uid = '$owner_uid' AND
  1908. $search_query_part
  1909. $filter_query_part
  1910. $view_query_part
  1911. $since_id_part
  1912. $query_strategy_part ORDER BY $order_by
  1913. $limit_query_part $offset_query_part";
  1914. if ($_REQUEST["debug"]) print $query;
  1915. $result = db_query($link, $query);
  1916. } else {
  1917. // browsing by tag
  1918. $select_qpart = "SELECT DISTINCT " .
  1919. "date_entered," .
  1920. "guid," .
  1921. "note," .
  1922. "ttrss_entries.id as id," .
  1923. "title," .
  1924. "updated," .
  1925. "unread," .
  1926. "feed_id," .
  1927. "orig_feed_id," .
  1928. "marked," .
  1929. "num_comments, " .
  1930. "comments, " .
  1931. "tag_cache," .
  1932. "label_cache," .
  1933. "link," .
  1934. "last_read," .
  1935. SUBSTRING_FOR_DATE . "(last_read,1,19) as last_read_noms," .
  1936. $since_id_part .
  1937. $vfeed_query_part .
  1938. $content_query_part .
  1939. SUBSTRING_FOR_DATE . "(updated,1,19) as updated_noms," .
  1940. "score ";
  1941. $feed_kind = "Tags";
  1942. $all_tags = explode(",", $feed);
  1943. if ($search_mode == 'any') {
  1944. $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
  1945. $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
  1946. $where_qpart = " WHERE " .
  1947. "ref_id = ttrss_entries.id AND " .
  1948. "ttrss_user_entries.owner_uid = $owner_uid AND " .
  1949. "post_int_id = int_id AND $tag_sql AND " .
  1950. $view_query_part .
  1951. $search_query_part .
  1952. $query_strategy_part . " ORDER BY $order_by " .
  1953. $limit_query_part;
  1954. } else {
  1955. $i = 1;
  1956. $sub_selects = array();
  1957. $sub_ands = array();
  1958. foreach ($all_tags as $term) {
  1959. 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");
  1960. $i++;
  1961. }
  1962. if ($i > 2) {
  1963. $x = 1;
  1964. $y = 2;
  1965. do {
  1966. array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
  1967. $x++;
  1968. $y++;
  1969. } while ($y < $i);
  1970. }
  1971. array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
  1972. array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
  1973. $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
  1974. $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
  1975. }
  1976. // error_log("TAG SQL: " . $tag_sql);
  1977. // $tag_sql = "tag_name = '$feed'"; DEFAULT way
  1978. // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
  1979. $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
  1980. }
  1981. return array($result, $feed_title, $feed_site_url, $last_error);
  1982. }
  1983. function sanitize($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
  1984. global $purifier;
  1985. if (!$owner) $owner = $_SESSION["uid"];
  1986. $res = trim($str); if (!$res) return '';
  1987. // create global Purifier object if needed
  1988. if (!$purifier) {
  1989. require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
  1990. $config = HTMLPurifier_Config::createDefault();
  1991. $allowed = "p,a[href],i,em,b,strong,code,pre,blockquote,br,img[src|alt|title|align|hspace],ul,ol,li,h1,h2,h3,h4,s,object[classid|type|id|name|width|height|codebase],param[name|value],table,tr,td,span[class]";
  1992. $config->set('HTML.SafeObject', true);
  1993. @$config->set('HTML', 'Allowed', $allowed);
  1994. $config->set('Output.FlashCompat', true);
  1995. $config->set('Attr.EnableID', true);
  1996. if (!defined('MOBILE_VERSION')) {
  1997. @$config->set('Cache', 'SerializerPath', CACHE_DIR . "/htmlpurifier");
  1998. } else {
  1999. @$config->set('Cache', 'SerializerPath', "../" . CACHE_DIR . "/htmlpurifier");
  2000. }
  2001. $config->set('Filter.YouTube', true);
  2002. $purifier = new HTMLPurifier($config);
  2003. }
  2004. $res = $purifier->purify($res);
  2005. if (get_pref($link, "STRIP_IMAGES", $owner)) {
  2006. $res = preg_replace('/<img[^>]+>/is', '', $res);
  2007. }
  2008. if (strpos($res, "href=") === false)
  2009. $res = rewrite_urls($res);
  2010. $charset_hack = '<head>
  2011. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  2012. </head>';
  2013. $res = trim($res); if (!$res) return '';
  2014. libxml_use_internal_errors(true);
  2015. $doc = new DOMDocument();
  2016. $doc->loadHTML($charset_hack . $res);
  2017. $xpath = new DOMXPath($doc);
  2018. $entries = $xpath->query('(//a[@href]|//img[@src])');
  2019. $br_inserted = 0;
  2020. foreach ($entries as $entry) {
  2021. if ($site_url) {
  2022. if ($entry->hasAttribute('href'))
  2023. $entry->setAttribute('href',
  2024. rewrite_relative_url($site_url, $entry->getAttribute('href')));
  2025. if ($entry->hasAttribute('src'))
  2026. if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
  2027. $entry->setAttribute('src',
  2028. rewrite_relative_url($site_url, $entry->getAttribute('src')));
  2029. }
  2030. if (strtolower($entry->nodeName) == "a") {
  2031. $entry->setAttribute("target", "_blank");
  2032. }
  2033. if (strtolower($entry->nodeName) == "img" && !$br_inserted) {
  2034. $br = $doc->createElement("br");
  2035. if ($entry->parentNode->nextSibling) {
  2036. $entry->parentNode->insertBefore($br, $entry->nextSibling);
  2037. $br_inserted = 1;
  2038. }
  2039. }
  2040. }
  2041. $node = $doc->getElementsByTagName('body')->item(0);
  2042. return $doc->saveXML($node, LIBXML_NOEMPTYTAG);
  2043. }
  2044. /**
  2045. * Send by mail a digest of last articles.
  2046. *
  2047. * @param mixed $link The database connection.
  2048. * @param integer $limit The maximum number of articles by digest.
  2049. * @return boolean Return false if digests are not enabled.
  2050. */
  2051. function send_headlines_digests($link, $debug = false) {
  2052. require_once 'lib/phpmailer/class.phpmailer.php';
  2053. $user_limit = 15; // amount of users to process (e.g. emails to send out)
  2054. $limit = 1000; // maximum amount of headlines to include
  2055. if ($debug) _debug("Sending digests, batch of max $user_limit users, headline limit = $limit");
  2056. if (DB_TYPE == "pgsql") {
  2057. $interval_query = "last_digest_sent < NOW() - INTERVAL '1 days'";
  2058. } else if (DB_TYPE == "mysql") {
  2059. $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL 1 DAY)";
  2060. }
  2061. $result = db_query($link, "SELECT id,email FROM ttrss_users
  2062. WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
  2063. while ($line = db_fetch_assoc($result)) {
  2064. if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
  2065. $preferred_ts = strtotime(get_pref($link, 'DIGEST_PREFERRED_TIME', $line['id'], '00:00'));
  2066. // try to send digests within 2 hours of preferred time
  2067. if ($preferred_ts && time() >= $preferred_ts &&
  2068. time() - $preferred_ts <= 7200) {
  2069. if ($debug) print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
  2070. $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
  2071. global $tz_offset;
  2072. // reset tz_offset global to prevent tz cache clash between users
  2073. $tz_offset = -1;
  2074. $tuple = prepare_headlines_digest($link, $line["id"], 1, $limit);
  2075. $digest = $tuple[0];
  2076. $headlines_count = $tuple[1];
  2077. $affected_ids = $tuple[2];
  2078. $digest_text = $tuple[3];
  2079. if ($headlines_count > 0) {
  2080. $mail = new PHPMailer();
  2081. $mail->PluginDir = "lib/phpmailer/";
  2082. $mail->SetLanguage("en", "lib/phpmailer/language/");
  2083. $mail->CharSet = "UTF-8";
  2084. $mail->From = SMTP_FROM_ADDRESS;
  2085. $mail->FromName = SMTP_FROM_NAME;
  2086. $mail->AddAddress($line["email"], $line["login"]);
  2087. if (SMTP_HOST) {
  2088. $mail->Host = SMTP_HOST;
  2089. $mail->Mailer = "smtp";
  2090. $mail->SMTPAuth = SMTP_LOGIN != '';
  2091. $mail->Username = SMTP_LOGIN;
  2092. $mail->Password = SMTP_PASSWORD;
  2093. }
  2094. $mail->IsHTML(true);
  2095. $mail->Subject = DIGEST_SUBJECT;
  2096. $mail->Body = $digest;
  2097. $mail->AltBody = $digest_text;
  2098. $rc = $mail->Send();
  2099. if (!$rc && $debug) print "ERROR: " . $mail->ErrorInfo;
  2100. if ($debug) print "RC=$rc\n";
  2101. if ($rc && $do_catchup) {
  2102. if ($debug) print "Marking affected articles as read...\n";
  2103. catchupArticlesById($link, $affected_ids, 0, $line["id"]);
  2104. }
  2105. } else {
  2106. if ($debug) print "No headlines\n";
  2107. }
  2108. db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
  2109. WHERE id = " . $line["id"]);
  2110. }
  2111. }
  2112. }
  2113. if ($debug) _debug("All done.");
  2114. }
  2115. function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 1000) {
  2116. require_once "lib/MiniTemplator.class.php";
  2117. $tpl = new MiniTemplator;
  2118. $tpl_t = new MiniTemplator;
  2119. $tpl->readTemplateFromFile("templates/digest_template_html.txt");
  2120. $tpl_t->readTemplateFromFile("templates/digest_template.txt");
  2121. $user_tz_string = get_pref($link, 'USER_TIMEZONE', $user_id);
  2122. $local_ts = convert_timestamp(time(), 'UTC', $user_tz_string);
  2123. $tpl->setVariable('CUR_DATE', date('Y/m/d', $local_ts));
  2124. $tpl->setVariable('CUR_TIME', date('G:i', $local_ts));
  2125. $tpl_t->setVariable('CUR_DATE', date('Y/m/d', $local_ts));
  2126. $tpl_t->setVariable('CUR_TIME', date('G:i', $local_ts));
  2127. $affected_ids = array();
  2128. if (DB_TYPE == "pgsql") {
  2129. $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
  2130. } else if (DB_TYPE == "mysql") {
  2131. $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
  2132. }
  2133. $result = db_query($link, "SELECT ttrss_entries.title,
  2134. ttrss_feeds.title AS feed_title,
  2135. COALESCE(ttrss_feed_categories.title, '".__('Uncategorized')."') AS cat_title,
  2136. date_updated,
  2137. ttrss_user_entries.ref_id,
  2138. link,
  2139. score,
  2140. content,
  2141. ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
  2142. FROM
  2143. ttrss_user_entries,ttrss_entries,ttrss_feeds
  2144. LEFT JOIN
  2145. ttrss_feed_categories ON (cat_id = ttrss_feed_categories.id)
  2146. WHERE
  2147. ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
  2148. AND include_in_digest = true
  2149. AND $interval_query
  2150. AND ttrss_user_entries.owner_uid = $user_id
  2151. AND unread = true
  2152. AND score >= 0
  2153. ORDER BY ttrss_feed_categories.title, ttrss_feeds.title, score DESC, date_updated DESC
  2154. LIMIT $limit");
  2155. $cur_feed_title = "";
  2156. $headlines_count = db_num_rows($result);
  2157. $headlines = array();
  2158. while ($line = db_fetch_assoc($result)) {
  2159. array_push($headlines, $line);
  2160. }
  2161. for ($i = 0; $i < sizeof($headlines); $i++) {
  2162. $line = $headlines[$i];
  2163. array_push($affected_ids, $line["ref_id"]);
  2164. $updated = make_local_datetime($link, $line['last_updated'], false,
  2165. $user_id);
  2166. /* if ($line["score"] != 0) {
  2167. if ($line["score"] > 0) $line["score"] = '+' . $line["score"];
  2168. $line["title"] .= " (".$line['score'].")";
  2169. } */
  2170. if (get_pref($link, 'ENABLE_FEED_CATS', $user_id)) {
  2171. $line['feed_title'] = $line['cat_title'] . " / " . $line['feed_title'];
  2172. }
  2173. $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
  2174. $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
  2175. $tpl->setVariable('ARTICLE_LINK', $line["link"]);
  2176. $tpl->setVariable('ARTICLE_UPDATED', $updated);
  2177. $tpl->setVariable('ARTICLE_EXCERPT',
  2178. truncate_string(strip_tags($line["content"]), 300));
  2179. // $tpl->setVariable('ARTICLE_CONTENT',
  2180. // strip_tags($article_content));
  2181. $tpl->addBlock('article');
  2182. $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
  2183. $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
  2184. $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
  2185. $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
  2186. // $tpl_t->setVariable('ARTICLE_EXCERPT',
  2187. // truncate_string(strip_tags($line["excerpt"]), 100));
  2188. $tpl_t->addBlock('article');
  2189. if ($headlines[$i]['feed_title'] != $headlines[$i+1]['feed_title']) {
  2190. $tpl->addBlock('feed');
  2191. $tpl_t->addBlock('feed');
  2192. }
  2193. }
  2194. $tpl->addBlock('digest');
  2195. $tpl->generateOutputToString($tmp);
  2196. $tpl_t->addBlock('digest');
  2197. $tpl_t->generateOutputToString($tmp_t);
  2198. return array($tmp, $headlines_count, $affected_ids, $tmp_t);
  2199. }
  2200. function check_for_update($link) {
  2201. if (CHECK_FOR_NEW_VERSION && $_SESSION['access_level'] >= 10) {
  2202. $version_url = "http://tt-rss.org/version.php?ver=" . VERSION;
  2203. $version_data = @fetch_file_contents($version_url);
  2204. if ($version_data) {
  2205. $version_data = json_decode($version_data, true);
  2206. if ($version_data && $version_data['version']) {
  2207. if (version_compare(VERSION, $version_data['version']) == -1) {
  2208. return $version_data;
  2209. }
  2210. }
  2211. }
  2212. }
  2213. return false;
  2214. }
  2215. function markArticlesById($link, $ids, $cmode) {
  2216. $tmp_ids = array();
  2217. foreach ($ids as $id) {
  2218. array_push($tmp_ids, "ref_id = '$id'");
  2219. }
  2220. $ids_qpart = join(" OR ", $tmp_ids);
  2221. if ($cmode == 0) {
  2222. db_query($link, "UPDATE ttrss_user_entries SET
  2223. marked = false,last_read = NOW()
  2224. WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
  2225. } else if ($cmode == 1) {
  2226. db_query($link, "UPDATE ttrss_user_entries SET
  2227. marked = true
  2228. WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
  2229. } else {
  2230. db_query($link, "UPDATE ttrss_user_entries SET
  2231. marked = NOT marked,last_read = NOW()
  2232. WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
  2233. }
  2234. }
  2235. function publishArticlesById($link, $ids, $cmode) {
  2236. $tmp_ids = array();
  2237. foreach ($ids as $id) {
  2238. array_push($tmp_ids, "ref_id = '$id'");
  2239. }
  2240. $ids_qpart = join(" OR ", $tmp_ids);
  2241. if ($cmode == 0) {
  2242. db_query($link, "UPDATE ttrss_user_entries SET
  2243. published = false,last_read = NOW()
  2244. WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
  2245. } else if ($cmode == 1) {
  2246. db_query($link, "UPDATE ttrss_user_entries SET
  2247. published = true
  2248. WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
  2249. } else {
  2250. db_query($link, "UPDATE ttrss_user_entries SET
  2251. published = NOT published,last_read = NOW()
  2252. WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
  2253. }
  2254. if (PUBSUBHUBBUB_HUB) {
  2255. $rss_link = get_self_url_prefix() .
  2256. "/public.php?op=rss&id=-2&key=" .
  2257. get_feed_access_key($link, -2, false);
  2258. $p = new Publisher(PUBSUBHUBBUB_HUB);
  2259. $pubsub_result = $p->publish_update($rss_link);
  2260. }
  2261. }
  2262. function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
  2263. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  2264. if (count($ids) == 0) return;
  2265. $tmp_ids = array();
  2266. foreach ($ids as $id) {
  2267. array_push($tmp_ids, "ref_id = '$id'");
  2268. }
  2269. $ids_qpart = join(" OR ", $tmp_ids);
  2270. if ($cmode == 0) {
  2271. db_query($link, "UPDATE ttrss_user_entries SET
  2272. unread = false,last_read = NOW()
  2273. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  2274. } else if ($cmode == 1) {
  2275. db_query($link, "UPDATE ttrss_user_entries SET
  2276. unread = true
  2277. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  2278. } else {
  2279. db_query($link, "UPDATE ttrss_user_entries SET
  2280. unread = NOT unread,last_read = NOW()
  2281. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  2282. }
  2283. /* update ccache */
  2284. $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
  2285. WHERE ($ids_qpart) AND owner_uid = $owner_uid");
  2286. while ($line = db_fetch_assoc($result)) {
  2287. ccache_update($link, $line["feed_id"], $owner_uid);
  2288. }
  2289. }
  2290. function catchupArticleById($link, $id, $cmode) {
  2291. if ($cmode == 0) {
  2292. db_query($link, "UPDATE ttrss_user_entries SET
  2293. unread = false,last_read = NOW()
  2294. WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
  2295. } else if ($cmode == 1) {
  2296. db_query($link, "UPDATE ttrss_user_entries SET
  2297. unread = true
  2298. WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
  2299. } else {
  2300. db_query($link, "UPDATE ttrss_user_entries SET
  2301. unread = NOT unread,last_read = NOW()
  2302. WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
  2303. }
  2304. $feed_id = getArticleFeed($link, $id);
  2305. ccache_update($link, $feed_id, $_SESSION["uid"]);
  2306. }
  2307. function make_guid_from_title($title) {
  2308. return preg_replace("/[ \"\',.:;]/", "-",
  2309. mb_strtolower(strip_tags($title), 'utf-8'));
  2310. }
  2311. function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
  2312. $a_id = db_escape_string($id);
  2313. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  2314. $query = "SELECT DISTINCT tag_name,
  2315. owner_uid as owner FROM
  2316. ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
  2317. ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
  2318. $obj_id = md5("TAGS:$owner_uid:$id");
  2319. $tags = array();
  2320. /* check cache first */
  2321. if ($tag_cache === false) {
  2322. $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
  2323. WHERE ref_id = '$id' AND owner_uid = $owner_uid");
  2324. $tag_cache = db_fetch_result($result, 0, "tag_cache");
  2325. }
  2326. if ($tag_cache) {
  2327. $tags = explode(",", $tag_cache);
  2328. } else {
  2329. /* do it the hard way */
  2330. $tmp_result = db_query($link, $query);
  2331. while ($tmp_line = db_fetch_assoc($tmp_result)) {
  2332. array_push($tags, $tmp_line["tag_name"]);
  2333. }
  2334. /* update the cache */
  2335. $tags_str = db_escape_string(join(",", $tags));
  2336. db_query($link, "UPDATE ttrss_user_entries
  2337. SET tag_cache = '$tags_str' WHERE ref_id = '$id'
  2338. AND owner_uid = $owner_uid");
  2339. }
  2340. return $tags;
  2341. }
  2342. function trim_array($array) {
  2343. $tmp = $array;
  2344. array_walk($tmp, 'trim');
  2345. return $tmp;
  2346. }
  2347. function tag_is_valid($tag) {
  2348. if ($tag == '') return false;
  2349. if (preg_match("/^[0-9]*$/", $tag)) return false;
  2350. if (mb_strlen($tag) > 250) return false;
  2351. if (function_exists('iconv')) {
  2352. $tag = iconv("utf-8", "utf-8", $tag);
  2353. }
  2354. if (!$tag) return false;
  2355. return true;
  2356. }
  2357. function render_login_form($link, $mobile = 0) {
  2358. switch ($mobile) {
  2359. case 0:
  2360. require_once "login_form.php";
  2361. break;
  2362. case 1:
  2363. require_once "mobile/login_form.php";
  2364. break;
  2365. case 2:
  2366. require_once "mobile/classic/login_form.php";
  2367. }
  2368. }
  2369. // from http://developer.apple.com/internet/safari/faq.html
  2370. function no_cache_incantation() {
  2371. header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
  2372. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
  2373. header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
  2374. header("Cache-Control: post-check=0, pre-check=0", false);
  2375. header("Pragma: no-cache"); // HTTP/1.0
  2376. }
  2377. function format_warning($msg, $id = "") {
  2378. global $link;
  2379. return "<div class=\"warning\" id=\"$id\">
  2380. <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
  2381. }
  2382. function format_notice($msg, $id = "") {
  2383. global $link;
  2384. return "<div class=\"notice\" id=\"$id\">
  2385. <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
  2386. }
  2387. function format_error($msg, $id = "") {
  2388. global $link;
  2389. return "<div class=\"error\" id=\"$id\">
  2390. <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
  2391. }
  2392. function print_notice($msg) {
  2393. return print format_notice($msg);
  2394. }
  2395. function print_warning($msg) {
  2396. return print format_warning($msg);
  2397. }
  2398. function print_error($msg) {
  2399. return print format_error($msg);
  2400. }
  2401. function T_sprintf() {
  2402. $args = func_get_args();
  2403. return vsprintf(__(array_shift($args)), $args);
  2404. }
  2405. function format_inline_player($link, $url, $ctype) {
  2406. $entry = "";
  2407. if (strpos($ctype, "audio/") === 0) {
  2408. if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
  2409. strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
  2410. strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
  2411. $id = 'AUDIO-' . uniqid();
  2412. $entry .= "<audio id=\"$id\"\">
  2413. <source src=\"$url\"></source>
  2414. </audio>";
  2415. $entry .= "<span onclick=\"player(this)\"
  2416. title=\"".__("Click to play")."\" status=\"0\"
  2417. class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
  2418. } else {
  2419. $entry .= "<object type=\"application/x-shockwave-flash\"
  2420. data=\"lib/button/musicplayer.swf?song_url=$url\"
  2421. width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
  2422. <param name=\"movie\"
  2423. value=\"lib/button/musicplayer.swf?song_url=$url\" />
  2424. </object>";
  2425. }
  2426. }
  2427. $filename = substr($url, strrpos($url, "/")+1);
  2428. $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
  2429. $filename . " (" . $ctype . ")" . "</a>";
  2430. return $entry;
  2431. }
  2432. function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
  2433. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  2434. $rv = array();
  2435. $rv['id'] = $id;
  2436. /* we can figure out feed_id from article id anyway, why do we
  2437. * pass feed_id here? let's ignore the argument :( */
  2438. $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
  2439. WHERE ref_id = '$id'");
  2440. $feed_id = (int) db_fetch_result($result, 0, "feed_id");
  2441. $rv['feed_id'] = $feed_id;
  2442. //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
  2443. $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
  2444. WHERE id = '$feed_id' AND owner_uid = $owner_uid");
  2445. if (db_num_rows($result) == 1) {
  2446. $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
  2447. $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
  2448. } else {
  2449. $rtl_content = false;
  2450. $always_display_enclosures = false;
  2451. }
  2452. if ($rtl_content) {
  2453. $rtl_tag = "dir=\"RTL\"";
  2454. $rtl_class = "RTL";
  2455. } else {
  2456. $rtl_tag = "";
  2457. $rtl_class = "";
  2458. }
  2459. if ($mark_as_read) {
  2460. $result = db_query($link, "UPDATE ttrss_user_entries
  2461. SET unread = false,last_read = NOW()
  2462. WHERE ref_id = '$id' AND owner_uid = $owner_uid");
  2463. ccache_update($link, $feed_id, $owner_uid);
  2464. }
  2465. $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
  2466. ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
  2467. (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
  2468. (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
  2469. num_comments,
  2470. tag_cache,
  2471. author,
  2472. orig_feed_id,
  2473. note
  2474. FROM ttrss_entries,ttrss_user_entries
  2475. WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
  2476. if ($result) {
  2477. $line = db_fetch_assoc($result);
  2478. if ($line["icon_url"]) {
  2479. $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
  2480. } else {
  2481. $feed_icon = "&nbsp;";
  2482. }
  2483. $feed_site_url = $line['site_url'];
  2484. $num_comments = $line["num_comments"];
  2485. $entry_comments = "";
  2486. if ($num_comments > 0) {
  2487. if ($line["comments"]) {
  2488. $comments_url = $line["comments"];
  2489. } else {
  2490. $comments_url = $line["link"];
  2491. }
  2492. $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
  2493. } else {
  2494. if ($line["comments"] && $line["link"] != $line["comments"]) {
  2495. $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
  2496. }
  2497. }
  2498. if ($zoom_mode) {
  2499. header("Content-Type: text/html");
  2500. $rv['content'] .= "<html><head>
  2501. <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
  2502. <title>Tiny Tiny RSS - ".$line["title"]."</title>
  2503. <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
  2504. </head><body>";
  2505. }
  2506. $title_escaped = db_escape_string($line['title']);
  2507. $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
  2508. truncate_string(strip_tags($line['title']), 15) . "</div>";
  2509. $rv['content'] .= "<div id=\"PTITLE-FULL-$id\" style=\"display : none\">" .
  2510. strip_tags($line['title']) . "</div>";
  2511. $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
  2512. $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
  2513. class=\"postHeader\" id=\"POSTHDR-$id\">";
  2514. $entry_author = $line["author"];
  2515. if ($entry_author) {
  2516. $entry_author = __(" - ") . $entry_author;
  2517. }
  2518. $parsed_updated = make_local_datetime($link, $line["updated"], true,
  2519. $owner_uid, true);
  2520. $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
  2521. if ($line["link"]) {
  2522. $rv['content'] .= "<div class='postTitle' clear='both'><a target='_blank'
  2523. title=\"".htmlspecialchars($line['title'])."\"
  2524. href=\"" .
  2525. $line["link"] . "\">" .
  2526. truncate_string($line["title"], 100) .
  2527. "<span class='author'>$entry_author</span></a></div>";
  2528. } else {
  2529. $rv['content'] .= "<div class='postTitle' clear='both'>" . $line["title"] . "$entry_author</div>";
  2530. }
  2531. $tag_cache = $line["tag_cache"];
  2532. if (!$tag_cache)
  2533. $tags = get_article_tags($link, $id, $owner_uid);
  2534. else
  2535. $tags = explode(",", $tag_cache);
  2536. $tags_str = format_tags_string($tags, $id);
  2537. $tags_str_full = join(", ", $tags);
  2538. if (!$tags_str_full) $tags_str_full = __("no tags");
  2539. if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
  2540. $rv['content'] .= "<div class='postTags' style='float : right'>
  2541. <img src='".theme_image($link, 'images/tag.png')."'
  2542. class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
  2543. if (!$zoom_mode) {
  2544. $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
  2545. <a title=\"".__('Edit tags for this article')."\"
  2546. href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
  2547. $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
  2548. id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
  2549. position=\"below\">$tags_str_full</div>";
  2550. $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
  2551. class='tagsPic' style=\"cursor : pointer\"
  2552. onclick=\"postOpenInNewTab(event, $id)\"
  2553. alt='Zoom' title='".__('Open article in new tab')."'>";
  2554. $button_plugins = explode(",", ARTICLE_BUTTON_PLUGINS);
  2555. foreach ($button_plugins as $p) {
  2556. $pclass = trim("${p}_button");
  2557. if (class_exists($pclass)) {
  2558. $plugin = new $pclass($link);
  2559. $rv['content'] .= $plugin->render($id, $line);
  2560. }
  2561. }
  2562. $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
  2563. class='tagsPic' style=\"cursor : pointer\"
  2564. onclick=\"closeArticlePanel($id)\"
  2565. title='".__('Close article')."'>";
  2566. } else {
  2567. $tags_str = strip_tags($tags_str);
  2568. $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
  2569. }
  2570. $rv['content'] .= "</div>";
  2571. $rv['content'] .= "<div clear='both'>$entry_comments</div>";
  2572. if ($line["orig_feed_id"]) {
  2573. $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
  2574. WHERE id = ".$line["orig_feed_id"]);
  2575. if (db_num_rows($tmp_result) != 0) {
  2576. $rv['content'] .= "<div clear='both'>";
  2577. $rv['content'] .= __("Originally from:");
  2578. $rv['content'] .= "&nbsp;";
  2579. $tmp_line = db_fetch_assoc($tmp_result);
  2580. $rv['content'] .= "<a target='_blank'
  2581. href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
  2582. $tmp_line['title'] . "</a>";
  2583. $rv['content'] .= "&nbsp;";
  2584. $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
  2585. $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.png'></a>";
  2586. $rv['content'] .= "</div>";
  2587. }
  2588. }
  2589. $rv['content'] .= "</div>";
  2590. $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
  2591. if ($line['note']) {
  2592. $rv['content'] .= format_article_note($id, $line['note']);
  2593. }
  2594. $rv['content'] .= "</div>";
  2595. $rv['content'] .= "<div class=\"postIcon\">" .
  2596. "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
  2597. href=\"".htmlspecialchars($feed_site_url)."\">".
  2598. $feed_icon . "</a></div>";
  2599. $rv['content'] .= "<div class=\"postContent\">";
  2600. // N-grams
  2601. if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_RELATED_THRESHOLD')) {
  2602. $ngram_result = db_query($link, "SELECT id,title FROM
  2603. ttrss_entries,ttrss_user_entries
  2604. WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
  2605. AND similarity(title, '$title_escaped') >= "._NGRAM_TITLE_RELATED_THRESHOLD."
  2606. AND title != '$title_escaped'
  2607. AND owner_uid = $owner_uid");
  2608. if (db_num_rows($ngram_result) > 0) {
  2609. $rv['content'] .= "<div dojoType=\"dijit.form.DropDownButton\">".
  2610. "<span>" . __('Related')."</span>";
  2611. $rv['content'] .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
  2612. while ($nline = db_fetch_assoc($ngram_result)) {
  2613. $rv['content'] .= "<div onclick=\"hlOpenInNewTab(null,".$nline['id'].")\"
  2614. dojoType=\"dijit.MenuItem\">".$nline['title']."</div>";
  2615. }
  2616. $rv['content'] .= "</div></div><br/";
  2617. }
  2618. }
  2619. $article_content = sanitize($link, $line["content"], false, $owner_uid,
  2620. $feed_site_url);
  2621. $rv['content'] .= $article_content;
  2622. $rv['content'] .= format_article_enclosures($link, $id,
  2623. $always_display_enclosures, $article_content);
  2624. $rv['content'] .= "</div>";
  2625. $rv['content'] .= "</div>";
  2626. }
  2627. if ($zoom_mode) {
  2628. $rv['content'] .= "
  2629. <div style=\"text-align : center\">
  2630. <button onclick=\"return window.close()\">".
  2631. __("Close this window")."</button></div>";
  2632. $rv['content'] .= "</body></html>";
  2633. }
  2634. return $rv;
  2635. }
  2636. function print_checkpoint($n, $s) {
  2637. $ts = getmicrotime();
  2638. echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
  2639. return $ts;
  2640. }
  2641. function sanitize_tag($tag) {
  2642. $tag = trim($tag);
  2643. $tag = mb_strtolower($tag, 'utf-8');
  2644. $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
  2645. // $tag = str_replace('"', "", $tag);
  2646. // $tag = str_replace("+", " ", $tag);
  2647. $tag = str_replace("technorati tag: ", "", $tag);
  2648. return $tag;
  2649. }
  2650. function get_self_url_prefix() {
  2651. return SELF_URL_PATH;
  2652. }
  2653. function opml_publish_url($link){
  2654. $url_path = get_self_url_prefix();
  2655. $url_path .= "/opml.php?op=publish&key=" .
  2656. get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
  2657. return $url_path;
  2658. }
  2659. /**
  2660. * Purge a feed contents, marked articles excepted.
  2661. *
  2662. * @param mixed $link The database connection.
  2663. * @param integer $id The id of the feed to purge.
  2664. * @return void
  2665. */
  2666. function clear_feed_articles($link, $id) {
  2667. if ($id != 0) {
  2668. $result = db_query($link, "DELETE FROM ttrss_user_entries
  2669. WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
  2670. } else {
  2671. $result = db_query($link, "DELETE FROM ttrss_user_entries
  2672. WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
  2673. }
  2674. $result = db_query($link, "DELETE FROM ttrss_entries WHERE
  2675. (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
  2676. ccache_update($link, $id, $_SESSION['uid']);
  2677. } // function clear_feed_articles
  2678. /**
  2679. * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
  2680. *
  2681. * @return string The Mozilla Firefox feed adding URL.
  2682. */
  2683. function add_feed_url() {
  2684. //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
  2685. $url_path = get_self_url_prefix() .
  2686. "/backend.php?op=pref-feeds&quiet=1&method=add&feed_url=%s";
  2687. return $url_path;
  2688. } // function add_feed_url
  2689. function encrypt_password($pass, $salt = '', $mode2 = false) {
  2690. if ($salt && $mode2) {
  2691. return "MODE2:" . hash('sha256', $salt . $pass);
  2692. } else if ($salt) {
  2693. return "SHA1X:" . sha1("$salt:$pass");
  2694. } else {
  2695. return "SHA1:" . sha1($pass);
  2696. }
  2697. } // function encrypt_password
  2698. function sanitize_article_content($text) {
  2699. # we don't support CDATA sections in articles, they break our own escaping
  2700. $text = preg_replace("/\[\[CDATA/", "", $text);
  2701. $text = preg_replace("/\]\]\>/", "", $text);
  2702. return $text;
  2703. }
  2704. function load_filters($link, $feed, $owner_uid, $action_id = false) {
  2705. $filters = array();
  2706. if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
  2707. $result = db_query($link, "SELECT reg_exp,
  2708. ttrss_filter_types.name AS name,
  2709. ttrss_filter_actions.name AS action,
  2710. inverse,
  2711. action_param,
  2712. filter_param
  2713. FROM ttrss_filters
  2714. LEFT JOIN ttrss_feeds ON (ttrss_feeds.id = '$feed'),
  2715. ttrss_filter_types,ttrss_filter_actions
  2716. WHERE
  2717. enabled = true AND
  2718. $ftype_query_part
  2719. ttrss_filters.owner_uid = $owner_uid AND
  2720. ttrss_filter_types.id = filter_type AND
  2721. ttrss_filter_actions.id = action_id AND
  2722. ((cat_filter = true AND ttrss_feeds.cat_id = ttrss_filters.cat_id) OR
  2723. (cat_filter = true AND ttrss_feeds.cat_id IS NULL AND
  2724. ttrss_filters.cat_id IS NULL) OR
  2725. (cat_filter = false AND (feed_id IS NULL OR feed_id = '$feed')))
  2726. ORDER BY reg_exp");
  2727. while ($line = db_fetch_assoc($result)) {
  2728. if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
  2729. $filter["reg_exp"] = $line["reg_exp"];
  2730. $filter["action"] = $line["action"];
  2731. $filter["action_param"] = $line["action_param"];
  2732. $filter["filter_param"] = $line["filter_param"];
  2733. $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
  2734. array_push($filters[$line["name"]], $filter);
  2735. }
  2736. return $filters;
  2737. }
  2738. function get_score_pic($score) {
  2739. if ($score > 100) {
  2740. return "score_high.png";
  2741. } else if ($score > 0) {
  2742. return "score_half_high.png";
  2743. } else if ($score < -100) {
  2744. return "score_low.png";
  2745. } else if ($score < 0) {
  2746. return "score_half_low.png";
  2747. } else {
  2748. return "score_neutral.png";
  2749. }
  2750. }
  2751. function feed_has_icon($id) {
  2752. return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
  2753. }
  2754. function init_connection($link) {
  2755. if ($link) {
  2756. if (DB_TYPE == "pgsql") {
  2757. pg_query($link, "set client_encoding = 'UTF-8'");
  2758. pg_set_client_encoding("UNICODE");
  2759. pg_query($link, "set datestyle = 'ISO, european'");
  2760. pg_query($link, "set TIME ZONE 0");
  2761. } else {
  2762. db_query($link, "SET time_zone = '+0:0'");
  2763. if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) {
  2764. db_query($link, "SET NAMES " . MYSQL_CHARSET);
  2765. }
  2766. }
  2767. return true;
  2768. } else {
  2769. print "Unable to connect to database:" . db_last_error();
  2770. return false;
  2771. }
  2772. }
  2773. /* function ccache_zero($link, $feed_id, $owner_uid) {
  2774. db_query($link, "UPDATE ttrss_counters_cache SET
  2775. value = 0, updated = NOW() WHERE
  2776. feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
  2777. } */
  2778. function ccache_zero_all($link, $owner_uid) {
  2779. db_query($link, "UPDATE ttrss_counters_cache SET
  2780. value = 0 WHERE owner_uid = '$owner_uid'");
  2781. db_query($link, "UPDATE ttrss_cat_counters_cache SET
  2782. value = 0 WHERE owner_uid = '$owner_uid'");
  2783. }
  2784. function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
  2785. if (!$is_cat) {
  2786. $table = "ttrss_counters_cache";
  2787. } else {
  2788. $table = "ttrss_cat_counters_cache";
  2789. }
  2790. db_query($link, "DELETE FROM $table WHERE
  2791. feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
  2792. }
  2793. function ccache_update_all($link, $owner_uid) {
  2794. if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
  2795. $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
  2796. WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
  2797. while ($line = db_fetch_assoc($result)) {
  2798. ccache_update($link, $line["feed_id"], $owner_uid, true);
  2799. }
  2800. /* We have to manually include category 0 */
  2801. ccache_update($link, 0, $owner_uid, true);
  2802. } else {
  2803. $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
  2804. WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
  2805. while ($line = db_fetch_assoc($result)) {
  2806. print ccache_update($link, $line["feed_id"], $owner_uid);
  2807. }
  2808. }
  2809. }
  2810. function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
  2811. $no_update = false) {
  2812. if (!is_numeric($feed_id)) return;
  2813. if (!$is_cat) {
  2814. $table = "ttrss_counters_cache";
  2815. if ($feed_id > 0) {
  2816. $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
  2817. WHERE id = '$feed_id'");
  2818. $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
  2819. }
  2820. } else {
  2821. $table = "ttrss_cat_counters_cache";
  2822. }
  2823. if (DB_TYPE == "pgsql") {
  2824. $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
  2825. } else if (DB_TYPE == "mysql") {
  2826. $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
  2827. }
  2828. $result = db_query($link, "SELECT value FROM $table
  2829. WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
  2830. LIMIT 1");
  2831. if (db_num_rows($result) == 1) {
  2832. return db_fetch_result($result, 0, "value");
  2833. } else {
  2834. if ($no_update) {
  2835. return -1;
  2836. } else {
  2837. return ccache_update($link, $feed_id, $owner_uid, $is_cat);
  2838. }
  2839. }
  2840. }
  2841. function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
  2842. $update_pcat = true) {
  2843. if (!is_numeric($feed_id)) return;
  2844. if (!$is_cat && $feed_id > 0) {
  2845. $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
  2846. WHERE id = '$feed_id'");
  2847. $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
  2848. }
  2849. $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
  2850. /* When updating a label, all we need to do is recalculate feed counters
  2851. * because labels are not cached */
  2852. if ($feed_id < 0) {
  2853. ccache_update_all($link, $owner_uid);
  2854. return;
  2855. }
  2856. if (!$is_cat) {
  2857. $table = "ttrss_counters_cache";
  2858. } else {
  2859. $table = "ttrss_cat_counters_cache";
  2860. }
  2861. if ($is_cat && $feed_id >= 0) {
  2862. if ($feed_id != 0) {
  2863. $cat_qpart = "cat_id = '$feed_id'";
  2864. } else {
  2865. $cat_qpart = "cat_id IS NULL";
  2866. }
  2867. /* Recalculate counters for child feeds */
  2868. $result = db_query($link, "SELECT id FROM ttrss_feeds
  2869. WHERE owner_uid = '$owner_uid' AND $cat_qpart");
  2870. while ($line = db_fetch_assoc($result)) {
  2871. ccache_update($link, $line["id"], $owner_uid, false, false);
  2872. }
  2873. $result = db_query($link, "SELECT SUM(value) AS sv
  2874. FROM ttrss_counters_cache, ttrss_feeds
  2875. WHERE id = feed_id AND $cat_qpart AND
  2876. ttrss_feeds.owner_uid = '$owner_uid'");
  2877. $unread = (int) db_fetch_result($result, 0, "sv");
  2878. } else {
  2879. $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
  2880. }
  2881. db_query($link, "BEGIN");
  2882. $result = db_query($link, "SELECT feed_id FROM $table
  2883. WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
  2884. if (db_num_rows($result) == 1) {
  2885. db_query($link, "UPDATE $table SET
  2886. value = '$unread', updated = NOW() WHERE
  2887. feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
  2888. } else {
  2889. db_query($link, "INSERT INTO $table
  2890. (feed_id, value, owner_uid, updated)
  2891. VALUES
  2892. ($feed_id, $unread, $owner_uid, NOW())");
  2893. }
  2894. db_query($link, "COMMIT");
  2895. if ($feed_id > 0 && $prev_unread != $unread) {
  2896. if (!$is_cat) {
  2897. /* Update parent category */
  2898. if ($update_pcat) {
  2899. $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
  2900. WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
  2901. $cat_id = (int) db_fetch_result($result, 0, "cat_id");
  2902. ccache_update($link, $cat_id, $owner_uid, true);
  2903. }
  2904. }
  2905. } else if ($feed_id < 0) {
  2906. ccache_update_all($link, $owner_uid);
  2907. }
  2908. return $unread;
  2909. }
  2910. /* function ccache_cleanup($link, $owner_uid) {
  2911. if (DB_TYPE == "pgsql") {
  2912. db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
  2913. (SELECT count(*) FROM ttrss_counters_cache AS c2
  2914. WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
  2915. AND owner_uid = '$owner_uid'");
  2916. db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
  2917. (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
  2918. WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
  2919. AND owner_uid = '$owner_uid'");
  2920. } else {
  2921. db_query($link, "DELETE c1 FROM
  2922. ttrss_counters_cache AS c1,
  2923. ttrss_counters_cache AS c2
  2924. WHERE
  2925. c1.owner_uid = '$owner_uid' AND
  2926. c1.owner_uid = c2.owner_uid AND
  2927. c1.feed_id = c2.feed_id");
  2928. db_query($link, "DELETE c1 FROM
  2929. ttrss_cat_counters_cache AS c1,
  2930. ttrss_cat_counters_cache AS c2
  2931. WHERE
  2932. c1.owner_uid = '$owner_uid' AND
  2933. c1.owner_uid = c2.owner_uid AND
  2934. c1.feed_id = c2.feed_id");
  2935. }
  2936. } */
  2937. function label_find_id($link, $label, $owner_uid) {
  2938. $result = db_query($link,
  2939. "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
  2940. AND owner_uid = '$owner_uid' LIMIT 1");
  2941. if (db_num_rows($result) == 1) {
  2942. return db_fetch_result($result, 0, "id");
  2943. } else {
  2944. return 0;
  2945. }
  2946. }
  2947. function get_article_labels($link, $id) {
  2948. $rv = array();
  2949. $result = db_query($link, "SELECT label_cache FROM
  2950. ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
  2951. $_SESSION["uid"]);
  2952. $label_cache = db_fetch_result($result, 0, "label_cache");
  2953. if ($label_cache) {
  2954. $label_cache = json_decode($label_cache, true);
  2955. if ($label_cache["no-labels"] == 1)
  2956. return $rv;
  2957. else
  2958. return $label_cache;
  2959. }
  2960. $result = db_query($link,
  2961. "SELECT DISTINCT label_id,caption,fg_color,bg_color
  2962. FROM ttrss_labels2, ttrss_user_labels2
  2963. WHERE id = label_id
  2964. AND article_id = '$id'
  2965. AND owner_uid = ".$_SESSION["uid"] . "
  2966. ORDER BY caption");
  2967. while ($line = db_fetch_assoc($result)) {
  2968. $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
  2969. $line["bg_color"]);
  2970. array_push($rv, $rk);
  2971. }
  2972. if (count($rv) > 0)
  2973. label_update_cache($link, $id, $rv);
  2974. else
  2975. label_update_cache($link, $id, array("no-labels" => 1));
  2976. return $rv;
  2977. }
  2978. function label_find_caption($link, $label, $owner_uid) {
  2979. $result = db_query($link,
  2980. "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
  2981. AND owner_uid = '$owner_uid' LIMIT 1");
  2982. if (db_num_rows($result) == 1) {
  2983. return db_fetch_result($result, 0, "caption");
  2984. } else {
  2985. return "";
  2986. }
  2987. }
  2988. function label_update_cache($link, $id, $labels = false, $force = false) {
  2989. if ($force)
  2990. label_clear_cache($link, $id);
  2991. if (!$labels)
  2992. $labels = get_article_labels($link, $id);
  2993. $labels = db_escape_string(json_encode($labels));
  2994. db_query($link, "UPDATE ttrss_user_entries SET
  2995. label_cache = '$labels' WHERE ref_id = '$id'");
  2996. }
  2997. function label_clear_cache($link, $id) {
  2998. db_query($link, "UPDATE ttrss_user_entries SET
  2999. label_cache = '' WHERE ref_id = '$id'");
  3000. }
  3001. function label_remove_article($link, $id, $label, $owner_uid) {
  3002. $label_id = label_find_id($link, $label, $owner_uid);
  3003. if (!$label_id) return;
  3004. $result = db_query($link,
  3005. "DELETE FROM ttrss_user_labels2
  3006. WHERE
  3007. label_id = '$label_id' AND
  3008. article_id = '$id'");
  3009. label_clear_cache($link, $id);
  3010. }
  3011. function label_add_article($link, $id, $label, $owner_uid) {
  3012. $label_id = label_find_id($link, $label, $owner_uid);
  3013. if (!$label_id) return;
  3014. $result = db_query($link,
  3015. "SELECT
  3016. article_id FROM ttrss_labels2, ttrss_user_labels2
  3017. WHERE
  3018. label_id = id AND
  3019. label_id = '$label_id' AND
  3020. article_id = '$id' AND owner_uid = '$owner_uid'
  3021. LIMIT 1");
  3022. if (db_num_rows($result) == 0) {
  3023. db_query($link, "INSERT INTO ttrss_user_labels2
  3024. (label_id, article_id) VALUES ('$label_id', '$id')");
  3025. }
  3026. label_clear_cache($link, $id);
  3027. }
  3028. function label_remove($link, $id, $owner_uid) {
  3029. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  3030. db_query($link, "BEGIN");
  3031. $result = db_query($link, "SELECT caption FROM ttrss_labels2
  3032. WHERE id = '$id'");
  3033. $caption = db_fetch_result($result, 0, "caption");
  3034. $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
  3035. AND owner_uid = " . $owner_uid);
  3036. if (db_affected_rows($link, $result) != 0 && $caption) {
  3037. /* Remove access key for the label */
  3038. $ext_id = -11 - $id;
  3039. db_query($link, "DELETE FROM ttrss_access_keys WHERE
  3040. feed_id = '$ext_id' AND owner_uid = $owner_uid");
  3041. /* Disable filters that reference label being removed */
  3042. db_query($link, "UPDATE ttrss_filters SET
  3043. enabled = false WHERE action_param = '$caption'
  3044. AND action_id = 7
  3045. AND owner_uid = " . $owner_uid);
  3046. /* Remove cached data */
  3047. db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
  3048. WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
  3049. }
  3050. db_query($link, "COMMIT");
  3051. }
  3052. function label_create($link, $caption, $fg_color = '', $bg_color = '', $owner_uid) {
  3053. if (!$owner_uid) $owner_uid = $_SESSION['uid'];
  3054. db_query($link, "BEGIN");
  3055. $result = false;
  3056. $result = db_query($link, "SELECT id FROM ttrss_labels2
  3057. WHERE caption = '$caption' AND owner_uid = $owner_uid");
  3058. if (db_num_rows($result) == 0) {
  3059. $result = db_query($link,
  3060. "INSERT INTO ttrss_labels2 (caption,owner_uid,fg_color,bg_color)
  3061. VALUES ('$caption', '$owner_uid', '$fg_color', '$bg_color')");
  3062. $result = db_affected_rows($link, $result) != 0;
  3063. }
  3064. db_query($link, "COMMIT");
  3065. return $result;
  3066. }
  3067. function format_tags_string($tags, $id) {
  3068. $tags_str = "";
  3069. $tags_nolinks_str = "";
  3070. $num_tags = 0;
  3071. $tag_limit = 6;
  3072. $formatted_tags = array();
  3073. foreach ($tags as $tag) {
  3074. $num_tags++;
  3075. $tag_escaped = str_replace("'", "\\'", $tag);
  3076. if (mb_strlen($tag) > 30) {
  3077. $tag = truncate_string($tag, 30);
  3078. }
  3079. $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
  3080. array_push($formatted_tags, $tag_str);
  3081. $tmp_tags_str = implode(", ", $formatted_tags);
  3082. if ($num_tags == $tag_limit || mb_strlen($tmp_tags_str) > 150) {
  3083. break;
  3084. }
  3085. }
  3086. $tags_str = implode(", ", $formatted_tags);
  3087. if ($num_tags < count($tags)) {
  3088. $tags_str .= ", &hellip;";
  3089. }
  3090. if ($num_tags == 0) {
  3091. $tags_str = __("no tags");
  3092. }
  3093. return $tags_str;
  3094. }
  3095. function format_article_labels($labels, $id) {
  3096. $labels_str = "";
  3097. foreach ($labels as $l) {
  3098. $labels_str .= sprintf("<span class='hlLabelRef'
  3099. style='color : %s; background-color : %s'>%s</span>",
  3100. $l[2], $l[3], $l[1]);
  3101. }
  3102. return $labels_str;
  3103. }
  3104. function format_article_note($id, $note) {
  3105. $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
  3106. <div class='noteEdit' onclick=\"editArticleNote($id)\">".
  3107. __('(edit note)')."</div>$note</div>";
  3108. return $str;
  3109. }
  3110. function toggle_collapse_cat($link, $cat_id, $mode) {
  3111. if ($cat_id > 0) {
  3112. $mode = bool_to_sql_bool($mode);
  3113. db_query($link, "UPDATE ttrss_feed_categories SET
  3114. collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
  3115. $_SESSION["uid"]);
  3116. } else {
  3117. $pref_name = '';
  3118. switch ($cat_id) {
  3119. case -1:
  3120. $pref_name = '_COLLAPSED_SPECIAL';
  3121. break;
  3122. case -2:
  3123. $pref_name = '_COLLAPSED_LABELS';
  3124. break;
  3125. case 0:
  3126. $pref_name = '_COLLAPSED_UNCAT';
  3127. break;
  3128. }
  3129. if ($pref_name) {
  3130. if ($mode) {
  3131. set_pref($link, $pref_name, 'true');
  3132. } else {
  3133. set_pref($link, $pref_name, 'false');
  3134. }
  3135. }
  3136. }
  3137. }
  3138. function remove_feed($link, $id, $owner_uid) {
  3139. if ($id > 0) {
  3140. /* save starred articles in Archived feed */
  3141. db_query($link, "BEGIN");
  3142. /* prepare feed if necessary */
  3143. $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
  3144. WHERE id = '$id'");
  3145. if (db_num_rows($result) == 0) {
  3146. db_query($link, "INSERT INTO ttrss_archived_feeds
  3147. (id, owner_uid, title, feed_url, site_url)
  3148. SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
  3149. WHERE id = '$id'");
  3150. }
  3151. db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
  3152. orig_feed_id = '$id' WHERE feed_id = '$id' AND
  3153. marked = true AND owner_uid = $owner_uid");
  3154. /* Remove access key for the feed */
  3155. db_query($link, "DELETE FROM ttrss_access_keys WHERE
  3156. feed_id = '$id' AND owner_uid = $owner_uid");
  3157. /* remove the feed */
  3158. db_query($link, "DELETE FROM ttrss_feeds
  3159. WHERE id = '$id' AND owner_uid = $owner_uid");
  3160. db_query($link, "COMMIT");
  3161. if (file_exists(ICONS_DIR . "/$id.ico")) {
  3162. unlink(ICONS_DIR . "/$id.ico");
  3163. }
  3164. ccache_remove($link, $id, $owner_uid);
  3165. } else {
  3166. label_remove($link, -11-$id, $owner_uid);
  3167. ccache_remove($link, -11-$id, $owner_uid);
  3168. }
  3169. }
  3170. function get_feed_category($link, $feed_cat, $parent_cat_id = false) {
  3171. if ($parent_cat_id) {
  3172. $parent_qpart = "parent_cat = '$parent_cat_id'";
  3173. $parent_insert = "'$parent_cat_id'";
  3174. } else {
  3175. $parent_qpart = "parent_cat IS NULL";
  3176. $parent_insert = "NULL";
  3177. }
  3178. $result = db_query($link,
  3179. "SELECT id FROM ttrss_feed_categories
  3180. WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
  3181. if (db_num_rows($result) == 0) {
  3182. return false;
  3183. } else {
  3184. return db_fetch_result($result, 0, "id");
  3185. }
  3186. }
  3187. function add_feed_category($link, $feed_cat, $parent_cat_id = false) {
  3188. if (!$feed_cat) return false;
  3189. db_query($link, "BEGIN");
  3190. if ($parent_cat_id) {
  3191. $parent_qpart = "parent_cat = '$parent_cat_id'";
  3192. $parent_insert = "'$parent_cat_id'";
  3193. } else {
  3194. $parent_qpart = "parent_cat IS NULL";
  3195. $parent_insert = "NULL";
  3196. }
  3197. $result = db_query($link,
  3198. "SELECT id FROM ttrss_feed_categories
  3199. WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
  3200. if (db_num_rows($result) == 0) {
  3201. $result = db_query($link,
  3202. "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
  3203. VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
  3204. db_query($link, "COMMIT");
  3205. return true;
  3206. }
  3207. return false;
  3208. }
  3209. function remove_feed_category($link, $id, $owner_uid) {
  3210. db_query($link, "DELETE FROM ttrss_feed_categories
  3211. WHERE id = '$id' AND owner_uid = $owner_uid");
  3212. ccache_remove($link, $id, $owner_uid, true);
  3213. }
  3214. function archive_article($link, $id, $owner_uid) {
  3215. db_query($link, "BEGIN");
  3216. $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
  3217. WHERE ref_id = '$id' AND owner_uid = $owner_uid");
  3218. if (db_num_rows($result) != 0) {
  3219. /* prepare the archived table */
  3220. $feed_id = (int) db_fetch_result($result, 0, "feed_id");
  3221. if ($feed_id) {
  3222. $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
  3223. WHERE id = '$feed_id'");
  3224. if (db_num_rows($result) == 0) {
  3225. db_query($link, "INSERT INTO ttrss_archived_feeds
  3226. (id, owner_uid, title, feed_url, site_url)
  3227. SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
  3228. WHERE id = '$feed_id'");
  3229. }
  3230. db_query($link, "UPDATE ttrss_user_entries
  3231. SET orig_feed_id = feed_id, feed_id = NULL
  3232. WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
  3233. }
  3234. }
  3235. db_query($link, "COMMIT");
  3236. }
  3237. function getArticleFeed($link, $id) {
  3238. $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
  3239. WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
  3240. if (db_num_rows($result) != 0) {
  3241. return db_fetch_result($result, 0, "feed_id");
  3242. } else {
  3243. return 0;
  3244. }
  3245. }
  3246. /**
  3247. * Fixes incomplete URLs by prepending "http://".
  3248. * Also replaces feed:// with http://, and
  3249. * prepends a trailing slash if the url is a domain name only.
  3250. *
  3251. * @param string $url Possibly incomplete URL
  3252. *
  3253. * @return string Fixed URL.
  3254. */
  3255. function fix_url($url) {
  3256. if (strpos($url, '://') === false) {
  3257. $url = 'http://' . $url;
  3258. } else if (substr($url, 0, 5) == 'feed:') {
  3259. $url = 'http:' . substr($url, 5);
  3260. }
  3261. //prepend slash if the URL has no slash in it
  3262. // "http://www.example" -> "http://www.example/"
  3263. if (strpos($url, '/', strpos($url, ':') + 3) === false) {
  3264. $url .= '/';
  3265. }
  3266. if ($url != "http:///")
  3267. return $url;
  3268. else
  3269. return '';
  3270. }
  3271. function validate_feed_url($url) {
  3272. $parts = parse_url($url);
  3273. return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
  3274. }
  3275. function get_article_enclosures($link, $id) {
  3276. $query = "SELECT * FROM ttrss_enclosures
  3277. WHERE post_id = '$id' AND content_url != ''";
  3278. $rv = array();
  3279. $result = db_query($link, $query);
  3280. if (db_num_rows($result) > 0) {
  3281. while ($line = db_fetch_assoc($result)) {
  3282. array_push($rv, $line);
  3283. }
  3284. }
  3285. return $rv;
  3286. }
  3287. function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
  3288. $feeds = array();
  3289. /* Labels */
  3290. if ($cat_id == -4 || $cat_id == -2) {
  3291. $counters = getLabelCounters($link, true);
  3292. foreach (array_values($counters) as $cv) {
  3293. $unread = $cv["counter"];
  3294. if ($unread || !$unread_only) {
  3295. $row = array(
  3296. "id" => $cv["id"],
  3297. "title" => $cv["description"],
  3298. "unread" => $cv["counter"],
  3299. "cat_id" => -2,
  3300. );
  3301. array_push($feeds, $row);
  3302. }
  3303. }
  3304. }
  3305. /* Virtual feeds */
  3306. if ($cat_id == -4 || $cat_id == -1) {
  3307. foreach (array(-1, -2, -3, -4, 0) as $i) {
  3308. $unread = getFeedUnread($link, $i);
  3309. if ($unread || !$unread_only) {
  3310. $title = getFeedTitle($link, $i);
  3311. $row = array(
  3312. "id" => $i,
  3313. "title" => $title,
  3314. "unread" => $unread,
  3315. "cat_id" => -1,
  3316. );
  3317. array_push($feeds, $row);
  3318. }
  3319. }
  3320. }
  3321. /* Real feeds */
  3322. if ($limit) {
  3323. $limit_qpart = "LIMIT $limit OFFSET $offset";
  3324. } else {
  3325. $limit_qpart = "";
  3326. }
  3327. if ($cat_id == -4 || $cat_id == -3) {
  3328. $result = db_query($link, "SELECT
  3329. id, feed_url, cat_id, title, order_id, ".
  3330. SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
  3331. FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
  3332. " ORDER BY cat_id, title " . $limit_qpart);
  3333. } else {
  3334. if ($cat_id)
  3335. $cat_qpart = "cat_id = '$cat_id'";
  3336. else
  3337. $cat_qpart = "cat_id IS NULL";
  3338. $result = db_query($link, "SELECT
  3339. id, feed_url, cat_id, title, order_id, ".
  3340. SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
  3341. FROM ttrss_feeds WHERE
  3342. $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
  3343. " ORDER BY cat_id, title " . $limit_qpart);
  3344. }
  3345. while ($line = db_fetch_assoc($result)) {
  3346. $unread = getFeedUnread($link, $line["id"]);
  3347. $has_icon = feed_has_icon($line['id']);
  3348. if ($unread || !$unread_only) {
  3349. $row = array(
  3350. "feed_url" => $line["feed_url"],
  3351. "title" => $line["title"],
  3352. "id" => (int)$line["id"],
  3353. "unread" => (int)$unread,
  3354. "has_icon" => $has_icon,
  3355. "cat_id" => (int)$line["cat_id"],
  3356. "last_updated" => strtotime($line["last_updated"]),
  3357. "order_id" => (int) $line["order_id"],
  3358. );
  3359. array_push($feeds, $row);
  3360. }
  3361. }
  3362. return $feeds;
  3363. }
  3364. function api_get_headlines($link, $feed_id, $limit, $offset,
  3365. $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
  3366. $include_attachments, $since_id,
  3367. $search = "", $search_mode = "", $match_on = "") {
  3368. $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
  3369. $view_mode, $is_cat, $search, $search_mode, $match_on,
  3370. $order, $offset, 0, false, $since_id);
  3371. $result = $qfh_ret[0];
  3372. $feed_title = $qfh_ret[1];
  3373. $headlines = array();
  3374. while ($line = db_fetch_assoc($result)) {
  3375. $is_updated = ($line["last_read"] == "" &&
  3376. ($line["unread"] != "t" && $line["unread"] != "1"));
  3377. $tags = explode(",", $line["tag_cache"]);
  3378. $labels = json_decode($line["label_cache"], true);
  3379. //if (!$tags) $tags = get_article_tags($link, $line["id"]);
  3380. //if (!$labels) $labels = get_article_labels($link, $line["id"]);
  3381. $headline_row = array(
  3382. "id" => (int)$line["id"],
  3383. "unread" => sql_bool_to_bool($line["unread"]),
  3384. "marked" => sql_bool_to_bool($line["marked"]),
  3385. "published" => sql_bool_to_bool($line["published"]),
  3386. "updated" => strtotime($line["updated"]),
  3387. "is_updated" => $is_updated,
  3388. "title" => $line["title"],
  3389. "link" => $line["link"],
  3390. "feed_id" => $line["feed_id"],
  3391. "tags" => $tags,
  3392. );
  3393. if ($include_attachments)
  3394. $headline_row['attachments'] = get_article_enclosures($link,
  3395. $line['id']);
  3396. if ($show_excerpt) {
  3397. $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
  3398. $headline_row["excerpt"] = $excerpt;
  3399. }
  3400. if ($show_content) {
  3401. $headline_row["content"] = $line["content_preview"];
  3402. }
  3403. // unify label output to ease parsing
  3404. if ($labels["no-labels"] == 1) $labels = array();
  3405. $headline_row["labels"] = $labels;
  3406. $headline_row["feed_title"] = $line["feed_title"];
  3407. array_push($headlines, $headline_row);
  3408. }
  3409. return $headlines;
  3410. }
  3411. function generate_error_feed($link, $error) {
  3412. $reply = array();
  3413. $reply['headlines']['id'] = -6;
  3414. $reply['headlines']['is_cat'] = false;
  3415. $reply['headlines']['toolbar'] = '';
  3416. $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
  3417. $reply['headlines-info'] = array("count" => 0,
  3418. "vgroup_last_feed" => '',
  3419. "unread" => 0,
  3420. "disable_cache" => true);
  3421. return $reply;
  3422. }
  3423. function generate_dashboard_feed($link) {
  3424. $reply = array();
  3425. $reply['headlines']['id'] = -5;
  3426. $reply['headlines']['is_cat'] = false;
  3427. $reply['headlines']['toolbar'] = '';
  3428. $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
  3429. $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
  3430. $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
  3431. WHERE owner_uid = " . $_SESSION['uid']);
  3432. $last_updated = db_fetch_result($result, 0, "last_updated");
  3433. $last_updated = make_local_datetime($link, $last_updated, false);
  3434. $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
  3435. $result = db_query($link, "SELECT COUNT(id) AS num_errors
  3436. FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
  3437. $num_errors = db_fetch_result($result, 0, "num_errors");
  3438. if ($num_errors > 0) {
  3439. $reply['headlines']['content'] .= "<br/>";
  3440. $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
  3441. __('Some feeds have update errors (click for details)')."</a>";
  3442. }
  3443. $reply['headlines']['content'] .= "</span></p>";
  3444. $reply['headlines-info'] = array("count" => 0,
  3445. "vgroup_last_feed" => '',
  3446. "unread" => 0,
  3447. "disable_cache" => true);
  3448. return $reply;
  3449. }
  3450. function save_email_address($link, $email) {
  3451. // FIXME: implement persistent storage of emails
  3452. if (!$_SESSION['stored_emails'])
  3453. $_SESSION['stored_emails'] = array();
  3454. if (!in_array($email, $_SESSION['stored_emails']))
  3455. array_push($_SESSION['stored_emails'], $email);
  3456. }
  3457. function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
  3458. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  3459. $sql_is_cat = bool_to_sql_bool($is_cat);
  3460. $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
  3461. WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
  3462. AND owner_uid = " . $owner_uid);
  3463. if (db_num_rows($result) == 1) {
  3464. $key = db_escape_string(sha1(uniqid(rand(), true)));
  3465. db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
  3466. WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
  3467. AND owner_uid = " . $owner_uid);
  3468. return $key;
  3469. } else {
  3470. return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
  3471. }
  3472. }
  3473. function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
  3474. if (!$owner_uid) $owner_uid = $_SESSION["uid"];
  3475. $sql_is_cat = bool_to_sql_bool($is_cat);
  3476. $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
  3477. WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
  3478. AND owner_uid = " . $owner_uid);
  3479. if (db_num_rows($result) == 1) {
  3480. return db_fetch_result($result, 0, "access_key");
  3481. } else {
  3482. $key = db_escape_string(sha1(uniqid(rand(), true)));
  3483. $result = db_query($link, "INSERT INTO ttrss_access_keys
  3484. (access_key, feed_id, is_cat, owner_uid)
  3485. VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
  3486. return $key;
  3487. }
  3488. return false;
  3489. }
  3490. /**
  3491. * Extracts RSS/Atom feed URLs from the given HTML URL.
  3492. *
  3493. * @param string $url HTML page URL
  3494. *
  3495. * @return array Array of feeds. Key is the full URL, value the title
  3496. */
  3497. function get_feeds_from_html($url, $login = false, $pass = false)
  3498. {
  3499. $url = fix_url($url);
  3500. $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
  3501. libxml_use_internal_errors(true);
  3502. $content = @fetch_file_contents($url, false, $login, $pass);
  3503. $doc = new DOMDocument();
  3504. $doc->loadHTML($content);
  3505. $xpath = new DOMXPath($doc);
  3506. $entries = $xpath->query('/html/head/link[@rel="alternate"]');
  3507. $feedUrls = array();
  3508. foreach ($entries as $entry) {
  3509. if ($entry->hasAttribute('href')) {
  3510. $title = $entry->getAttribute('title');
  3511. if ($title == '') {
  3512. $title = $entry->getAttribute('type');
  3513. }
  3514. $feedUrl = rewrite_relative_url(
  3515. $baseUrl, $entry->getAttribute('href')
  3516. );
  3517. $feedUrls[$feedUrl] = $title;
  3518. }
  3519. }
  3520. return $feedUrls;
  3521. }
  3522. /**
  3523. * Checks if the content behind the given URL is a HTML file
  3524. *
  3525. * @param string $url URL to check
  3526. *
  3527. * @return boolean True if the URL contains HTML content
  3528. */
  3529. function url_is_html($url, $login = false, $pass = false) {
  3530. $content = substr(fetch_file_contents($url, false, $login, $pass), 0, 1000);
  3531. if (stripos($content, '<html>') === false
  3532. && stripos($content, '<html ') === false
  3533. ) {
  3534. return false;
  3535. }
  3536. return true;
  3537. }
  3538. function print_label_select($link, $name, $value, $attributes = "") {
  3539. $result = db_query($link, "SELECT caption FROM ttrss_labels2
  3540. WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
  3541. print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
  3542. "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
  3543. while ($line = db_fetch_assoc($result)) {
  3544. $issel = ($line["caption"] == $value) ? "selected=\"1\"" : "";
  3545. print "<option value=\"".htmlspecialchars($line["caption"])."\"
  3546. $issel>" . htmlspecialchars($line["caption"]) . "</option>";
  3547. }
  3548. # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
  3549. print "</select>";
  3550. }
  3551. function format_article_enclosures($link, $id, $always_display_enclosures,
  3552. $article_content) {
  3553. $result = get_article_enclosures($link, $id);
  3554. $rv = '';
  3555. if (count($result) > 0) {
  3556. $entries_html = array();
  3557. $entries = array();
  3558. foreach ($result as $line) {
  3559. $url = $line["content_url"];
  3560. $ctype = $line["content_type"];
  3561. if (!$ctype) $ctype = __("unknown type");
  3562. $filename = substr($url, strrpos($url, "/")+1);
  3563. # $player = format_inline_player($link, $url, $ctype);
  3564. # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
  3565. # $filename . " (" . $ctype . ")" . "</a>";
  3566. $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
  3567. dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
  3568. array_push($entries_html, $entry);
  3569. $entry = array();
  3570. $entry["type"] = $ctype;
  3571. $entry["filename"] = $filename;
  3572. $entry["url"] = $url;
  3573. array_push($entries, $entry);
  3574. }
  3575. if (!get_pref($link, "STRIP_IMAGES")) {
  3576. if ($always_display_enclosures ||
  3577. !preg_match("/<img/i", $article_content)) {
  3578. foreach ($entries as $entry) {
  3579. if (preg_match("/image/", $entry["type"]) ||
  3580. preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
  3581. $rv .= "<p><img
  3582. alt=\"".htmlspecialchars($entry["filename"])."\"
  3583. src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
  3584. }
  3585. }
  3586. }
  3587. }
  3588. $rv .= "<div dojoType=\"dijit.form.DropDownButton\">".
  3589. "<span>" . __('Attachments')."</span>";
  3590. $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
  3591. foreach ($entries_html as $entry) { $rv .= $entry; };
  3592. $rv .= "</div></div>";
  3593. }
  3594. return $rv;
  3595. }
  3596. function getLastArticleId($link) {
  3597. $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
  3598. WHERE owner_uid = " . $_SESSION["uid"]);
  3599. if (db_num_rows($result) == 1) {
  3600. return db_fetch_result($result, 0, "id");
  3601. } else {
  3602. return -1;
  3603. }
  3604. }
  3605. function build_url($parts) {
  3606. return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
  3607. }
  3608. /**
  3609. * Converts a (possibly) relative URL to a absolute one.
  3610. *
  3611. * @param string $url Base URL (i.e. from where the document is)
  3612. * @param string $rel_url Possibly relative URL in the document
  3613. *
  3614. * @return string Absolute URL
  3615. */
  3616. function rewrite_relative_url($url, $rel_url) {
  3617. if (strpos($rel_url, "magnet:") === 0) {
  3618. return $rel_url;
  3619. } else if (strpos($rel_url, "://") !== false) {
  3620. return $rel_url;
  3621. } else if (strpos($rel_url, "//") === 0) {
  3622. # protocol-relative URL (rare but they exist)
  3623. return $rel_url;
  3624. } else if (strpos($rel_url, "/") === 0)
  3625. {
  3626. $parts = parse_url($url);
  3627. $parts['path'] = $rel_url;
  3628. return build_url($parts);
  3629. } else {
  3630. $parts = parse_url($url);
  3631. if (!isset($parts['path'])) {
  3632. $parts['path'] = '/';
  3633. }
  3634. $dir = $parts['path'];
  3635. if (substr($dir, -1) !== '/') {
  3636. $dir = dirname($parts['path']);
  3637. $dir !== '/' && $dir .= '/';
  3638. }
  3639. $parts['path'] = $dir . $rel_url;
  3640. return build_url($parts);
  3641. }
  3642. }
  3643. function sphinx_search($query, $offset = 0, $limit = 30) {
  3644. require_once 'lib/sphinxapi.php';
  3645. $sphinxClient = new SphinxClient();
  3646. $sphinxClient->SetServer('localhost', 9312);
  3647. $sphinxClient->SetConnectTimeout(1);
  3648. $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
  3649. 'feed_title' => 20));
  3650. $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2);
  3651. $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
  3652. $sphinxClient->SetLimits($offset, $limit, 1000);
  3653. $sphinxClient->SetArrayResult(false);
  3654. $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
  3655. $result = $sphinxClient->Query($query, SPHINX_INDEX);
  3656. $ids = array();
  3657. if (is_array($result['matches'])) {
  3658. foreach (array_keys($result['matches']) as $int_id) {
  3659. $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
  3660. array_push($ids, $ref_id);
  3661. }
  3662. }
  3663. return $ids;
  3664. }
  3665. function cleanup_tags($link, $days = 14, $limit = 1000) {
  3666. if (DB_TYPE == "pgsql") {
  3667. $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
  3668. } else if (DB_TYPE == "mysql") {
  3669. $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
  3670. }
  3671. $tags_deleted = 0;
  3672. while ($limit > 0) {
  3673. $limit_part = 500;
  3674. $query = "SELECT ttrss_tags.id AS id
  3675. FROM ttrss_tags, ttrss_user_entries, ttrss_entries
  3676. WHERE post_int_id = int_id AND $interval_query AND
  3677. ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
  3678. $result = db_query($link, $query);
  3679. $ids = array();
  3680. while ($line = db_fetch_assoc($result)) {
  3681. array_push($ids, $line['id']);
  3682. }
  3683. if (count($ids) > 0) {
  3684. $ids = join(",", $ids);
  3685. print ".";
  3686. $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
  3687. $tags_deleted += db_affected_rows($link, $tmp_result);
  3688. } else {
  3689. break;
  3690. }
  3691. $limit -= $limit_part;
  3692. }
  3693. print "\n";
  3694. return $tags_deleted;
  3695. }
  3696. function print_user_stylesheet($link) {
  3697. $value = get_pref($link, 'USER_STYLESHEET');
  3698. if ($value) {
  3699. print "<style type=\"text/css\">";
  3700. print str_replace("<br/>", "\n", $value);
  3701. print "</style>";
  3702. }
  3703. }
  3704. /* function rewrite_urls($line) {
  3705. global $url_regex;
  3706. $urls = null;
  3707. $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
  3708. "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
  3709. return $result;
  3710. } */
  3711. function rewrite_urls($html) {
  3712. libxml_use_internal_errors(true);
  3713. $charset_hack = '<head>
  3714. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  3715. </head>';
  3716. $doc = new DOMDocument();
  3717. $doc->loadHTML($charset_hack . $html);
  3718. $xpath = new DOMXPath($doc);
  3719. $entries = $xpath->query('//*/text()');
  3720. foreach ($entries as $entry) {
  3721. if (strstr($entry->wholeText, "://") !== false) {
  3722. $text = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
  3723. "<a target=\"_blank\" href=\"\\1\">\\1</a>", $entry->wholeText);
  3724. if ($text != $entry->wholeText) {
  3725. $cdoc = new DOMDocument();
  3726. $cdoc->loadHTML($charset_hack . $text);
  3727. foreach ($cdoc->childNodes as $cnode) {
  3728. $cnode = $doc->importNode($cnode, true);
  3729. if ($cnode) {
  3730. $entry->parentNode->insertBefore($cnode);
  3731. }
  3732. }
  3733. $entry->parentNode->removeChild($entry);
  3734. }
  3735. }
  3736. }
  3737. $node = $doc->getElementsByTagName('body')->item(0);
  3738. // http://tt-rss.org/forum/viewtopic.php?f=1&t=970
  3739. if ($node)
  3740. return $doc->saveXML($node, LIBXML_NOEMPTYTAG);
  3741. else
  3742. return $html;
  3743. }
  3744. function filter_to_sql($filter) {
  3745. $query = "";
  3746. $regexp_valid = preg_match('/' . $filter['reg_exp'] . '/',
  3747. $filter['reg_exp']) !== FALSE;
  3748. if ($regexp_valid) {
  3749. if (DB_TYPE == "pgsql")
  3750. $reg_qpart = "~";
  3751. else
  3752. $reg_qpart = "REGEXP";
  3753. switch ($filter["type"]) {
  3754. case "title":
  3755. $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
  3756. $filter['reg_exp'] . "')";
  3757. break;
  3758. case "content":
  3759. $query = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
  3760. $filter['reg_exp'] . "')";
  3761. break;
  3762. case "both":
  3763. $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
  3764. $filter['reg_exp'] . "') OR LOWER(" .
  3765. "ttrss_entries.content) $reg_qpart LOWER('" . $filter['reg_exp'] . "')";
  3766. break;
  3767. case "tag":
  3768. $query = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
  3769. $filter['reg_exp'] . "')";
  3770. break;
  3771. case "link":
  3772. $query = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
  3773. $filter['reg_exp'] . "')";
  3774. break;
  3775. case "date":
  3776. if ($filter["filter_param"] == "before")
  3777. $cmp_qpart = "<";
  3778. else
  3779. $cmp_qpart = ">=";
  3780. $timestamp = date("Y-m-d H:N:s", strtotime($filter["reg_exp"]));
  3781. $query = "ttrss_entries.date_entered $cmp_qpart '$timestamp'";
  3782. break;
  3783. case "author":
  3784. $query = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
  3785. $filter['reg_exp'] . "')";
  3786. break;
  3787. }
  3788. if ($filter["inverse"])
  3789. $query = "NOT ($query)";
  3790. if ($query) {
  3791. if (DB_TYPE == "pgsql") {
  3792. $query = " ($query) AND ttrss_entries.date_entered > NOW() - INTERVAL '14 days'";
  3793. } else {
  3794. $query = " ($query) AND ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL 14 DAY)";
  3795. }
  3796. $query .= " AND ";
  3797. }
  3798. return $query;
  3799. } else {
  3800. return false;
  3801. }
  3802. }
  3803. // Status codes:
  3804. // -1 - never connected
  3805. // 0 - no data received
  3806. // 1 - data received successfully
  3807. // 2 - did not receive valid data
  3808. // >10 - server error, code + 10 (e.g. 16 means server error 6)
  3809. function get_linked_feeds($link, $instance_id = false) {
  3810. if ($instance_id)
  3811. $instance_qpart = "id = '$instance_id' AND ";
  3812. else
  3813. $instance_qpart = "";
  3814. if (DB_TYPE == "pgsql") {
  3815. $date_qpart = "last_connected < NOW() - INTERVAL '6 hours'";
  3816. } else {
  3817. $date_qpart = "last_connected < DATE_SUB(NOW(), INTERVAL 6 HOUR)";
  3818. }
  3819. $result = db_query($link, "SELECT id, access_key, access_url FROM ttrss_linked_instances
  3820. WHERE $instance_qpart $date_qpart ORDER BY last_connected");
  3821. while ($line = db_fetch_assoc($result)) {
  3822. $id = $line['id'];
  3823. _debug("Updating: " . $line['access_url'] . " ($id)");
  3824. $fetch_url = $line['access_url'] . '/public.php?op=fbexport';
  3825. $post_query = 'key=' . $line['access_key'];
  3826. $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
  3827. // try doing it the old way
  3828. if (!$feeds) {
  3829. $fetch_url = $line['access_url'] . '/backend.php?op=fbexport';
  3830. $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
  3831. }
  3832. if ($feeds) {
  3833. $feeds = json_decode($feeds, true);
  3834. if ($feeds) {
  3835. if ($feeds['error']) {
  3836. $status = $feeds['error']['code'] + 10;
  3837. } else {
  3838. $status = 1;
  3839. if (count($feeds['feeds']) > 0) {
  3840. db_query($link, "DELETE FROM ttrss_linked_feeds
  3841. WHERE instance_id = '$id'");
  3842. foreach ($feeds['feeds'] as $feed) {
  3843. $feed_url = db_escape_string($feed['feed_url']);
  3844. $title = db_escape_string($feed['title']);
  3845. $subscribers = db_escape_string($feed['subscribers']);
  3846. $site_url = db_escape_string($feed['site_url']);
  3847. db_query($link, "INSERT INTO ttrss_linked_feeds
  3848. (feed_url, site_url, title, subscribers, instance_id, created, updated)
  3849. VALUES
  3850. ('$feed_url', '$site_url', '$title', '$subscribers', '$id', NOW(), NOW())");
  3851. }
  3852. } else {
  3853. // received 0 feeds, this might indicate that
  3854. // the instance on the other hand is rebuilding feedbrowser cache
  3855. // we will try again later
  3856. // TODO: maybe perform expiration based on updated here?
  3857. }
  3858. _debug("Processed " . count($feeds['feeds']) . " feeds.");
  3859. }
  3860. } else {
  3861. $status = 2;
  3862. }
  3863. } else {
  3864. $status = 0;
  3865. }
  3866. _debug("Status: $status");
  3867. db_query($link, "UPDATE ttrss_linked_instances SET
  3868. last_status_out = '$status', last_connected = NOW() WHERE id = '$id'");
  3869. }
  3870. }
  3871. function make_feed_browser($link, $search, $limit, $mode = 1) {
  3872. $owner_uid = $_SESSION["uid"];
  3873. $rv = '';
  3874. if ($search) {
  3875. $search_qpart = "AND (UPPER(feed_url) LIKE UPPER('%$search%') OR
  3876. UPPER(title) LIKE UPPER('%$search%'))";
  3877. } else {
  3878. $search_qpart = "";
  3879. }
  3880. if ($mode == 1) {
  3881. /* $result = db_query($link, "SELECT feed_url, subscribers FROM
  3882. ttrss_feedbrowser_cache WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
  3883. WHERE tf.feed_url = ttrss_feedbrowser_cache.feed_url
  3884. AND owner_uid = '$owner_uid') $search_qpart
  3885. ORDER BY subscribers DESC LIMIT $limit"); */
  3886. $result = db_query($link, "SELECT feed_url, site_url, title, SUM(subscribers) AS subscribers FROM
  3887. (SELECT feed_url, site_url, title, subscribers FROM ttrss_feedbrowser_cache UNION ALL
  3888. SELECT feed_url, site_url, title, subscribers FROM ttrss_linked_feeds) AS qqq
  3889. WHERE
  3890. (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
  3891. WHERE tf.feed_url = qqq.feed_url
  3892. AND owner_uid = '$owner_uid') $search_qpart
  3893. GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT $limit");
  3894. } else if ($mode == 2) {
  3895. $result = db_query($link, "SELECT *,
  3896. (SELECT COUNT(*) FROM ttrss_user_entries WHERE
  3897. orig_feed_id = ttrss_archived_feeds.id) AS articles_archived
  3898. FROM
  3899. ttrss_archived_feeds
  3900. WHERE
  3901. (SELECT COUNT(*) FROM ttrss_feeds
  3902. WHERE ttrss_feeds.feed_url = ttrss_archived_feeds.feed_url AND
  3903. owner_uid = '$owner_uid') = 0 AND
  3904. owner_uid = '$owner_uid' $search_qpart
  3905. ORDER BY id DESC LIMIT $limit");
  3906. }
  3907. $feedctr = 0;
  3908. while ($line = db_fetch_assoc($result)) {
  3909. if ($mode == 1) {
  3910. $feed_url = htmlspecialchars($line["feed_url"]);
  3911. $site_url = htmlspecialchars($line["site_url"]);
  3912. $subscribers = $line["subscribers"];
  3913. $check_box = "<input onclick='toggleSelectListRow2(this)'
  3914. dojoType=\"dijit.form.CheckBox\"
  3915. type=\"checkbox\" \">";
  3916. $class = ($feedctr % 2) ? "even" : "odd";
  3917. $site_url = "<a target=\"_blank\"
  3918. href=\"$site_url\">
  3919. <span class=\"fb_feedTitle\">".
  3920. htmlspecialchars($line["title"])."</span></a>";
  3921. $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
  3922. href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
  3923. style='vertical-align : middle'></a>";
  3924. $rv .= "<li>$check_box $feed_url $site_url".
  3925. "&nbsp;<span class='subscribers'>($subscribers)</span></li>";
  3926. } else if ($mode == 2) {
  3927. $feed_url = htmlspecialchars($line["feed_url"]);
  3928. $site_url = htmlspecialchars($line["site_url"]);
  3929. $title = htmlspecialchars($line["title"]);
  3930. $check_box = "<input onclick='toggleSelectListRow2(this)' dojoType=\"dijit.form.CheckBox\"
  3931. type=\"checkbox\">";
  3932. $class = ($feedctr % 2) ? "even" : "odd";
  3933. if ($line['articles_archived'] > 0) {
  3934. $archived = sprintf(__("%d archived articles"), $line['articles_archived']);
  3935. $archived = "&nbsp;<span class='subscribers'>($archived)</span>";
  3936. } else {
  3937. $archived = '';
  3938. }
  3939. $site_url = "<a target=\"_blank\"
  3940. href=\"$site_url\">
  3941. <span class=\"fb_feedTitle\">".
  3942. htmlspecialchars($line["title"])."</span></a>";
  3943. $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
  3944. href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
  3945. style='vertical-align : middle'></a>";
  3946. $rv .= "<li id=\"FBROW-".$line["id"]."\">".
  3947. "$check_box $feed_url $site_url $archived</li>";
  3948. }
  3949. ++$feedctr;
  3950. }
  3951. if ($feedctr == 0) {
  3952. $rv .= "<li style=\"text-align : center\"><p>".__('No feeds found.')."</p></li>";
  3953. }
  3954. return $rv;
  3955. }
  3956. if (!function_exists('gzdecode')) {
  3957. function gzdecode($string) { // no support for 2nd argument
  3958. return file_get_contents('compress.zlib://data:who/cares;base64,'.
  3959. base64_encode($string));
  3960. }
  3961. }
  3962. function perform_data_import($link, $filename, $owner_uid) {
  3963. $num_imported = 0;
  3964. $num_processed = 0;
  3965. $num_feeds_created = 0;
  3966. $doc = @DOMDocument::load($filename);
  3967. if (!$doc) {
  3968. $contents = file_get_contents($filename);
  3969. if ($contents) {
  3970. $data = @gzuncompress($contents);
  3971. }
  3972. if (!$data) {
  3973. $data = @gzdecode($contents);
  3974. }
  3975. if ($data)
  3976. $doc = DOMDocument::loadXML($data);
  3977. }
  3978. if ($doc) {
  3979. $xpath = new DOMXpath($doc);
  3980. $container = $doc->firstChild;
  3981. if ($container && $container->hasAttribute('schema-version')) {
  3982. $schema_version = $container->getAttribute('schema-version');
  3983. if ($schema_version != SCHEMA_VERSION) {
  3984. print "<p>" .__("Could not import: incorrect schema version.") . "</p>";
  3985. return;
  3986. }
  3987. } else {
  3988. print "<p>" . __("Could not import: unrecognized document format.") . "</p>";
  3989. return;
  3990. }
  3991. $articles = $xpath->query("//article");
  3992. foreach ($articles as $article_node) {
  3993. if ($article_node->childNodes) {
  3994. $ref_id = 0;
  3995. $article = array();
  3996. foreach ($article_node->childNodes as $child) {
  3997. if ($child->nodeName != 'label_cache')
  3998. $article[$child->nodeName] = db_escape_string($child->nodeValue);
  3999. else
  4000. $article[$child->nodeName] = $child->nodeValue;
  4001. }
  4002. //print_r($article);
  4003. if ($article['guid']) {
  4004. ++$num_processed;
  4005. //db_query($link, "BEGIN");
  4006. //print 'GUID:' . $article['guid'] . "\n";
  4007. $result = db_query($link, "SELECT id FROM ttrss_entries
  4008. WHERE guid = '".$article['guid']."'");
  4009. if (db_num_rows($result) == 0) {
  4010. $result = db_query($link,
  4011. "INSERT INTO ttrss_entries
  4012. (title,
  4013. guid,
  4014. link,
  4015. updated,
  4016. content,
  4017. content_hash,
  4018. no_orig_date,
  4019. date_updated,
  4020. date_entered,
  4021. comments,
  4022. num_comments,
  4023. author)
  4024. VALUES
  4025. ('".$article['title']."',
  4026. '".$article['guid']."',
  4027. '".$article['link']."',
  4028. '".$article['updated']."',
  4029. '".$article['content']."',
  4030. '".sha1($article['content'])."',
  4031. false,
  4032. NOW(),
  4033. NOW(),
  4034. '',
  4035. '0',
  4036. '')");
  4037. $result = db_query($link, "SELECT id FROM ttrss_entries
  4038. WHERE guid = '".$article['guid']."'");
  4039. if (db_num_rows($result) != 0) {
  4040. $ref_id = db_fetch_result($result, 0, "id");
  4041. }
  4042. } else {
  4043. $ref_id = db_fetch_result($result, 0, "id");
  4044. }
  4045. //print "Got ref ID: $ref_id\n";
  4046. if ($ref_id) {
  4047. $feed_url = $article['feed_url'];
  4048. $feed_title = $article['feed_title'];
  4049. $feed = 'NULL';
  4050. if ($feed_url && $feed_title) {
  4051. $result = db_query($link, "SELECT id FROM ttrss_feeds
  4052. WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
  4053. if (db_num_rows($result) != 0) {
  4054. $feed = db_fetch_result($result, 0, "id");
  4055. } else {
  4056. // try autocreating feed in Uncategorized...
  4057. $result = db_query($link, "INSERT INTO ttrss_feeds (owner_uid,
  4058. feed_url, title) VALUES ($owner_uid, '$feed_url', '$feed_title')");
  4059. $result = db_query($link, "SELECT id FROM ttrss_feeds
  4060. WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
  4061. if (db_num_rows($result) != 0) {
  4062. ++$num_feeds_created;
  4063. $feed = db_fetch_result($result, 0, "id");
  4064. }
  4065. }
  4066. }
  4067. if ($feed != 'NULL')
  4068. $feed_qpart = "feed_id = $feed";
  4069. else
  4070. $feed_qpart = "feed_id IS NULL";
  4071. //print "$ref_id / $feed / " . $article['title'] . "\n";
  4072. $result = db_query($link, "SELECT int_id FROM ttrss_user_entries
  4073. WHERE ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND $feed_qpart");
  4074. if (db_num_rows($result) == 0) {
  4075. $marked = bool_to_sql_bool(sql_bool_to_bool($article['marked']));
  4076. $published = bool_to_sql_bool(sql_bool_to_bool($article['published']));
  4077. $score = (int) $article['score'];
  4078. $tag_cache = $article['tag_cache'];
  4079. $label_cache = db_escape_string($article['label_cache']);
  4080. $note = $article['note'];
  4081. //print "Importing " . $article['title'] . "<br/>";
  4082. ++$num_imported;
  4083. $result = db_query($link,
  4084. "INSERT INTO ttrss_user_entries
  4085. (ref_id, owner_uid, feed_id, unread, last_read, marked,
  4086. published, score, tag_cache, label_cache, uuid, note)
  4087. VALUES ($ref_id, $owner_uid, $feed, false,
  4088. NULL, $marked, $published, $score, '$tag_cache',
  4089. '$label_cache', '', '$note')");
  4090. $label_cache = json_decode($label_cache, true);
  4091. if (is_array($label_cache) && $label_cache["no-labels"] != 1) {
  4092. foreach ($label_cache as $label) {
  4093. label_create($link, $label[1],
  4094. $label[2], $label[3], $owner_uid);
  4095. label_add_article($link, $ref_id, $label[1], $owner_uid);
  4096. }
  4097. }
  4098. //db_query($link, "COMMIT");
  4099. }
  4100. }
  4101. }
  4102. }
  4103. }
  4104. print "<p>" .
  4105. T_sprintf("Finished: %d articles processed, %d imported, %d feeds created.",
  4106. $num_processed, $num_imported, $num_feeds_created) .
  4107. "</p>";
  4108. } else {
  4109. print "<p>" . __("Could not load XML document.") . "</p>";
  4110. }
  4111. }
  4112. function get_random_bytes($length) {
  4113. if (function_exists('openssl_random_pseudo_bytes')) {
  4114. return openssl_random_pseudo_bytes($length);
  4115. } else {
  4116. $output = "";
  4117. for ($i = 0; $i < $length; $i++)
  4118. $output .= chr(mt_rand(0, 255));
  4119. return $output;
  4120. }
  4121. }
  4122. function read_stdin() {
  4123. $fp = fopen("php://stdin", "r");
  4124. if ($fp) {
  4125. $line = trim(fgets($fp));
  4126. fclose($fp);
  4127. return $line;
  4128. }
  4129. return null;
  4130. }
  4131. ?>