pla.php 240 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165
  1. <?php
  2. //
  3. // Project: phpLiteAdmin (https://www.phpliteadmin.org/)
  4. // Version: 1.9.8.2
  5. // Summary: PHP-based admin tool to manage SQLite2 and SQLite3 databases on the web
  6. // Last updated: 2019-09-05
  7. // Developers:
  8. // Dane Iracleous (daneiracleous@gmail.com)
  9. // Ian Aldrighetti (ian.aldrighetti@gmail.com)
  10. // George Flanagin & Digital Gaslight, Inc (george@digitalgaslight.com)
  11. // Christopher Kramer (crazy4chrissi@gmail.com, http://en.christosoft.de)
  12. // Ayman Teryaki (http://havalite.com)
  13. // Dreadnaut (dreadnaut@gmail.com, http://dreadnaut.altervista.org)
  14. //
  15. //
  16. // Copyright (C) 2019, phpLiteAdmin
  17. //
  18. // This program is free software: you can redistribute it and/or modify
  19. // it under the terms of the GNU General Public License as published by
  20. // the Free Software Foundation, either version 3 of the License, or
  21. // (at your option) any later version.
  22. //
  23. // This program is distributed in the hope that it will be useful,
  24. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. // GNU General Public License for more details.
  27. //
  28. // You should have received a copy of the GNU General Public License
  29. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  30. //
  31. // ////////////////////////////////////////////////////////////////////////
  32. //
  33. // Please report any bugs you may encounter to our issue tracker here:
  34. // https://bitbucket.org/phpliteadmin/public/issues?status=new&status=open
  35. //
  36. // This is sample configuration file
  37. //
  38. // You can configure phpliteadmin in one of 2 ways:
  39. // 1. Rename phpliteadmin.config.sample.php to phpliteadmin.config.php and change parameters in there.
  40. // You can set only your custom settings in phpliteadmin.config.php. All other settings will be set to defaults.
  41. // 2. Change parameters directly in main phpliteadmin.php file
  42. //
  43. // Please see https://bitbucket.org/phpliteadmin/public/wiki/Configuration for more details
  44. //password to gain access
  45. $password = 'admin';
  46. //directory relative to this file to search for databases (if false, manually list databases in the $databases variable)
  47. $directory = '../../tmp/appdata/palicanon';
  48. //whether or not to scan the subdirectories of the above directory infinitely deep
  49. $subdirectories = false;
  50. //if the above $directory variable is set to false, you must specify the databases manually in an array as the next variable
  51. //if any of the databases do not exist as they are referenced by their path, they will be created automatically
  52. $databases = array(
  53. array(
  54. 'path'=> 'database1.sqlite',
  55. 'name'=> 'Database 1'
  56. ),
  57. array(
  58. 'path'=> 'database2.sqlite',
  59. 'name'=> 'Database 2'
  60. ),
  61. );
  62. /* ---- Interface settings ---- */
  63. // Theme! If you want to change theme, save the CSS file in same folder of phpliteadmin or in folder "themes"
  64. $theme = 'phpliteadmin.css';
  65. // the default language! If you want to change it, save the language file in same folder of phpliteadmin or in folder "languages"
  66. // More about localizations (downloads, how to translate etc.): https://bitbucket.org/phpliteadmin/public/wiki/Localization
  67. $language = 'en';
  68. // set default number of rows. You need to relog after changing the number
  69. $rowsNum = 30;
  70. // reduce string characters by a number bigger than 10
  71. $charsNum = 300;
  72. // maximum number of SQL queries to save in the history
  73. $maxSavedQueries = 10;
  74. /* ---- Custom functions ---- */
  75. //a list of custom functions that can be applied to columns in the databases
  76. //make sure to define every function below if it is not a core PHP function
  77. $custom_functions = array(
  78. 'md5', 'sha1', 'time', 'strtotime',
  79. // add the names of your custom functions to this array
  80. /* 'leet_text', */
  81. );
  82. // define your custom functions here
  83. /*
  84. function leet_text($value)
  85. {
  86. return strtr($value, 'eaAsSOl', '344zZ01');
  87. }
  88. */
  89. /* ---- Advanced options ---- */
  90. //changing the following variable allows multiple phpLiteAdmin installs to work under the same domain.
  91. $cookie_name = 'pla3412';
  92. //whether or not to put the app in debug mode where errors are outputted
  93. $debug = false;
  94. // the user is allowed to create databases with only these extensions
  95. $allowed_extensions = array('db','db3','sqlite','sqlite3');
  96. // English language-texts.
  97. // Read our wiki on how to translate: https://bitbucket.org/phpliteadmin/public/wiki/Localization
  98. $lang = array(
  99. "direction" => "LTR",
  100. "date_format" => 'g:ia \o\n F j, Y (T)', // see http://php.net/manual/en/function.date.php for what the letters stand for
  101. "ver" => "version",
  102. "for" => "for",
  103. "to" => "to",
  104. "go" => "Go",
  105. "yes" => "Yes",
  106. "no" => "No",
  107. "sql" => "SQL",
  108. "csv" => "CSV",
  109. "csv_tbl" => "Table that CSV pertains to",
  110. "srch" => "Search",
  111. "srch_again" => "Do Another Search",
  112. "login" => "Log In",
  113. "logout" => "Logout",
  114. "view" => "View", // here, the noun SQL view is meant, not the verb "to view"
  115. "confirm" => "Confirm",
  116. "cancel" => "Cancel",
  117. "save_as" => "Save As",
  118. "options" => "Options",
  119. "no_opt" => "No options",
  120. "help" => "Help",
  121. "installed" => "installed",
  122. "not_installed" => "not installed",
  123. "done" => "done",
  124. "insert" => "Insert",
  125. "export" => "Export",
  126. "import" => "Import",
  127. "rename" => "Rename",
  128. "empty" => "Empty",
  129. "drop" => "Drop",
  130. "tbl" => "Table",
  131. "chart" => "Chart",
  132. "err" => "ERROR",
  133. "act" => "Action",
  134. "rec" => "Records",
  135. "col" => "Column",
  136. "cols" => "Columns",
  137. "rows" => "row(s)",
  138. "edit" => "Edit",
  139. "del" => "Delete",
  140. "add" => "Add",
  141. "backup" => "Backup database file",
  142. "before" => "Before",
  143. "after" => "After",
  144. "passwd" => "Password",
  145. "passwd_incorrect" => "Incorrect password.",
  146. "chk_ext" => "Checking supported SQLite PHP extensions",
  147. "autoincrement" => "Autoincrement",
  148. "not_null" => "Not NULL",
  149. "attention" => "Attention",
  150. "none" => "None",
  151. "as_defined" => "As defined",
  152. "expression" => "Expression",
  153. "download" => "Download",
  154. "open_in_browser" => "Open in browser",
  155. "sqlite_ext" => "SQLite extension",
  156. "sqlite_ext_support" => "It appears that none of the supported SQLite library extensions are available in your installation of PHP. You may not use %s until you install at least one of them.",
  157. "sqlite_v" => "SQLite version",
  158. "sqlite_v_error" => "It appears that your database is of SQLite version %s but your installation of PHP does not contain the necessary extensions to handle this version. To fix the problem, either delete the database and allow %s to create it automatically or recreate it manually as SQLite version %s.",
  159. "report_issue" => "The problem cannot be diagnosed properly. Please file an issue report at",
  160. "sqlite_limit" => "Due to the limitations of SQLite, only the field name and data type can be modified.",
  161. "php_v" => "PHP version",
  162. "new_version" => "There is a new version!",
  163. "db_dump" => "database dump",
  164. "db_f" => "database file",
  165. "db_ch" => "Change Database",
  166. "db_event" => "Database Event",
  167. "db_name" => "Database name",
  168. "db_rename" => "Rename Database",
  169. "db_renamed" => "Database '%s' has been renamed to",
  170. "db_del" => "Delete Database",
  171. "db_path" => "Path to database",
  172. "db_size" => "Size of database",
  173. "db_mod" => "Database last modified",
  174. "db_create" => "Create New Database",
  175. "db_vac" => "The database, '%s', has been VACUUMed.",
  176. "db_not_writeable" => "The database, '%s', does not exist and cannot be created because the containing directory, '%s', is not writable. The application is unusable until you make it writable.",
  177. "db_setup" => "There was a problem setting up your database, %s. An attempt will be made to find out what's going on so you can fix the problem more easily",
  178. "db_exists" => "A database, other file or directory of the name '%s' already exists.",
  179. "db_blank" => "The database name cannot be blank.",
  180. "exported" => "Exported",
  181. "struct" => "Structure",
  182. "struct_for" => "structure for",
  183. "on_tbl" => "on table",
  184. "data_dump" => "Data dump for",
  185. "backup_hint" => "Hint: To backup your database, the easiest way is to %s.",
  186. "backup_hint_linktext" => "download the database-file",
  187. "total_rows" => "a total of %s rows",
  188. "total" => "Total",
  189. "not_dir" => "The directory you specified to scan for databases does not exist or is not a directory.",
  190. "bad_php_directive" => "It appears that the PHP directive, 'register_globals' is enabled. This is bad. You need to disable it before continuing.",
  191. "page_gen" => "Page generated in %s seconds.",
  192. "powered" => "Powered by",
  193. "free_software" => "This is free software.",
  194. "please_donate" => "Please donate.",
  195. "remember" => "Remember me",
  196. "no_db" => "Welcome to %s. It appears that you have selected to scan a directory for databases to manage. However, %s could not find any valid SQLite databases. You may use the form below to create your first database.",
  197. "no_db2" => "The directory you specified does not contain any existing databases to manage, and the directory is not writable. This means you can't create any new databases using %s. Either make the directory writable or manually upload databases to the directory.",
  198. "dir_not_executable" => "The directory you specified cannot be scanned for databases as %s has no execute permissions on it. On Linux, use 'chmod +x %s' to fix this.",
  199. "create" => "Create",
  200. "created" => "has been created",
  201. "create_tbl" => "Create new table",
  202. "create_tbl_db" => "Create new table on database",
  203. "create_trigger" => "Creating new trigger on table",
  204. "create_index" => "Creating new index on table",
  205. "create_index1" => "Create Index",
  206. "create_view" => "Create new view on database",
  207. "trigger" => "Trigger",
  208. "triggers" => "Triggers",
  209. "trigger_name" => "Trigger name",
  210. "trigger_act" => "Trigger Action",
  211. "trigger_step" => "Trigger Steps (semicolon terminated)",
  212. "when_exp" => "WHEN expression (type expression without 'WHEN')",
  213. "index" => "Index",
  214. "indexes" => "Indexes",
  215. "index_name" => "Index name",
  216. "name" => "Name",
  217. "unique" => "Unique",
  218. "seq_no" => "Seq. No.",
  219. "emptied" => "has been emptied",
  220. "dropped" => "has been dropped",
  221. "renamed" => "has been renamed to",
  222. "altered" => "has been altered successfully",
  223. "inserted" => "inserted",
  224. "deleted" => "deleted",
  225. "affected" => "affected",
  226. "blank_index" => "Index name must not be blank.",
  227. "one_index" => "You must specify at least one index column.",
  228. "docu" => "Documentation",
  229. "license" => "License",
  230. "proj_site" => "Project Site",
  231. "bug_report" => "This may be a bug that needs to be reported at",
  232. "return" => "Return",
  233. "browse" => "Browse",
  234. "fld" => "Field",
  235. "fld_num" => "Number of Fields",
  236. "fields" => "Fields",
  237. "type" => "Type",
  238. "operator" => "Operator",
  239. "val" => "Value",
  240. "update" => "Update",
  241. "comments" => "Comments",
  242. "specify_fields" => "You must specify the number of table fields.",
  243. "specify_tbl" => "You must specify a table name.",
  244. "specify_col" => "You must specify a column.",
  245. "tbl_exists" => "Table of the same name already exists.",
  246. "show" => "Show",
  247. "show_rows" => "Showing %s row(s). ",
  248. "showing" => "Showing",
  249. "showing_rows" => "Showing rows",
  250. "query_time" => "(Query took %s sec)",
  251. "syntax_err" => "There is a problem with the syntax of your query (Query was not executed)",
  252. "run_sql" => "Run SQL query/queries on database '%s'",
  253. "recent_queries" => "Recent Queries",
  254. "full_texts" => "Show full texts",
  255. "no_full_texts" => "Shorten long texts",
  256. "ques_empty" => "Are you sure you want to empty the table '%s'?",
  257. "ques_drop" => "Are you sure you want to drop the table '%s'?",
  258. "ques_drop_view" => "Are you sure you want to drop the view '%s'?",
  259. "ques_del_rows" => "Are you sure you want to delete row(s) %s from table '%s'?",
  260. "ques_del_db" => "Are you sure you want to delete the database '%s'?",
  261. "ques_column_delete" => "Are you sure you want to delete column(s) %s from table '%s'?",
  262. "ques_del_index" => "Are you sure you want to delete index '%s'?",
  263. "ques_del_trigger" => "Are you sure you want to delete trigger '%s'?",
  264. "ques_primarykey_add" => "Are you sure you want to add a primary key for the column(s) %s in table '%s'?",
  265. "export_struct" => "Export with structure",
  266. "export_data" => "Export with data",
  267. "add_drop" => "Add DROP TABLE",
  268. "add_transact" => "Add TRANSACTION",
  269. "fld_terminated" => "Fields terminated by",
  270. "fld_enclosed" => "Fields enclosed by",
  271. "fld_escaped" => "Fields escaped by",
  272. "fld_names" => "Field names in first row",
  273. "rep_null" => "Replace NULL by",
  274. "rem_crlf" => "Remove CRLF characters within fields",
  275. "put_fld" => "Put field names in first row",
  276. "null_represent" => "NULL represented by",
  277. "import_suc" => "Import was successful.",
  278. "import_into" => "Import into",
  279. "import_f" => "File to import",
  280. "max_file_size" => "Maximum file size",
  281. "rename_tbl" => "Rename table '%s' to",
  282. "rows_records" => "row(s) starting from record # ",
  283. "rows_aff" => "row(s) affected. ",
  284. "as_a" => "as a",
  285. "readonly_tbl" => "'%s' is a view, which means it is a SELECT statement treated as a read-only table. You may not edit or insert records.",
  286. "chk_all" => "Check All",
  287. "unchk_all" => "Uncheck All",
  288. "with_sel" => "With Selected",
  289. "no_tbl" => "No table in database.",
  290. "no_chart" => "If you can read this, it means the chart could not be generated. The data you are trying to view may not be appropriate for a chart.",
  291. "no_rows" => "There are no rows in the table for the range you selected.",
  292. "no_sel" => "You did not select anything.",
  293. "chart_type" => "Chart Type",
  294. "chart_bar" => "Bar Chart",
  295. "chart_pie" => "Pie Chart",
  296. "chart_line" => "Line Chart",
  297. "lbl" => "Labels",
  298. "empty_tbl" => "This table is empty.",
  299. "click" => "Click here",
  300. "insert_rows" => "to insert rows.",
  301. "restart_insert" => "Restart insertion with ",
  302. "ignore" => "Ignore",
  303. "func" => "Function",
  304. "new_insert" => "Insert As New Row",
  305. "save_ch" => "Save Changes",
  306. "def_val" => "Default Value",
  307. "prim_key" => "Primary Key",
  308. "tbl_end" => "field(s) at end of table",
  309. "query_used_table" => "Query used to create this table",
  310. "query_used_view" => "Query used to create this view",
  311. "create_index2" => "Create an index on",
  312. "create_trigger2" => "Create a new trigger",
  313. "new_fld" => "Adding new field(s) to table '%s'",
  314. "add_flds" => "Add Fields",
  315. "edit_col" => "Editing column '%s'",
  316. "vac" => "Vacuum",
  317. "vac_desc" => "Large databases sometimes need to be VACUUMed to reduce their footprint on the server. Click the button below to VACUUM the database '%s'.",
  318. "vac_on_empty"=>"Rebuild database file to recover unused space (Vacuum)",
  319. "event" => "Event",
  320. "each_row" => "For Each Row",
  321. "define_index" => "Define index properties",
  322. "dup_val" => "Duplicate values",
  323. "allow" => "Allowed",
  324. "not_allow" => "Not Allowed",
  325. "asc" => "Ascending",
  326. "desc" => "Descending",
  327. "warn0" => "You have been warned.",
  328. "warn_passwd" => "You are using the default password, which can be dangerous. You can change it easily at the top of %s.",
  329. "counting_skipped" => "Counting of records has been skipped for some tables because your database is comparably big and some tables don't have primary keys assigned to them so counting might be slow. Add a primary key to these tables or %sforce counting%s.",
  330. "sel_state" => "Select Statement",
  331. "delimit" => "Delimiter",
  332. "back_top" => "Back to Top",
  333. "choose_f" => "Choose File",
  334. "instead" => "Instead of",
  335. "define_in_col" => "Define index column(s)",
  336. "delete_only_managed" => "You can only delete databases managed by this tool!",
  337. "rename_only_managed" => "You can only rename databases managed by this tool!",
  338. "db_moved_outside" => "You either tried to move the database into a directory where it cannot be managed anylonger, or the check if you did this failed because of missing rights.",
  339. "extension_not_allowed" => "The extension you provided is not within the list of allowed extensions. Please use one of the following extensions",
  340. "add_allowed_extension" => "You can add extensions to this list by adding your extension to \$allowed_extensions in the configuration.",
  341. "database_not_writable" => "The database-file is not writable, so its content cannot be changed in any way.",
  342. "directory_not_writable" => "The database-file itself is writable, but to write into it, the containing directory needs to be writable as well. This is because SQLite puts temporary files in there for locking.",
  343. "tbl_inexistent" => "Table %s does not exist",
  344. "col_inexistent" => "Column %s does not exist",
  345. // errors that can happen when ALTER TABLE fails. You don't necessarily have to translate these.
  346. "alter_failed" => "Altering of Table %s failed",
  347. "alter_tbl_name_not_replacable" => "could not replace the table name with the temporary one",
  348. "alter_no_def" => "no ALTER definition",
  349. "alter_parse_failed" =>"failed to parse ALTER definition",
  350. "alter_action_not_recognized" => "ALTER action could not be recognized",
  351. "alter_no_add_col" => "no column to add detected in ALTER statement",
  352. "alter_pattern_mismatch"=>"Pattern did not match on your original CREATE TABLE statement",
  353. "alter_col_not_recognized" => "could not recognize new or old column name",
  354. "alter_unknown_operation" => "Unknown ALTER operation!",
  355. /* Help documentation */
  356. "help_doc" => "Help Documentation",
  357. "help1" => "SQLite Library Extensions",
  358. "help1_x" => "%s uses PHP library extensions that allow interaction with SQLite databases. Currently, %s supports PDO, SQLite3, and SQLiteDatabase. Both PDO and SQLite3 deal with version 3 of SQLite, while SQLiteDatabase deals with version 2. So, if your PHP installation includes more than one SQLite library extension, PDO and SQLite3 will take precedence to make use of the better technology. However, if you have existing databases that are of version 2 of SQLite, %s will be forced to use SQLiteDatabase for only those databases. Not all databases need to be of the same version. During the database creation, however, the most advanced extension will be used.",
  359. "help2" => "Creating a New Database",
  360. "help2_x" => "When you create a new database, the name you entered will be appended with the appropriate file extension (.db, .db3, .sqlite, etc.) if you do not include it yourself. The database will be created in the directory you specified as the \$directory variable.",
  361. "help3" => "Tables vs. Views",
  362. "help3_x" => "On the main database page, there is a list of tables and views. Since views are read-only, certain operations will be disabled. These disabled operations will be apparent by their omission in the location where they should appear on the row for a view. If you want to change the data for a view, you need to drop that view and create a new view with the appropriate SELECT statement that queries other existing tables. For more information, see <a href='http://en.wikipedia.org/wiki/View_(database)' target='_blank'>http://en.wikipedia.org/wiki/View_(database)</a>",
  363. "help4" => "Writing a Select Statement for a New View",
  364. "help4_x" => "When you create a new view, you must write an SQL SELECT statement that it will use as its data. A view is simply a read-only table that can be accessed and queried like a regular table, except it cannot be modified through insertion, column editing, or row editing. It is only used for conveniently fetching data.",
  365. "help5" => "Export Structure to SQL File",
  366. "help5_x" => "During the process for exporting to an SQL file, you may choose to include the queries that create the table and columns.",
  367. "help6" => "Export Data to SQL File",
  368. "help6_x" => "During the process for exporting to an SQL file, you may choose to include the queries that populate the table(s) with the current records of the table(s).",
  369. "help7" => "Add Drop Table to Exported SQL File",
  370. "help7_x" => "During the process for exporting to an SQL file, you may choose to include queries to DROP the existing tables before adding them so that problems do not occur when trying to create tables that already exist.",
  371. "help8" => "Add Transaction to Exported SQL File",
  372. "help8_x" => "During the process for exporting to an SQL file, you may choose to wrap the queries around a TRANSACTION so that if an error occurs at any time during the importation process using the exported file, the database can be reverted to its previous state, preventing partially updated data from populating the database.",
  373. "help9" => "Add Comments to Exported SQL File",
  374. "help9_x" => "During the process for exporting to an SQL file, you may choose to include comments that explain each step of the process so that a human can better understand what is happening.",
  375. "help10" => "Partial Indexes",
  376. "help10_x" => "Partial indexes are indexes over a subset of the rows of a table specified by a WHERE clause. Note this requires at least SQLite 3.8.0 and database files with partial indexes won't be readable or writable by older versions. See the <a href='https://www.sqlite.org/partialindex.html' target='_blank'>SQLite documentation.</a>",
  377. "help11" => "Maximum size of file uploads",
  378. "help11_x" => "The maximum size of file uploads is determined by three PHP settings: <em>upload_max_filesize</em>, <em>post_max_size</em> and <em>memory_limit</em>. The smallest of these three limits the maximum size for file uploads. To upload larger files, adjust these values in your <em>php.ini</em> file."
  379. );
  380. //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  381. //there is no reason for the average user to edit anything below this comment
  382. //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  383. //- Initialization
  384. // load optional configuration file
  385. $config_filename = './config.php';
  386. if (is_readable($config_filename))
  387. {
  388. include_once $config_filename;
  389. }
  390. //constants 1
  391. define("PROJECT", "phpLiteAdmin");
  392. define("VERSION", "1.9.8.2");
  393. define("FORCETYPE", false); //force the extension that will be used (set to false in almost all circumstances except debugging)
  394. define("SYSTEMPASSWORD", $password); // Makes things easier.
  395. define('PROJECT_URL','https://www.phpliteadmin.org/');
  396. define('DONATE_URL','https://www.phpliteadmin.org/donate/');
  397. define('VERSION_CHECK_URL','https://www.phpliteadmin.org/current_version.php');
  398. define('PROJECT_BUGTRACKER_LINK','<a href="https://bitbucket.org/phpliteadmin/public/issues?status=new&status=open" target="_blank">https://bitbucket.org/phpliteadmin/public/issues?status=new&status=open</a>');
  399. define('PROJECT_INSTALL_LINK','<a href="https://bitbucket.org/phpliteadmin/public/wiki/Installation" target="_blank">https://bitbucket.org/phpliteadmin/public/wiki/Installation</a>');
  400. class MicroTimer {
  401. private $startTime, $stopTime;
  402. // creates and starts a timer
  403. function __construct()
  404. {
  405. $this->startTime = microtime(true);
  406. }
  407. // stops a timer
  408. public function stop()
  409. {
  410. $this->stopTime = microtime(true);
  411. }
  412. // returns the number of seconds from the timer's creation, or elapsed
  413. // between creation and call to ->stop()
  414. public function elapsed()
  415. {
  416. if ($this->stopTime)
  417. return round($this->stopTime - $this->startTime, 4);
  418. return round(microtime(true) - $this->startTime, 4);
  419. }
  420. // called when using a MicroTimer object as a string
  421. public function __toString()
  422. {
  423. return (string) $this->elapsed();
  424. }
  425. }
  426. // class Resources (issue #157)
  427. // outputs secondary files, such as css and javascript
  428. // data is stored gzipped (gzencode) and encoded (base64_encode)
  429. //
  430. // up here, we don't output anything. debug output might appear here which is catched by ob and thrown later
  431. ob_start();
  432. // Resource output (css and javascript files)
  433. // we get out of the main code as soon as possible, without inizializing the session
  434. if (isset($_GET['resource']))
  435. {
  436. Resources::output($_GET['resource']);
  437. exit();
  438. }
  439. // don't mess with this - required for the login session
  440. ini_set('session.cookie_httponly', '1');
  441. session_start();
  442. // version-number added so after updating, old session-data is not used anylonger
  443. // cookies names cannot contain symbols, except underscores
  444. define("COOKIENAME", preg_replace('/[^a-zA-Z0-9_]/', '_', $cookie_name . '_' . VERSION) );
  445. $params = new GetParameters();
  446. if($debug==true)
  447. {
  448. ini_set("display_errors", 1);
  449. error_reporting(E_STRICT | E_ALL);
  450. } else
  451. {
  452. @ini_set("display_errors", 0);
  453. }
  454. // start the timer to record page load time
  455. $pageTimer = new MicroTimer();
  456. // load language file
  457. if($language != 'en') {
  458. $temp_lang=$lang;
  459. if(is_file('languages/lang_'.$language.'.php'))
  460. include('languages/lang_'.$language.'.php');
  461. elseif(is_file('lang_'.$language.'.php'))
  462. include('lang_'.$language.'.php');
  463. $lang = array_merge($temp_lang, $lang);
  464. unset($temp_lang);
  465. }
  466. //data types array
  467. $sqlite_datatypes = array("INTEGER", "REAL", "TEXT", "BLOB","NUMERIC","BOOLEAN","DATETIME");
  468. //available SQLite functions array (don't add anything here or there will be problems)
  469. $sqlite_functions = array("abs", "hex", "length", "lower", "ltrim", "random", "round", "rtrim", "trim", "typeof", "upper");
  470. //- Support functions
  471. // for php < 5.6.0
  472. if(!function_exists('hash_equals'))
  473. {
  474. function hash_equals($str1, $str2)
  475. {
  476. if(strlen($str1) != strlen($str2))
  477. return false;
  478. else {
  479. $res = $str1 ^ $str2;
  480. $ret = 0;
  481. for($i = strlen($res) - 1; $i >= 0; $i--)
  482. $ret |= ord($res[$i]);
  483. return !$ret;
  484. }
  485. }
  486. }
  487. //function that allows SQL delimiter to be ignored inside comments or strings
  488. function explode_sql($delimiter, $sql)
  489. {
  490. $ign = array('"' => '"', "'" => "'", "/*" => "*/", "--" => "\n"); // Ignore sequences.
  491. $out = array();
  492. $last = 0;
  493. $slen = strlen($sql);
  494. $dlen = strlen($delimiter);
  495. $i = 0;
  496. while($i < $slen)
  497. {
  498. // Split on delimiter
  499. if($slen - $i >= $dlen && substr($sql, $i, $dlen) == $delimiter)
  500. {
  501. array_push($out, substr($sql, $last, $i - $last));
  502. $last = $i + $dlen;
  503. $i += $dlen;
  504. continue;
  505. }
  506. // Eat comments and string literals
  507. foreach($ign as $start => $end)
  508. {
  509. $ilen = strlen($start);
  510. if($slen - $i >= $ilen && substr($sql, $i, $ilen) == $start)
  511. {
  512. $i+=strlen($start);
  513. $elen = strlen($end);
  514. while($i < $slen)
  515. {
  516. if($slen - $i >= $elen && substr($sql, $i, $elen) == $end)
  517. {
  518. // SQL comment characters can be escaped by doubling the character. This recognizes and skips those.
  519. if($start == $end && $slen - $i >= $elen*2 && substr($sql, $i, $elen*2) == $end.$end)
  520. {
  521. $i += $elen * 2;
  522. continue;
  523. }
  524. else
  525. {
  526. $i += $elen;
  527. continue 3;
  528. }
  529. }
  530. $i++;
  531. }
  532. continue 2;
  533. }
  534. }
  535. $i++;
  536. }
  537. if($last < $slen)
  538. array_push($out, substr($sql, $last, $slen - $last));
  539. return $out;
  540. }
  541. //function to scan entire directory tree and subdirectories
  542. function dir_tree($dir)
  543. {
  544. $path = array();
  545. $stack = array($dir);
  546. while($stack)
  547. {
  548. $thisdir = array_pop($stack);
  549. if($dircont = scandir($thisdir))
  550. {
  551. $i=0;
  552. while(isset($dircont[$i]))
  553. {
  554. if($dircont[$i] !== '.' && $dircont[$i] !== '..')
  555. {
  556. $current_file = $thisdir.DIRECTORY_SEPARATOR.$dircont[$i];
  557. if(is_file($current_file))
  558. {
  559. $path[] = $thisdir.DIRECTORY_SEPARATOR.$dircont[$i];
  560. }
  561. elseif (is_dir($current_file))
  562. {
  563. $path[] = $thisdir.DIRECTORY_SEPARATOR.$dircont[$i];
  564. $stack[] = $current_file;
  565. }
  566. }
  567. $i++;
  568. }
  569. }
  570. }
  571. return $path;
  572. }
  573. //the function echo the help [?] links to the documentation
  574. function helpLink($name)
  575. {
  576. global $lang;
  577. return "<a href='?help=1' onclick='openHelp(\"".$name."\"); return false;' class='helpq' title='".$lang['help'].": ".$name."' target='_blank'><span>[?]</span></a>";
  578. }
  579. // function to encode value into HTML just like htmlentities, but with adjusted default settings
  580. function htmlencode($value, $flags=ENT_QUOTES, $encoding ="UTF-8")
  581. {
  582. return htmlentities($value, $flags, $encoding);
  583. }
  584. // reduce string chars
  585. function subString($str)
  586. {
  587. global $charsNum, $params;
  588. if($charsNum > 10 && (!isset($params->fulltexts) || !$params->fulltexts) && mb_strlen($str)>$charsNum)
  589. {
  590. $str = mb_substr($str, 0, $charsNum).'...';
  591. }
  592. return $str;
  593. }
  594. // marks searchwords and htmlencodes correctly
  595. function markSearchWords($input, $field, $search)
  596. {
  597. $output = htmlencode($input);
  598. if(isset($search['values'][$field]) && is_array($search['values'][$field]))
  599. {
  600. // build one regex that matches (all) search words
  601. $regex = '/';
  602. $vali=0;
  603. foreach($search['values'][$field] as $searchValue)
  604. {
  605. if($search['operators'][$field] =='LIKE' || $search['operators'][$field] == 'LIKE%')
  606. $regex .= '(?:'.($searchValue[0]=='%'?'':'^'); // does the searchvalue have to occur at the start?
  607. $regex .= preg_quote(trim($searchValue,'%'),'/'); // the search value
  608. if($search['operators'][$field] =='LIKE' || $search['operators'][$field] == 'LIKE%')
  609. $regex .= (substr($searchValue,-1)=='%'?'':'$').')'; // does the searchvalue have to occur at the end?
  610. if($vali++<count($search['values'][$field]))
  611. $regex .= '|'; // there is another search value, so we add a |
  612. }
  613. $regex .= '/u';
  614. // LIKE operator is not case sensitive, others are
  615. if($search['operators'][$field] =='LIKE' || $search['operators'][$field] == 'LIKE%')
  616. $regex.= 'i';
  617. // split the string into parts that match and should be highlighted and parts in between
  618. // $fldBetweenParts: the parts that don't match (might contain empty strings)
  619. $fldBetweenParts = preg_split($regex, $input);
  620. // $fldFoundParts[0]: the parts that match
  621. preg_match_all($regex, $input, $fldFoundParts);
  622. // stick the parts together
  623. $output = '';
  624. foreach($fldBetweenParts as $index => $betweenPart)
  625. {
  626. $output .= htmlencode($betweenPart); // part that does not match (might be empty)
  627. if(isset($fldFoundParts[0][$index]))
  628. $output .= '<u class="found">'.htmlencode($fldFoundParts[0][$index]).'</u>'; // the part that matched
  629. }
  630. }
  631. return $output;
  632. }
  633. // checks the (new) name of a database file
  634. function checkDbName($name)
  635. {
  636. global $allowed_extensions;
  637. $info = pathinfo($name);
  638. if(isset($info['extension']) && !in_array($info['extension'], $allowed_extensions))
  639. {
  640. return false;
  641. } else
  642. {
  643. return (!is_file($name) && !is_dir($name));
  644. }
  645. }
  646. // check whether a path is a db managed by this tool
  647. // requires that $databases is already filled!
  648. // returns the key of the db if managed, false otherwise.
  649. function isManagedDB($path)
  650. {
  651. global $databases;
  652. foreach($databases as $db_key => $database)
  653. {
  654. if($path === $database['path'])
  655. {
  656. // a db we manage. Thats okay.
  657. // return the key.
  658. return $db_key;
  659. }
  660. }
  661. // not a db we manage!
  662. return false;
  663. }
  664. // from a typename of a colun, get the type of the column's affinty
  665. // see https://www.sqlite.org/datatype3.html section 2.1 for rules
  666. function get_type_affinity($type)
  667. {
  668. if (preg_match("/INT/i", $type))
  669. return "INTEGER";
  670. else if (preg_match("/(?:CHAR|CLOB|TEXT)/i", $type))
  671. return "TEXT";
  672. else if (preg_match("/BLOB/i", $type) || $type=="")
  673. return "NONE";
  674. else if (preg_match("/(?:REAL|FLOA|DOUB)/i", $type))
  675. return "REAL";
  676. else
  677. return "NUMERIC";
  678. }
  679. // Returns a file size limit in bytes based on the PHP upload_max_filesize
  680. // post_max_size and memory_limit. Returns -1 in case of no limit.
  681. function fileUploadMaxSize()
  682. {
  683. $max1 = parseSize(ini_get('post_max_size'));
  684. $max2 = parseSize(ini_get('upload_max_filesize'));
  685. $max3 = parseSize(ini_get('memory_limit'));
  686. if($max1>0 && ($max1<=$max2 || $max2==0) && ($max1<=$max3 || $max3==-1))
  687. return $max1;
  688. elseif($max2>0 && ($max2<=$max1 || $max1==0) && ($max2<=$max3 || $max3==-1))
  689. return $max2;
  690. elseif($max3>-1 && ($max3<=$max1 || $max1==0) && ($max3<=$max2 || $max2==0))
  691. return $max3;
  692. else
  693. return -1; // no limit
  694. }
  695. // Parses given size string like "12M" into number of bytes
  696. // based on https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Utility%21Bytes.php/function/Bytes%3A%3AtoInt/8.2.x
  697. function parseSize($size)
  698. {
  699. // Remove the non-unit characters from the size.
  700. $unit = preg_replace('/[^bkmgtpezy]/i', '', $size);
  701. // Remove the non-numeric characters from the size.
  702. $size = preg_replace('/[^0-9\.]/', '', $size);
  703. if ($unit)
  704. {
  705. // Find the position of the unit in the ordered string which is the power
  706. // of magnitude to multiply a kilobyte by.
  707. return round($size * pow(1024, stripos('bkmgtpezy', $unit[0])));
  708. }
  709. else {
  710. return round($size);
  711. }
  712. }
  713. //- Check user authentication, login and logout
  714. $auth = new Authorization(); //create authorization object
  715. // check if user has attempted to log out
  716. if (isset($_GET['logout']))
  717. $auth->revoke();
  718. // check if user has attempted to log in
  719. else if (isset($_POST['login']) && isset($_POST['password']))
  720. {
  721. $attempt = $auth->attemptGrant($_POST['password'], isset($_POST['remember']));
  722. $params->redirect( $attempt ? array():array('failed'=>'1') );
  723. }
  724. //- Actions on database files and bulk data
  725. if ($auth->isAuthorized())
  726. {
  727. //- Create a new database
  728. if(isset($_POST['new_dbname']))
  729. {
  730. if($_POST['new_dbname']=='')
  731. $params->redirect(array('table'=>null), $lang['err'].': '.$lang['db_blank']);
  732. else
  733. {
  734. $str = preg_replace('@[^\w\-.]@u','', $_POST['new_dbname']);
  735. $dbname = $str;
  736. $dbpath = $str;
  737. if(checkDbName($dbname))
  738. {
  739. $tdata = array();
  740. $tdata['name'] = $dbname;
  741. $tdata['path'] = $directory.DIRECTORY_SEPARATOR.$dbpath;
  742. if(isset($_POST['new_dbtype']))
  743. $tdata['type'] = $_POST['new_dbtype'];
  744. else
  745. $tdata['type'] = 3;
  746. $td = new Database($tdata);
  747. $td->query("VACUUM");
  748. } else
  749. {
  750. if(is_file($dbname) || is_dir($dbname))
  751. $params->redirect(array('view'=>'structure'),$lang['err'].': '.sprintf($lang['db_exists'], htmlencode($dbname)));
  752. else
  753. $params->redirect(array('view'=>'structure'),$lang['extension_not_allowed'].': '.implode(', ', array_map('htmlencode', $allowed_extensions)).'<br />'.$lang['add_allowed_extension']);
  754. }
  755. }
  756. }
  757. //- Scan a directory for databases
  758. if($directory!==false)
  759. {
  760. if($directory[strlen($directory)-1]==DIRECTORY_SEPARATOR) //if user has a trailing slash in the directory, remove it
  761. $directory = substr($directory, 0, strlen($directory)-1);
  762. if(is_dir($directory)) //make sure the directory is valid
  763. {
  764. if($subdirectories===true)
  765. $arr = dir_tree($directory);
  766. else
  767. $arr = scandir($directory);
  768. $databases = array();
  769. $j = 0;
  770. for($i=0; $i<sizeof($arr); $i++) //iterate through all the files in the databases
  771. {
  772. if($subdirectories===false)
  773. $arr[$i] = $directory.DIRECTORY_SEPARATOR.$arr[$i];
  774. if(@!is_file($arr[$i])) continue;
  775. $con = file_get_contents($arr[$i], NULL, NULL, 0, 60);
  776. if(strpos($con, "** This file contains an SQLite 2.1 database **", 0)!==false || strpos($con, "SQLite format 3", 0)!==false)
  777. {
  778. $databases[$j]['path'] = $arr[$i];
  779. if($subdirectories===false)
  780. $databases[$j]['name'] = basename($arr[$i]);
  781. else
  782. $databases[$j]['name'] = $arr[$i];
  783. $databases[$j]['writable'] = is_writable($databases[$j]['path']);
  784. $databases[$j]['writable_dir'] = is_writable(dirname($databases[$j]['path']));
  785. $databases[$j]['readable'] = is_readable($databases[$j]['path']);
  786. $j++;
  787. }
  788. }
  789. // 22 August 2011: gkf fixed bug #50.
  790. sort($databases);
  791. if(isset($tdata))
  792. {
  793. foreach($databases as $db_id => $database)
  794. {
  795. if($database['path'] === $tdata['path'])
  796. {
  797. $currentDB = $database;
  798. $params->database = $database['path'];
  799. break;
  800. }
  801. }
  802. }
  803. }
  804. else //the directory is not valid - display error and exit
  805. {
  806. echo "<div class='confirm' style='margin:20px;'>".$lang['not_dir']."</div>";
  807. exit();
  808. }
  809. }
  810. else
  811. {
  812. for($i=0; $i<sizeof($databases); $i++)
  813. {
  814. if(!file_exists($databases[$i]['path']))
  815. {
  816. // the file does not exist and will be created when clicked, if permissions allow to
  817. $databases[$i]['writable'] = is_writable(dirname($databases[$i]['path']));
  818. $databases[$i]['writable_dir'] = is_writable(dirname($databases[$i]['path']));
  819. $databases[$i]['readable'] = is_writable(dirname($databases[$i]['path']));
  820. }
  821. else
  822. {
  823. $databases[$i]['writable'] = is_writable($databases[$i]['path']);
  824. $databases[$i]['writable_dir'] = is_writable(dirname($databases[$i]['path']));
  825. $databases[$i]['readable'] = is_readable($databases[$i]['path']);
  826. }
  827. }
  828. sort($databases);
  829. }
  830. // we now have the $databases array set. Check whether selected DB is a managed Db (is in this array)
  831. if(!isset($currentDB) && (isset($_GET['database']) || isset($_POST['database']) ) )
  832. {
  833. $selected_db = ( isset($_POST['database']) ? $_POST['database'] : $_GET['database'] );
  834. $db_key = isManagedDB($selected_db);
  835. if($db_key!==false) {
  836. $currentDB = $databases[$db_key];
  837. $params->database = $databases[$db_key]['path'];
  838. }
  839. }
  840. //- Delete an existing database
  841. if(isset($_GET['database_delete']))
  842. {
  843. $dbpath = $_POST['database_delete'];
  844. // check whether $dbpath really is a db we manage
  845. $checkDB = isManagedDB($dbpath);
  846. if($checkDB !== false)
  847. {
  848. unlink($dbpath);
  849. unset($params->database);
  850. unset($currentDB);
  851. unset($databases[$checkDB]);
  852. } else die($lang['err'].': '.$lang['delete_only_managed']);
  853. }
  854. //- Rename an existing database
  855. if(isset($_GET['database_rename']))
  856. {
  857. $oldpath = $_POST['oldname'];
  858. $newpath = $_POST['newname'];
  859. $oldpath_parts = pathinfo($oldpath);
  860. $newpath_parts = pathinfo($newpath);
  861. // only rename?
  862. $newpath = $oldpath_parts['dirname'].DIRECTORY_SEPARATOR.basename($_POST['newname']);
  863. if($newpath != $_POST['newname'] && $subdirectories)
  864. {
  865. // it seems that the file should not only be renamed but additionally moved.
  866. // we need to make sure it stays within $directory...
  867. $new_realpath = realpath($newpath_parts['dirname']).DIRECTORY_SEPARATOR;
  868. $directory_realpath = realpath($directory).DIRECTORY_SEPARATOR;
  869. if(strpos($new_realpath, $directory_realpath)===0)
  870. {
  871. // its okay, the new directory is within $directory
  872. $newpath = $_POST['newname'];
  873. }
  874. else $params->redirect(array('view'=>'rename'), $lang['err'].': '.$lang['db_moved_outside']);
  875. }
  876. if(checkDbName($newpath))
  877. {
  878. $checkDB = isManagedDB($oldpath);
  879. if($checkDB !==false )
  880. {
  881. rename($oldpath, $newpath);
  882. $databases[$checkDB]['path'] = $newpath;
  883. $databases[$checkDB]['name'] = basename($newpath);
  884. $currentDB = $databases[$checkDB];
  885. $params->database = $databases[$checkDB]['path'];
  886. $params->redirect(array('view'=>'rename'), sprintf($lang['db_renamed'], htmlencode($oldpath))." '".htmlencode($newpath)."'.");
  887. }
  888. else $params->redirect(array('view'=>'rename'), $lang['err'].': '.$lang['rename_only_managed']);
  889. }
  890. else
  891. {
  892. if(is_file($newpath) || is_dir($newpath))
  893. $params->redirect(array('view'=>'rename'), $lang['err'].": " . sprintf($lang['db_exists'], htmlencode($newpath)));
  894. else
  895. $params->redirect(array('view'=>'rename'), $lang['err'].": " . $lang['extension_not_allowed'].': '.implode(', ', array_map('htmlencode', $allowed_extensions)).'<br />'.$lang['add_allowed_extension']);
  896. }
  897. }
  898. //- Export (download a dump) an existing database
  899. if(isset($_POST['export']))
  900. {
  901. ob_end_clean();
  902. $export_filename = str_replace(array("\r", "\n"), '',$_POST['filename']); // against http header injection (php < 5.1.2 only)
  903. if($_POST['export_type']=="sql")
  904. {
  905. header('Content-Type: text/sql');
  906. header('Content-Disposition: attachment; filename="'.$export_filename.'.'.$_POST['export_type'].'";');
  907. if(isset($_POST['tables']))
  908. $tables = $_POST['tables'];
  909. else
  910. {
  911. $tables = array();
  912. $tables[0] = $_POST['single_table'];
  913. }
  914. $drop = isset($_POST['drop']);
  915. $structure = isset($_POST['structure']);
  916. $data = isset($_POST['data']);
  917. $transaction = isset($_POST['transaction']);
  918. $comments = isset($_POST['comments']);
  919. $db = new Database($currentDB);
  920. echo $db->export_sql($tables, $drop, $structure, $data, $transaction, $comments);
  921. }
  922. else if($_POST['export_type']=="csv")
  923. {
  924. header("Content-type: application/csv");
  925. header('Content-Disposition: attachment; filename="'.$export_filename.'.'.$_POST['export_type'].'";');
  926. header("Pragma: no-cache");
  927. header("Expires: 0");
  928. if(isset($_POST['tables']))
  929. $tables = $_POST['tables'];
  930. else
  931. {
  932. $tables = array();
  933. $tables[0] = $_POST['single_table'];
  934. }
  935. $field_terminate = $_POST['export_csv_fieldsterminated'];
  936. $field_enclosed = $_POST['export_csv_fieldsenclosed'];
  937. $field_escaped = $_POST['export_csv_fieldsescaped'];
  938. $null = $_POST['export_csv_replacenull'];
  939. $crlf = isset($_POST['export_csv_crlf']);
  940. $fields_in_first_row = isset($_POST['export_csv_fieldnames']);
  941. $db = new Database($currentDB);
  942. echo $db->export_csv($tables, $field_terminate, $field_enclosed, $field_escaped, $null, $crlf, $fields_in_first_row);
  943. }
  944. exit();
  945. }
  946. //- Import a file into an existing database
  947. if(isset($_POST['import']))
  948. {
  949. $db = new Database($currentDB);
  950. $db->registerUserFunction($custom_functions);
  951. if($_POST['import_type']=="sql")
  952. {
  953. $data = file_get_contents($_FILES["file"]["tmp_name"]);
  954. $importSuccess = $db->import_sql($data);
  955. }
  956. else
  957. {
  958. $field_terminate = $_POST['import_csv_fieldsterminated'];
  959. $field_enclosed = $_POST['import_csv_fieldsenclosed'];
  960. $field_escaped = $_POST['import_csv_fieldsescaped'];
  961. $null = $_POST['import_csv_replacenull'];
  962. $fields_in_first_row = isset($_POST['import_csv_fieldnames']);
  963. if(isset($_POST['single_table']) && $_POST['single_table']!='')
  964. $table = $_POST['single_table'];
  965. else
  966. {
  967. $table = basename($_FILES["file"]["name"],".csv");
  968. $i="";
  969. while($db->getTypeOfTable($table.$i)!="")
  970. {
  971. if($i=="")
  972. $i=2;
  973. else
  974. $i++;
  975. }
  976. $table = $table.$i;
  977. }
  978. $importSuccess = $db->import_csv($_FILES["file"]["tmp_name"], $table, $field_terminate, $field_enclosed, $field_escaped, $null, $fields_in_first_row);
  979. }
  980. }
  981. //- Download (backup) a database file (as SQLite file, not as dump)
  982. if(isset($_GET['download']) && isManagedDB($_GET['download'])!==false)
  983. {
  984. ob_end_clean();
  985. header("Content-type: application/octet-stream");
  986. header('Content-Disposition: attachment; filename="'.basename($_GET['download']).'";');
  987. header("Pragma: no-cache");
  988. header("Expires: 0");
  989. readfile($_GET['download']);
  990. exit;
  991. }
  992. //- Select database (from session or first available)
  993. if(!isset($currentDB) && count($databases)>0)
  994. {
  995. //set the current database to the first existing one in the array (default)
  996. $currentDB = reset($databases);
  997. $params->database = $currentDB['path'];
  998. }
  999. if(isset($currentDB))
  1000. {
  1001. //- Open database (creates a Database object)
  1002. $db = new Database($currentDB); //create the Database object
  1003. $db->registerUserFunction($custom_functions);
  1004. }
  1005. // collect parameters early, just once
  1006. $target_table = isset($_GET['table']) ? $_GET['table'] : null;
  1007. // are we working on a view? let's check once here
  1008. $target_table_type = !is_null($target_table) ? $db->getTypeOfTable($target_table) : null;
  1009. if(is_null($target_table_type) && !is_null($target_table))
  1010. $params->redirect(array('table'=>null), $lang['err'].': '.sprintf($lang['tbl_inexistent'], htmlencode($target_table)));
  1011. $params->table = $target_table;
  1012. // initialize / change fulltexts and numrows parameter
  1013. if(isset($_GET['fulltexts']))
  1014. $params->fulltexts = ($_GET['fulltexts'] ? 1 : 0);
  1015. else
  1016. $params->fulltexts = 0;
  1017. if(isset($_GET['numRows']) && intval($_GET['numRows'])>0)
  1018. $params->numRows = intval($_GET['numRows']);
  1019. else
  1020. $params->numRows = $rowsNum;
  1021. //- Switch on $_GET['action'] for operations without output
  1022. if(isset($_GET['action']) && isset($_GET['confirm']))
  1023. {
  1024. switch($_GET['action'])
  1025. {
  1026. //- Table actions
  1027. //- Create table (=table_create)
  1028. case "table_create":
  1029. $num = intval($_POST['rows']);
  1030. $name = $_POST['tablename'];
  1031. $primary_keys = array();
  1032. for($i=0; $i<$num; $i++)
  1033. {
  1034. if($_POST[$i.'_field']!="" && isset($_POST[$i.'_primarykey']))
  1035. {
  1036. $primary_keys[] = $_POST[$i.'_field'];
  1037. }
  1038. }
  1039. $query = "CREATE TABLE ".$db->quote($name)." (";
  1040. for($i=0; $i<$num; $i++)
  1041. {
  1042. if($_POST[$i.'_field']!="")
  1043. {
  1044. $query .= $db->quote($_POST[$i.'_field'])." ";
  1045. $query .= $_POST[$i.'_type']." ";
  1046. if(isset($_POST[$i.'_primarykey']))
  1047. {
  1048. if(count($primary_keys)==1)
  1049. {
  1050. $query .= "PRIMARY KEY ";
  1051. if(isset($_POST[$i.'_autoincrement']) && $db->getType() != "SQLiteDatabase")
  1052. $query .= "AUTOINCREMENT ";
  1053. }
  1054. $query .= "NOT NULL ";
  1055. }
  1056. if(!isset($_POST[$i.'_primarykey']) && isset($_POST[$i.'_notnull']))
  1057. $query .= "NOT NULL ";
  1058. if($_POST[$i.'_defaultoption']!='defined' && $_POST[$i.'_defaultoption']!='none' && $_POST[$i.'_defaultoption']!='expr')
  1059. $query .= "DEFAULT ".$_POST[$i.'_defaultoption']." ";
  1060. elseif($_POST[$i.'_defaultoption']=='expr')
  1061. $query .= "DEFAULT (".$_POST[$i.'_defaultvalue'].") ";
  1062. elseif(isset($_POST[$i.'_defaultvalue']) && $_POST[$i.'_defaultoption']=='defined')
  1063. {
  1064. $typeAffinity = get_type_affinity($_POST[$i.'_type']);
  1065. if(($typeAffinity=="INTEGER" || $typeAffinity=="REAL" || $typeAffinity=="NUMERIC") && is_numeric($_POST[$i.'_defaultvalue']))
  1066. $query .= "DEFAULT ".$_POST[$i.'_defaultvalue']." ";
  1067. else
  1068. $query .= "DEFAULT ".$db->quote($_POST[$i.'_defaultvalue'])." ";
  1069. }
  1070. $query = substr($query, 0, -1);
  1071. $query .= ", ";
  1072. }
  1073. }
  1074. if (count($primary_keys)>1)
  1075. {
  1076. $compound_key = "";
  1077. foreach ($primary_keys as $primary_key)
  1078. {
  1079. $compound_key .= ($compound_key=="" ? "" : ", ") . $db->quote($primary_key);
  1080. }
  1081. $query .= "PRIMARY KEY (".$compound_key."), ";
  1082. }
  1083. $query = substr($query, 0, -2);
  1084. $query .= ")";
  1085. $result = $db->query($query);
  1086. if($result === false)
  1087. $completed = $db->getError(true);
  1088. else
  1089. $completed = $lang['tbl']." '".htmlencode($_POST['tablename'])."' ".$lang['created'].".<br/><span style='font-size:11px;'>".htmlencode($query)."</span>";
  1090. $params->redirect(($result===false ? array() : array('action'=>'column_view', 'table'=>$name) ), $completed);
  1091. break;
  1092. //- Empty table (=table_empty)
  1093. case "table_empty":
  1094. $query1 = "DELETE FROM ".$db->quote_id($_GET['table']).";";
  1095. $result1 = $db->query($query1);
  1096. if($result1 === false)
  1097. $completed = $db->getError(true);
  1098. if(isset($_POST['vacuum']) && $_POST['vacuum'])
  1099. {
  1100. $query2 = "VACUUM;";
  1101. $result2 = $db->query($query2);
  1102. }
  1103. else
  1104. $query2 = "";
  1105. if($result1 !== false)
  1106. $completed = $lang['tbl']." '".htmlencode($_GET['table'])."' ".$lang['emptied'].".<br/><span style='font-size:11px;'>".htmlencode($query1)."<br />".htmlencode($query2)."</span>";
  1107. $params->redirect(($result1===false ? array() : array('action'=>'row_view') ), $completed);
  1108. break;
  1109. //- Create view (=view_create)
  1110. case "view_create":
  1111. $query = "CREATE VIEW ".$db->quote($_POST['viewname'])." AS ".$_POST['select'];
  1112. $result = $db->query($query);
  1113. if($result === false)
  1114. $completed = $db->getError(true);
  1115. else
  1116. $completed = $lang['view']." '".htmlencode($_POST['viewname'])."' ".$lang['created'].".<br/><span style='font-size:11px;'>".htmlencode($query)."</span>";
  1117. $params->redirect(($result===false ? array() : array('action'=>'column_view', 'table'=>$_POST['viewname']) ), $completed);
  1118. break;
  1119. //- Drop table (=table_drop)
  1120. case "table_drop":
  1121. $query1 = "DROP TABLE ".$db->quote_id($_GET['table']).";";
  1122. $result1=$db->query($query1);
  1123. if($result1 === false)
  1124. $completed = $db->getError(true);
  1125. if(isset($_POST['vacuum']) && $_POST['vacuum'])
  1126. {
  1127. $query2 = "VACUUM;";
  1128. $result2 = $db->query($query2);
  1129. }
  1130. else
  1131. $query2 = "";
  1132. if($result1 !== false)
  1133. {
  1134. $target_table = null;
  1135. $completed = $lang['tbl']." '".htmlencode($_GET['table'])."' ".$lang['dropped'].".<br/><span style='font-size:11px;'>".htmlencode($query1)."<br />".htmlencode($query2)."</span>";;
  1136. }
  1137. $params->redirect(array('table'=>null), $completed);
  1138. break;
  1139. //- Drop view (=view_drop)
  1140. case "view_drop":
  1141. $query = "DROP VIEW ".$db->quote_id($_POST['viewname']);
  1142. $result=$db->query($query);
  1143. if($result === false)
  1144. $completed = $db->getError(true);
  1145. else
  1146. $completed = $lang['view']." '".htmlencode($_POST['viewname'])."' ".$lang['dropped'].".<br/><span style='font-size:11px;'>".htmlencode($query)."</span>";
  1147. $params->redirect(array('table'=>null), $completed);
  1148. break;
  1149. //- Rename table (=table_rename)
  1150. case "table_rename":
  1151. $query = "ALTER TABLE ".$db->quote_id($_GET['table'])." RENAME TO ".$db->quote($_POST['newname']);
  1152. $type = $db->getTypeOfTable($_GET['table']);
  1153. if($db->getVersion()==3 && $type=='table' // SQLite 3 can rename tables, not views
  1154. // In SQL(ite) table names are case-insensitve, so changing is not supported by SQLite.
  1155. // But table names are stored and displayed case sensitive, so we use the workaround for case sensitive renaming.
  1156. && !($_GET['table'] !== $_POST['newname'] && strtolower($_GET['table']) === strtolower($_POST['newname']))
  1157. )
  1158. $result = $db->query($query, true);
  1159. else
  1160. // Workaround can rename tables of sqlite2 and views of both sqlite versions. Can also do case sensitive renames.
  1161. $result = $db->query($query, false);
  1162. if($result === false)
  1163. $completed = $db->getError(true);
  1164. else
  1165. {
  1166. $completed = $lang['tbl']." '".htmlencode($_GET['table'])."' ".$lang['renamed']." '".htmlencode($_POST['newname'])."'.<br/><span style='font-size:11px;'>".htmlencode($query)."</span>";
  1167. $target_table = $_POST['newname'];
  1168. }
  1169. $params->redirect(array('action'=>'row_view', 'table'=>$_POST['newname']), $completed);
  1170. break;
  1171. //- Search table (=table_search)
  1172. case "table_search":
  1173. $searchValues = array();
  1174. $searchOperators = array();
  1175. $tableInfo = $db->getTableInfo($target_table);
  1176. $j = 0;
  1177. $whereExpr = array();
  1178. for($i=0; $i<sizeof($tableInfo); $i++)
  1179. {
  1180. $field = $tableInfo[$i][1];
  1181. $operator = $_POST['field_'.$i.'_operator'];
  1182. $searchOperators[$field] = $operator;
  1183. $value = $_POST['field_'.$i.'_value'];
  1184. if($value!="" || $operator=="!= ''" || $operator=="= ''" || $operator == 'IS NULL' || $operator == 'IS NOT NULL')
  1185. {
  1186. if($operator=="= ''" || $operator=="!= ''" || $operator == 'IS NULL' || $operator == 'IS NOT NULL')
  1187. $whereExpr[$j] = $db->quote_id($field)." ".$operator;
  1188. else{
  1189. if($operator == "LIKE%"){
  1190. $operator = "LIKE";
  1191. if(!preg_match('/(^%)|(%$)/', $value)) $value = '%'.$value.'%';
  1192. $searchValues[$field] = array($value);
  1193. $valueQuoted = $db->quote($value);
  1194. }
  1195. elseif($operator == 'IN' || $operator == 'NOT IN')
  1196. {
  1197. $value = trim($value, '() ');
  1198. $values = explode(',',$value);
  1199. $values = array_map('trim', $values, array_fill(0,count($values),' \'"'));
  1200. if($operator == 'IN')
  1201. $searchValues[$field] = $values;
  1202. $values = array_map(array($db, 'quote'), $values);
  1203. $valueQuoted = '(' .implode(', ', $values) . ')';
  1204. }
  1205. else
  1206. {
  1207. $searchValues[$field] = array($value);
  1208. $valueQuoted = $db->quote($value);
  1209. }
  1210. $whereExpr[$j] = $db->quote_id($field)." ".$operator." ".$valueQuoted;
  1211. }
  1212. $j++;
  1213. }
  1214. }
  1215. $searchWhere = '';
  1216. if(sizeof($whereExpr)>0)
  1217. {
  1218. $searchWhere .= " WHERE ".$whereExpr[0];
  1219. for($i=1; $i<sizeof($whereExpr); $i++)
  1220. {
  1221. $searchWhere .= " AND ".$whereExpr[$i];
  1222. }
  1223. }
  1224. $searchID = md5($searchWhere);
  1225. $_SESSION[COOKIENAME.'search'][$searchID] = array(
  1226. 'where' => $searchWhere,
  1227. 'values' => $searchValues,
  1228. 'operators' => $searchOperators
  1229. );
  1230. $params->redirect(array('action'=>'table_search','search'=>$searchID));
  1231. break;
  1232. //- Row actions
  1233. //- Create row (=row_create)
  1234. case "row_create":
  1235. $completed = "";
  1236. $num = $_POST['newRows'];
  1237. $z = 0;
  1238. $error = false;
  1239. $tableInfo = $db->getTableInfo($target_table);
  1240. for($i=0; $i<$num; $i++)
  1241. {
  1242. if(!isset($_POST[$i.":ignore"]))
  1243. {
  1244. $query_cols = "";
  1245. $query_vals = "";
  1246. $all_default = true;
  1247. for($j=0; $j<sizeof($tableInfo); $j++)
  1248. {
  1249. $null = isset($_POST[$j."_null"][$i]);
  1250. $type = strtoupper($tableInfo[$j]['type']);
  1251. $typeAffinity = get_type_affinity($type);
  1252. if(!$null && isset($_POST[$i.":".$j]))
  1253. $value = $_POST[$i.":".$j];
  1254. else
  1255. $value = "";
  1256. if(preg_match('/^BLOB/', $type))
  1257. {
  1258. if($_FILES[$i.":".$j]["error"] == UPLOAD_ERR_OK && is_file($_FILES[$i.":".$j]["tmp_name"]))
  1259. $blobFiles[$j] = $_FILES[$i.":".$j]["tmp_name"];
  1260. else
  1261. $blobFiles[$j] = null;
  1262. }
  1263. elseif($value===$tableInfo[$j]['dflt_value'])
  1264. {
  1265. // if the value is the default value, skip it
  1266. continue;
  1267. }
  1268. $all_default = false;
  1269. $query_cols .= $db->quote_id($tableInfo[$j]['name']).",";
  1270. $function = $_POST["function_".$j][$i];
  1271. if($function!="")
  1272. $query_vals .= $function."(";
  1273. if(preg_match('/^BLOB/', $type))
  1274. $query_vals .= ':blobval'.$j;
  1275. elseif(($typeAffinity=="TEXT" || $typeAffinity=="NONE") && !$null)
  1276. $query_vals .= $db->quote($value);
  1277. elseif(($typeAffinity=="INTEGER" || $typeAffinity=="REAL"|| $typeAffinity=="NUMERIC") && $value=="")
  1278. $query_vals .= "NULL";
  1279. elseif($null)
  1280. $query_vals .= "NULL";
  1281. else
  1282. $query_vals .= $db->quote($value);
  1283. if($function!="")
  1284. $query_vals .= ")";
  1285. $query_vals .= ",";
  1286. }
  1287. $query = "INSERT INTO ".$db->quote_id($target_table);
  1288. if(!$all_default)
  1289. {
  1290. $query_cols = substr($query_cols, 0, strlen($query_cols)-1);
  1291. $query_vals = substr($query_vals, 0, strlen($query_vals)-1);
  1292. $query.=" (". $query_cols . ") VALUES (". $query_vals. ")";
  1293. } else {
  1294. $query .= " DEFAULT VALUES";
  1295. }
  1296. if(isset($blobFiles))
  1297. {
  1298. // blob files need to be done using a prepared statement because the query size would be too large
  1299. $handle = $db->prepareQuery($query);
  1300. foreach($blobFiles as $j=>$filename)
  1301. $db->bindValue($handle, ':blobval'.$j, file_get_contents($filename), 'blob');
  1302. $result1 = $db->executePrepared($handle, false);
  1303. }
  1304. else
  1305. $result1 = $db->query($query);
  1306. if($result1===false)
  1307. $error = true;
  1308. $completed .= "<span style='font-size:11px;'>".htmlencode($query)."</span><br/>";
  1309. $z++;
  1310. }
  1311. }
  1312. if($error)
  1313. $completed = $db->getError(true);
  1314. else
  1315. $completed = $z." ".$lang['rows']." ".$lang['inserted'].".<br/><br/>".$completed;
  1316. $params->redirect(array('action'=>'row_view'), $completed);
  1317. break;
  1318. //- Delete row (=row_delete)
  1319. case "row_delete":
  1320. $pks = json_decode($_GET['pk']);
  1321. $query = "DELETE FROM ".$db->quote_id($target_table)." WHERE (".$db->wherePK($target_table,json_decode($pks[0])).")";
  1322. for($i=1; $i<sizeof($pks); $i++)
  1323. {
  1324. $query .= " OR (".$db->wherePK($target_table,json_decode($pks[$i])).")";
  1325. }
  1326. $result = $db->query($query);
  1327. if($result === false)
  1328. $completed = $db->getError(true);
  1329. else
  1330. $completed = sizeof($pks)." ".$lang['rows']." ".$lang['deleted'].".<br/><span style='font-size:11px;'>".htmlencode($query)."</span>";
  1331. $params->redirect(array('action'=>'row_view'), $completed);
  1332. break;
  1333. //- Edit row (=row_edit)
  1334. case "row_edit":
  1335. $pks = json_decode($_GET['pk']);
  1336. $z = 0;
  1337. $tableInfo = $db->getTableInfo($target_table);
  1338. if(isset($_POST['new_row']))
  1339. $completed = "";
  1340. else
  1341. $completed = sizeof($pks)." ".$lang['rows']." ".$lang['affected'].".<br/><br/>";
  1342. for($i=0; $i<sizeof($pks); $i++)
  1343. {
  1344. if(isset($_POST['new_row']))
  1345. {
  1346. $query_cols = "";
  1347. $query_vals = "";
  1348. $all_default = true;
  1349. for($j=0; $j<sizeof($tableInfo); $j++)
  1350. {
  1351. $null = isset($_POST[$j."_null"][$i]);
  1352. $type = strtoupper($tableInfo[$j]['type']);
  1353. $typeAffinity = get_type_affinity($type);
  1354. if(!$null)
  1355. {
  1356. if(preg_match('/^BLOB/', $type))
  1357. {
  1358. if(isset($_POST["row_".$i."_field_".$j."_blob_use"]) && $_POST["row_".$i."_field_".$j."_blob_use"]=='old')
  1359. {
  1360. $select = 'SELECT '.$db->quote_id($tableInfo[$j]['name']).' AS \'blob\' FROM '.$db->quote_id($target_table).' WHERE '.$db->wherePK($target_table, json_decode($pks[$i]));
  1361. $bl = $db->select($select);
  1362. $blobFiles[$j] = $bl['blob'];
  1363. unset($bl);
  1364. }
  1365. else
  1366. {
  1367. if($_FILES[$i.":".$j]["error"] == UPLOAD_ERR_OK && is_file($_FILES[$i.":".$j]["tmp_name"]))
  1368. $blobFiles[$j] = file_get_contents($_FILES[$i.":".$j]["tmp_name"]);
  1369. else
  1370. $blobFiles[$j] = null;
  1371. }
  1372. }
  1373. else
  1374. $value = $_POST[$j][$i];
  1375. }
  1376. else
  1377. $value = "";
  1378. if(!preg_match('/^BLOB/', $type) && $value===$tableInfo[$j]['dflt_value'])
  1379. {
  1380. // if the value is the default value, skip it
  1381. continue;
  1382. }
  1383. $all_default = false;
  1384. $query_cols .= $db->quote_id($tableInfo[$j]['name']).",";
  1385. $function = $_POST["function_".$j][$i];
  1386. if($function!="")
  1387. $query_vals .= $function."(";
  1388. if(preg_match('/^BLOB/', $type))
  1389. $query_vals .= ':blobval'.$j;
  1390. elseif(($typeAffinity=="TEXT" || $typeAffinity=="NONE") && !$null)
  1391. $query_vals .= $db->quote($value);
  1392. elseif(($typeAffinity=="INTEGER" || $typeAffinity=="REAL"|| $typeAffinity=="NUMERIC") && $value=="")
  1393. $query_vals .= "NULL";
  1394. elseif($null)
  1395. $query_vals .= "NULL";
  1396. else
  1397. $query_vals .= $db->quote($value);
  1398. if($function!="")
  1399. $query_vals .= ")";
  1400. $query_vals .= ",";
  1401. }
  1402. $query = "INSERT INTO ".$db->quote_id($target_table);
  1403. if(!$all_default)
  1404. {
  1405. $query_cols = substr($query_cols, 0, strlen($query_cols)-1);
  1406. $query_vals = substr($query_vals, 0, strlen($query_vals)-1);
  1407. $query.=" (". $query_cols . ") VALUES (". $query_vals. ")";
  1408. } else {
  1409. $query .= " DEFAULT VALUES";
  1410. }
  1411. if(isset($blobFiles))
  1412. {
  1413. // blob files need to be done using a prepared statement because the query size would be too large
  1414. $handle = $db->prepareQuery($query);
  1415. foreach($blobFiles as $j=>$blobval)
  1416. $db->bindValue($handle, ':blobval'.$j, $blobval, 'blob');
  1417. $result1 = $db->executePrepared($handle, false);
  1418. }
  1419. else
  1420. $result1 = $db->query($query);
  1421. if($result1===false)
  1422. $error = true;
  1423. $z++;
  1424. }
  1425. else
  1426. {
  1427. $query = "UPDATE ".$db->quote_id($target_table)." SET ";
  1428. for($j=0; $j<sizeof($tableInfo); $j++)
  1429. {
  1430. $type = strtoupper($tableInfo[$j]['type']);
  1431. $function = $_POST["function_".$j][$i];
  1432. $null = isset($_POST[$j."_null"][$i]);
  1433. // if the old BLOB value is chosen to be kept, just skip this column
  1434. if(!$null && preg_match('/^BLOB/', $type) && isset($_POST["row_".$i."_field_".$j."_blob_use"]) && $_POST["row_".$i."_field_".$j."_blob_use"]=='old')
  1435. continue;
  1436. if(!$null && preg_match('/^BLOB/', $type))
  1437. {
  1438. if($_FILES[$i.":".$j]["error"] == UPLOAD_ERR_OK && is_file($_FILES[$i.":".$j]["tmp_name"]))
  1439. $blobFiles[$j] = $_FILES[$i.":".$j]["tmp_name"];
  1440. else
  1441. $blobFiles[$j] = null;
  1442. }
  1443. $query .= $db->quote_id($tableInfo[$j]['name'])."=";
  1444. if($function!="")
  1445. $query .= $function."(";
  1446. if($null)
  1447. $query .= "NULL";
  1448. else
  1449. {
  1450. if(preg_match('/^BLOB/', $type))
  1451. $query .= ':blobval'.$j;
  1452. else
  1453. $query .= $db->quote($_POST[$j][$i]);
  1454. }
  1455. if($function!="")
  1456. $query .= ")";
  1457. $query .= ", ";
  1458. }
  1459. $query = substr($query, 0, -2);
  1460. $query .= " WHERE ".$db->wherePK($target_table, json_decode($pks[$i]));
  1461. if(isset($blobFiles))
  1462. {
  1463. // blob files need to be done using a prepared statement because the query size would be too large
  1464. $handle = $db->prepareQuery($query);
  1465. foreach($blobFiles as $j=>$filename)
  1466. $db->bindValue($handle, ':blobval'.$j, file_get_contents($filename), 'blob');
  1467. $result1 = $db->executePrepared($handle, false);
  1468. }
  1469. else
  1470. $result1 = $db->query($query);
  1471. if($result1===false)
  1472. {
  1473. $error = true;
  1474. }
  1475. }
  1476. $completed .= "<span style='font-size:11px;'>".htmlencode($query)."</span><br/>";
  1477. }
  1478. if($error)
  1479. $completed = $db->getError(true);
  1480. elseif(isset($_POST['new_row']))
  1481. $completed = $z." ".$lang['rows']." ".$lang['inserted'].".<br/><br/>".$completed;
  1482. $params->redirect(array('action'=>'row_view'), $completed);
  1483. break;
  1484. case "row_get_blob":
  1485. $blobVal = $db->select("SELECT ".$db->quote_id($_GET['column'])." AS 'blob' FROM ".$db->quote_id($target_table)." WHERE ".$db->wherePK($target_table, json_decode($_GET['pk'])));
  1486. $filename = 'download';
  1487. if(function_exists('getimagesizefromstring')) // introduced in PHP 5.4.0
  1488. $imagesize = getimagesizefromstring($blobVal['blob']);
  1489. if(isset($imagesize) && $imagesize!==false && isset($imagesize['mime']))
  1490. $mimetype = $imagesize['mime'];
  1491. elseif(class_exists('finfo')) // included since php 5.3.0, but might be disabled on Windows
  1492. {
  1493. $finfo = new finfo(FILEINFO_MIME);
  1494. $mimetype = $finfo->buffer($blobVal['blob']);
  1495. }
  1496. else
  1497. $mimetype = "application/octet-stream";
  1498. if(isset($imagesize) && $imagesize!==false && isset($imagesize[2]))
  1499. $extension = image_type_to_extension($imagesize[2]);
  1500. else
  1501. $extension = '.blob';
  1502. ob_end_clean();
  1503. header('Content-Length: '.strlen($blobVal['blob']));
  1504. header("Content-type: ".$mimetype);
  1505. if(isset($_GET['download_blob']) && $_GET['download_blob'])
  1506. header('Content-Disposition: attachment; filename="'.$filename.$extension.'";');
  1507. header("Pragma: no-cache");
  1508. header("Expires: 0");
  1509. echo $blobVal['blob'];
  1510. exit;
  1511. break;
  1512. //- Column actions
  1513. //- Create column (=column_create)
  1514. case "column_create":
  1515. $num = intval($_POST['rows']);
  1516. for($i=0; $i<$num; $i++)
  1517. {
  1518. if($_POST[$i.'_field']!="")
  1519. {
  1520. $query = "ALTER TABLE ".$db->quote_id($target_table)." ADD ".$db->quote($_POST[$i.'_field'])." ";
  1521. $query .= $_POST[$i.'_type']." ";
  1522. if(isset($_POST[$i.'_primarykey']))
  1523. $query .= "PRIMARY KEY ";
  1524. if(isset($_POST[$i.'_notnull']))
  1525. $query .= "NOT NULL ";
  1526. if($_POST[$i.'_defaultoption']!='defined' && $_POST[$i.'_defaultoption']!='none' && $_POST[$i.'_defaultoption']!='expr')
  1527. $query .= "DEFAULT ".$_POST[$i.'_defaultoption']." ";
  1528. elseif($_POST[$i.'_defaultoption']=='expr')
  1529. $query .= "DEFAULT (".$_POST[$i.'_defaultvalue'].") ";
  1530. elseif(isset($_POST[$i.'_defaultvalue']) && $_POST[$i.'_defaultoption']=='defined')
  1531. {
  1532. $typeAffinity = get_type_affinity($_POST[$i.'_type']);
  1533. if(($typeAffinity=="INTEGER" || $typeAffinity=="REAL" || $typeAffinity=="NUMERIC") && is_numeric($_POST[$i.'_defaultvalue']))
  1534. $query .= "DEFAULT ".$_POST[$i.'_defaultvalue']." ";
  1535. else
  1536. $query .= "DEFAULT ".$db->quote($_POST[$i.'_defaultvalue'])." ";
  1537. }
  1538. if($db->getVersion()==3 &&
  1539. ($_POST[$i.'_defaultoption']=='defined' || $_POST[$i.'_defaultoption']=='none' || $_POST[$i.'_defaultoption']=='NULL')
  1540. // Sqlite3 cannot add columns with default values that are not constant
  1541. && !isset($_POST[$i.'_primarykey'])
  1542. // sqlite3 cannot add primary key columns
  1543. && (!isset($_POST[$i.'_notnull']) || $_POST[$i.'_defaultoption']!='none')
  1544. // SQLite3 cannot add NOT NULL columns without DEFAULT even if the table is empty
  1545. )
  1546. // use SQLITE3 ALTER TABLE ADD COLUMN
  1547. $result = $db->query($query, true);
  1548. else
  1549. // use ALTER TABLE workaround
  1550. $result = $db->query($query, false);
  1551. if($result===false)
  1552. $error = true;
  1553. }
  1554. }
  1555. if($error)
  1556. $completed = $db->getError(true);
  1557. else
  1558. $completed = $lang['tbl']." '".htmlencode($target_table)."' ".$lang['altered'].".";
  1559. $params->redirect(array('action'=>'column_view'), $completed);
  1560. break;
  1561. //- Delete column (=column_delete)
  1562. case "column_delete":
  1563. $pks = explode(":", $_GET['pk']);
  1564. $query = "ALTER TABLE ".$db->quote_id($target_table).' DROP '.$db->quote_id($pks[0]);
  1565. for($i=1; $i<sizeof($pks); $i++)
  1566. {
  1567. $query .= ", DROP ".$db->quote_id($pks[$i]);
  1568. }
  1569. $result = $db->query($query);
  1570. if($result === false)
  1571. $completed = $db->getError(true);
  1572. else
  1573. $completed = $lang['tbl']." '".htmlencode($target_table)."' ".$lang['altered'].".";
  1574. $params->redirect(array('action'=>'column_view'), $completed);
  1575. break;
  1576. //- Add a primary key (=primarykey_add)
  1577. case "primarykey_add":
  1578. $pks = explode(":", $_GET['pk']);
  1579. $query = "ALTER TABLE ".$db->quote_id($target_table).' ADD PRIMARY KEY ('.$db->quote_id($pks[0]);
  1580. for($i=1; $i<sizeof($pks); $i++)
  1581. {
  1582. $query .= ", ".$db->quote_id($pks[$i]);
  1583. }
  1584. $query .= ")";
  1585. $result = $db->query($query);
  1586. if($result === false)
  1587. $completed = $db->getError(true);
  1588. else
  1589. $completed = $lang['tbl']." '".htmlencode($target_table)."' ".$lang['altered'].".";
  1590. $params->redirect(array('action'=>'column_view'), $completed);
  1591. break;
  1592. //- Edit column (=column_edit)
  1593. case "column_edit":
  1594. $query = "ALTER TABLE ".$db->quote_id($target_table).' CHANGE '.$db->quote_id($_POST['oldvalue'])." ".$db->quote($_POST['0_field'])." ".$_POST['0_type'];
  1595. $result = $db->query($query);
  1596. if($result === false)
  1597. $completed = $db->getError(true);
  1598. else
  1599. $completed = $lang['tbl']." '".htmlencode($target_table)."' ".$lang['altered'].".";
  1600. $params->redirect(array('action'=>'column_view'), $completed);
  1601. break;
  1602. //- Delete trigger (=trigger_delete)
  1603. case "trigger_delete":
  1604. $query = "DROP TRIGGER ".$db->quote_id($_GET['pk']);
  1605. $result = $db->query($query);
  1606. if($result === false)
  1607. $completed = $db->getError(true);
  1608. else
  1609. $completed = $lang['trigger']." '".htmlencode($_GET['pk'])."' ".$lang['deleted'].".<br/><span style='font-size:11px;'>".htmlencode($query)."</span>";
  1610. $params->redirect(array('action'=>'column_view'), $completed);
  1611. break;
  1612. //- Delete index (=index_delete)
  1613. case "index_delete":
  1614. $query = "DROP INDEX ".$db->quote_id($_GET['pk']);
  1615. $result = $db->query($query);
  1616. if($result === false)
  1617. $completed = $db->getError(true);
  1618. else
  1619. $completed = $lang['index']." '".htmlencode($_GET['pk'])."' ".$lang['deleted'].".<br/><span style='font-size:11px;'>".htmlencode($query)."</span>";
  1620. $params->redirect(array('action'=>'column_view'), $completed);
  1621. break;
  1622. //- Create trigger (=trigger_create)
  1623. case "trigger_create":
  1624. $str = "CREATE TRIGGER ".$db->quote($_POST['trigger_name']);
  1625. if($_POST['beforeafter']!="")
  1626. $str .= " ".$_POST['beforeafter'];
  1627. $str .= " ".$_POST['event']." ON ".$db->quote_id($target_table);
  1628. if(isset($_POST['foreachrow']))
  1629. $str .= " FOR EACH ROW";
  1630. if($_POST['whenexpression']!="")
  1631. $str .= " WHEN ".$_POST['whenexpression'];
  1632. $str .= " BEGIN";
  1633. $str .= " ".$_POST['triggersteps'];
  1634. $str .= " END";
  1635. $query = $str;
  1636. $result = $db->query($query);
  1637. if($result === false)
  1638. $completed = $db->getError(true);
  1639. else
  1640. $completed = $lang['trigger']." ".$lang['created'].".<br/><span style='font-size:11px;'>".htmlencode($query)."</span>";
  1641. $params->redirect(array('action'=>'column_view'), $completed);
  1642. break;
  1643. //- Create index (=index_create)
  1644. case "index_create":
  1645. $num = $_POST['num'];
  1646. if($_POST['name']=="")
  1647. {
  1648. $completed = $lang['blank_index'];
  1649. }
  1650. else if($_POST['0_field']=="")
  1651. {
  1652. $completed = $lang['one_index'];
  1653. }
  1654. else
  1655. {
  1656. $str = "CREATE ";
  1657. if($_POST['duplicate']=="no")
  1658. $str .= "UNIQUE ";
  1659. $str .= "INDEX ".$db->quote($_POST['name'])." ON ".$db->quote_id($target_table)." (";
  1660. $str .= $db->quote_id($_POST['0_field']).$_POST['0_order'];
  1661. for($i=1; $i<$num; $i++)
  1662. {
  1663. if($_POST[$i.'_field']!="")
  1664. $str .= ", ".$db->quote_id($_POST[$i.'_field']).$_POST[$i.'_order'];
  1665. }
  1666. $str .= ")";
  1667. if(isset($_POST['where']) && $_POST['where']!='')
  1668. $str.=" WHERE ".$_POST['where'];
  1669. $query = $str;
  1670. $result = $db->query($query);
  1671. if($result === false)
  1672. $completed = $db->getError(true);
  1673. else
  1674. $completed = $lang['index']." ".$lang['created'].".<br/><span style='font-size:11px;'>".htmlencode($query)."</span>";
  1675. }
  1676. $params->redirect(array('action'=>'column_view'), $completed);
  1677. break;
  1678. }
  1679. }
  1680. }
  1681. // if not in debug mode, destroy all output until here
  1682. if($debug)
  1683. $bufferedOutput = ob_get_contents();
  1684. ob_end_clean();
  1685. //- HTML: output starts here
  1686. header('Content-Type: text/html; charset=utf-8');
  1687. ?>
  1688. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  1689. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  1690. <head>
  1691. <!-- Copyright <?php echo date("Y").' '.PROJECT.' ('.PROJECT_URL.')'; ?> -->
  1692. <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
  1693. <link rel="shortcut icon" href="?resource=favicon" />
  1694. <title><?php echo PROJECT ?></title>
  1695. <?php
  1696. //- HTML: css/theme include
  1697. if(isset($_GET['theme'])) $theme = basename($_GET['theme']);
  1698. // allow themes to be dropped in subfolder "themes"
  1699. if(is_file('themes/'.$theme)) $theme = 'themes/'.$theme;
  1700. if (file_exists($theme))
  1701. // an external stylesheet exists - import it
  1702. echo "<link href='{$theme}' rel='stylesheet' type='text/css' />", PHP_EOL;
  1703. else
  1704. // only use the default stylesheet if an external one does not exist
  1705. echo "<link href='?resource=css' rel='stylesheet' type='text/css' />", PHP_EOL;
  1706. // HTML: output help text, then exit
  1707. if(isset($_GET['help']))
  1708. {
  1709. //help section array
  1710. $help = array($lang['help1'] => sprintf($lang['help1_x'], PROJECT, PROJECT, PROJECT));
  1711. for($i=2; isset($lang['help'.$i]); $i++)
  1712. $help[$lang['help'.$i]]=$lang['help'.$i.'_x'];
  1713. ?>
  1714. </head>
  1715. <body style="direction:<?php echo $lang['direction']; ?>;">
  1716. <div id='help_container'>
  1717. <?php
  1718. echo "<div class='help_list'>";
  1719. echo "<span style='font-size:18px;'>".PROJECT." v".VERSION." ".$lang['help_doc']."</span><br/><br/>";
  1720. foreach((array)$help as $key => $val)
  1721. {
  1722. echo "<a href='#".$key."'>".$key."</a><br/>";
  1723. }
  1724. echo "</div>";
  1725. echo "<br/><br/>";
  1726. foreach((array)$help as $key => $val)
  1727. {
  1728. echo "<div class='help_outer'>";
  1729. echo "<a class='headd' name='".$key."'>".$key."</a>";
  1730. echo "<div class='help_inner'>";
  1731. echo $val;
  1732. echo "</div>";
  1733. echo "<a class='help_top' href='#top'>".$lang['back_top']."</a>";
  1734. echo "</div>";
  1735. }
  1736. ?>
  1737. </div>
  1738. </body>
  1739. </html>
  1740. <?php
  1741. exit();
  1742. }
  1743. if($auth->isAuthorized())
  1744. {
  1745. //- Javascript include
  1746. ?>
  1747. <!-- JavaScript Support -->
  1748. <script type='text/javascript' src='?resource=javascript'></script>
  1749. <script type="text/javascript">
  1750. var fileUploadMaxSize = <?php echo fileUploadMaxSize(); ?>;
  1751. var fileUploadMaxSizeErrorMsg = '<?php echo $lang['err'].': \n'.$lang['max_file_size']; ?>';
  1752. </script>
  1753. <!-- SQL code editor with Syntax Highlighting etc. -->
  1754. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.24.2/codemirror.min.css">
  1755. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.24.2/addon/hint/show-hint.min.css">
  1756. <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.24.2/codemirror.min.js"></script>
  1757. <!-- Codemirror 5.24.2 does not yet include the SQLite support that we wrote, so we fetch changed files from rawgit for the time being-->
  1758. <script src="https://cdn.rawgit.com/codemirror/CodeMirror/c4387d6073b15ccf0f32773eb71a54f3b694f2f0/mode/sql/sql.js"></script>
  1759. <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.24.2/addon/hint/show-hint.min.js"></script>
  1760. <script src="https://cdn.rawgit.com/codemirror/CodeMirror/65c70cf5d18ac3a0c1a3fe717d90a81ff823aa9f/addon/hint/sql-hint.js"></script>
  1761. <?php
  1762. }
  1763. ?>
  1764. </head>
  1765. <body style="direction:<?php echo $lang['direction']; ?>;">
  1766. <?php
  1767. // if in debug mode, ouput all output that has been generated above now
  1768. if($debug)
  1769. echo $bufferedOutput;
  1770. if(ini_get("register_globals") == "on" || ini_get("register_globals")=="1") //check whether register_globals is turned on - if it is, we need to not continue
  1771. {
  1772. echo "<div class='confirm' style='margin:20px;'>".$lang['bad_php_directive']."</div>";
  1773. echo "</body></html>";
  1774. exit();
  1775. }
  1776. //- HTML: login screen if not authorized, exit
  1777. if(!$auth->isAuthorized())
  1778. {
  1779. echo "<div id='loginBox'>";
  1780. echo "<h1><span id='logo'>".PROJECT."</span> <span id='version'>v".VERSION."</span></h1>";
  1781. echo "<div style='padding:15px; text-align:center;'>";
  1782. if (isset($_GET['failed']))
  1783. echo "<span class='warning'>".$lang['passwd_incorrect']."</span><br/><br/>";
  1784. echo $params->getForm();
  1785. echo $lang['passwd'].": <input type='password' name='password' autofocus='autofocus'/><br/>";
  1786. echo "<label><input type='checkbox' name='remember' value='yes' checked='checked'/> ".$lang['remember']."</label><br/><br/>";
  1787. echo "<input type='submit' value='".$lang['login']."' class='btn'/>";
  1788. echo "<input type='hidden' name='login' value='true' />";
  1789. echo "</form>";
  1790. echo "</div>";
  1791. echo "</div>";
  1792. echo "<br/>";
  1793. echo "<div style='text-align:center;'>";
  1794. echo "<span style='font-size:11px;'>".$lang['powered']." <a href='".PROJECT_URL."' target='_blank' style='font-size:11px;'>".PROJECT."</a> | ";
  1795. printf($lang['page_gen'], $pageTimer);
  1796. echo "</span></div>";
  1797. echo "</body></html>";
  1798. exit();
  1799. }
  1800. //- User is authorized, display the main application
  1801. if(count($databases)==0) // the database array is empty, offer to create a new database
  1802. {
  1803. //- HTML: form to create a new database, exit
  1804. if($directory!==false && is_writable($directory))
  1805. {
  1806. echo "<div class='confirm' style='margin:20px;'>";
  1807. printf($lang['no_db'], PROJECT, PROJECT);
  1808. echo "</div>";
  1809. //if the user has performed some action, show the resulting message
  1810. if(isset($_GET['message']) && isset($_SESSION[COOKIENAME.'messages'][$_GET['message']]))
  1811. {
  1812. echo "<div class='confirm' style='margin:10px 20px;'>";
  1813. echo $_SESSION[COOKIENAME.'messages'][$_GET['message']];
  1814. echo "</div><br />";
  1815. unset($_SESSION[COOKIENAME.'messages'][$_GET['message']]);
  1816. }
  1817. echo "<fieldset style='margin:15px;'><legend><b>".$lang['db_create']."</b></legend>";
  1818. echo $params->getForm(array('table'=>null), 'post', false, 'create_database');
  1819. echo "<input type='text' name='new_dbname' style='width:150px;'/> ";
  1820. if(class_exists('SQLiteDatabase') && (class_exists('SQLite3') || class_exists('PDO')))
  1821. {
  1822. echo "<select name='new_dbtype' class='newDbType'>";
  1823. echo "<option value='3'>SQLite 3</option>";
  1824. echo "<option value='2'>SQLite 2</option>";
  1825. echo "</select>";
  1826. }
  1827. echo "<input type='submit' value='".$lang['create']."' class='btn'/>";
  1828. echo "</form>";
  1829. echo "</fieldset>";
  1830. }
  1831. elseif(($directory!==false && !is_executable($directory)))
  1832. {
  1833. echo "<div class='confirm' style='margin:20px;'>";
  1834. echo $lang['err'].": ".sprintf($lang['dir_not_executable'], PROJECT, $directory);
  1835. echo "</div><br/>";
  1836. }
  1837. else
  1838. {
  1839. echo "<div class='confirm' style='margin:20px;'>";
  1840. echo $lang['err'].": ".sprintf($lang['no_db2'], PROJECT);
  1841. echo "</div><br/>";
  1842. }
  1843. exit();
  1844. }
  1845. //- HTML: sidebar
  1846. echo '<table class="body_tbl" width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td valign="top" class="left_td" style="width:100px; padding:9px 2px 9px 9px;">';
  1847. echo "<div id='leftNav'>";
  1848. echo "<h1><a href='".$params->getURL()."'>";
  1849. echo "<span id='logo'>".PROJECT."</span> <span id='version'>v".VERSION."</span>";
  1850. echo "</a></h1>";
  1851. echo "<div id='headerlinks'>";
  1852. echo "<a href='javascript:void' onclick='openHelp(\"top\");'>".$lang['docu']."</a> | ";
  1853. echo "<a href='https://www.gnu.org/licenses/gpl.html' target='_blank'>".$lang['license']."</a> | ";
  1854. echo "<a href='".PROJECT_URL."' target='_blank'>".$lang['proj_site']."</a>";
  1855. echo "</div>";
  1856. //- HTML: database list
  1857. $db->print_db_list();
  1858. echo "<fieldset style='margin:15px;'><legend>";
  1859. echo "<a href='".$params->getURL(array('table'=>null))."'";
  1860. if (!$target_table)
  1861. echo " class='active_table'";
  1862. $name = $currentDB['name'];
  1863. if(strlen($name)>25)
  1864. $name = "...".substr($name, strlen($name)-22, 22);
  1865. echo ">".htmlencode($name)."</a>";
  1866. echo "</legend>";
  1867. //- HTML: table list
  1868. $tables = $db->getTables(true, false);
  1869. foreach($tables as $tableName => $tableType)
  1870. {
  1871. echo "<span class='sidebar_table'>";
  1872. echo $params->getLink(array('action'=>'column_view', 'table'=>$tableName), "[".$lang[$tableType=='table'?'tbl':'view']."]");
  1873. echo "</span> ";
  1874. echo $params->getLink(array('action'=>'row_view', 'table'=>$tableName), htmlencode($tableName),
  1875. ($target_table == $tableName ? 'active_table' : '') );
  1876. echo "<br/>";
  1877. }
  1878. if(count($tables)==0)
  1879. echo $lang['no_tbl'];
  1880. echo "</fieldset>";
  1881. //- HTML: form to create a new database
  1882. if($directory!==false && is_writable($directory))
  1883. {
  1884. echo "<fieldset style='margin:15px;'><legend><b>".$lang['db_create']."</b> ".helpLink($lang['help2'])."</legend>";
  1885. echo $params->getForm(array('table'=>null), 'post', false, 'create_database');
  1886. echo "<input type='text' name='new_dbname' style='width:150px;'/>";
  1887. if(class_exists('SQLiteDatabase') && (class_exists('SQLite3') || class_exists('PDO')))
  1888. {
  1889. echo "<select name='new_dbtype' class='newDbType'>";
  1890. echo "<option value='3'>SQLite 3</option>";
  1891. echo "<option value='2'>SQLite 2</option>";
  1892. echo "</select>";
  1893. }
  1894. echo "<input type='submit' value='".$lang['create']."' class='btn'/>";
  1895. echo "</form>";
  1896. echo "</fieldset>";
  1897. }
  1898. echo "<div style='text-align:center;'>";
  1899. echo $params->getForm(array(),'get');
  1900. echo "<input type='submit' value='".$lang['logout']."' name='logout' class='btn'/>";
  1901. echo "</form>";
  1902. echo "</div>";
  1903. echo "</div>";
  1904. echo '</td><td valign="top" id="main_column" class="right_td" style="padding:9px 2px 9px 9px;">';
  1905. //- HTML: breadcrumb navigation
  1906. echo $params->getLink(array('table'=>null), htmlencode($currentDB['name']));
  1907. if ($target_table)
  1908. echo " &rarr; ".$params->getLink(array('action'=>'row_view'), htmlencode($target_table));
  1909. echo "<br/><br/>";
  1910. //- Show the various tab views for a table
  1911. if($target_table)
  1912. {
  1913. //- HTML: tabs
  1914. echo $params->getLink(array('action'=>'row_view'), $lang['browse'],
  1915. (in_array($_GET['action'], array('row_view', 'row_editordelete') ) ? 'tab_pressed' : 'tab'));
  1916. echo $params->getLink(array('action'=>'column_view'), $lang['struct'],
  1917. (in_array($_GET['action'], array('column_view', 'column_edit', 'column_confirm', 'primarykey_add', 'column_create', 'index_create', 'index_delete', 'trigger_create', 'trigger_delete') ) ? 'tab_pressed' : 'tab'));
  1918. echo $params->getLink(array('action'=>'table_sql'), $lang['sql'],
  1919. ($_GET['action']=="table_sql" ? 'tab_pressed' : 'tab'));
  1920. echo $params->getLink(array(
  1921. 'action' => 'table_search',
  1922. 'oldSearch' => (isset($_GET['search'])?$_GET['search']:null)
  1923. ), $lang['srch'], ($_GET['action']=="table_search" ? 'tab_pressed' : 'tab'));
  1924. if($target_table_type == 'table' && $db->isWritable() && $db->isDirWritable())
  1925. echo $params->getLink(array('action'=>'row_create'), $lang['insert'],
  1926. ($_GET['action']=="row_create" ? 'tab_pressed' : 'tab'));
  1927. echo $params->getLink(array('action'=>'table_export'), $lang['export'],
  1928. ($_GET['action']=="table_export" ? 'tab_pressed' : 'tab'));
  1929. if($target_table_type == 'table' && $db->isWritable() && $db->isDirWritable())
  1930. echo $params->getLink(array('action'=>'table_import'), $lang['import'],
  1931. ($_GET['action']=="table_import" ? 'tab_pressed' : 'tab'));
  1932. if($db->isWritable() && $db->isDirWritable())
  1933. echo $params->getLink(array('action'=>'table_rename'), $lang['rename'],
  1934. ($_GET['action']=="table_rename" ? 'tab_pressed' : 'tab'));
  1935. if($target_table_type == 'table' && $db->isWritable() && $db->isDirWritable())
  1936. {
  1937. echo $params->getLink(array('action'=>'table_empty'), $lang['empty'],
  1938. ($_GET['action']=="table_empty" ? 'tab_pressed empty' : 'tab empty'));
  1939. echo $params->getLink(array('action'=>'table_drop'), $lang['drop'],
  1940. ($_GET['action']=="table_drop" ? 'tab_pressed drop' : 'tab drop'));
  1941. } elseif($db->isWritable() && $db->isDirWritable()) {
  1942. echo $params->getLink(array('action'=>'view_drop'), $lang['drop'],
  1943. ($_GET['action']=="view_drop" ? 'tab_pressed drop' : 'tab drop'));
  1944. }
  1945. }
  1946. else
  1947. //- Show the various tab views for a database
  1948. {
  1949. $view = isset($_GET['view']) ? $_GET['view'] : 'structure';
  1950. echo $params->getLink(array('view'=>'structure'), $lang['struct'], ($view=="structure" ? 'tab_pressed': 'tab') );
  1951. echo $params->getLink(array('view'=>'sql'), $lang['sql'], ($view=="sql" ? 'tab_pressed': 'tab') );
  1952. echo $params->getLink(array('view'=>'export'), $lang['export'], ($view=="export" ? 'tab_pressed': 'tab') );
  1953. if($db->isWritable() && $db->isDirWritable())
  1954. echo $params->getLink(array('view'=>'import'), $lang['import'], ($view=="import" ? 'tab_pressed': 'tab') );
  1955. if($db->isWritable() && $db->isDirWritable())
  1956. echo $params->getLink(array('view'=>'vacuum'), $lang['vac'], ($view=="vacuum" ? 'tab_pressed': 'tab') );
  1957. if($directory!==false && is_writable($directory))
  1958. {
  1959. echo $params->getLink(array('view'=>'rename'), $lang['db_rename'], ($view=="rename" ? 'tab_pressed': 'tab') );
  1960. echo $params->getLink(array('view'=>'delete'), "<span>".$lang['db_del']."</span>", ($view=="delete" ? 'tab_pressed delete_db': 'tab delete_db') );
  1961. }
  1962. }
  1963. echo "<div style='clear:both;'></div>";
  1964. echo "<div id='main'>";
  1965. //- HTML: confirmation panel
  1966. //if the user has performed some action, show the resulting message
  1967. if(isset($_GET['message']) && isset($_SESSION[COOKIENAME.'messages'][$_GET['message']]))
  1968. {
  1969. echo "<div class='confirm'>";
  1970. echo $_SESSION[COOKIENAME.'messages'][$_GET['message']];
  1971. echo "</div><br />";
  1972. unset($_SESSION[COOKIENAME.'messages'][$_GET['message']]);
  1973. }
  1974. //- Switch on $_GET['action'] for operations with output
  1975. if(isset($_GET['action']) && !isset($_GET['confirm']))
  1976. {
  1977. switch($_GET['action'])
  1978. {
  1979. //- Table actions
  1980. //- Create table (=table_create)
  1981. case "table_create":
  1982. $query = "SELECT name FROM sqlite_master WHERE type='table' AND name=".$db->quote($_GET['tablename']);
  1983. $results = $db->selectArray($query);
  1984. if(sizeof($results)>0)
  1985. $exists = true;
  1986. else
  1987. $exists = false;
  1988. echo "<h2>".$lang['create_tbl'].": '".htmlencode($_GET['tablename'])."'</h2>";
  1989. if($_GET['tablefields']=="" || intval($_GET['tablefields'])<=0)
  1990. echo $lang['specify_fields'];
  1991. else if($_GET['tablename']=="")
  1992. echo $lang['specify_tbl'];
  1993. else if($exists)
  1994. echo $lang['tbl_exists'];
  1995. else
  1996. {
  1997. $num = intval($_GET['tablefields']);
  1998. $name = $_GET['tablename'];
  1999. echo $params->getForm(array('action'=>'table_create', 'confirm'=>'1'));
  2000. echo "<input type='hidden' name='tablename' value='".htmlencode($name)."'/>";
  2001. echo "<input type='hidden' name='rows' value='".$num."'/>";
  2002. echo "<table border='0' cellpadding='2' cellspacing='1' class='viewTable'>";
  2003. echo "<tr>";
  2004. $headings = array($lang['fld'], $lang['type'], $lang['prim_key']);
  2005. if($db->getType() != "SQLiteDatabase") $headings[] = $lang['autoincrement'];
  2006. $headings[] = $lang['not_null'];
  2007. $headings[] = $lang['def_val'];
  2008. for($k=0; $k<count($headings); $k++)
  2009. echo "<td class='tdheader'>" . $headings[$k] . "</td>";
  2010. echo "</tr>";
  2011. for($i=0; $i<$num; $i++)
  2012. {
  2013. $tdWithClass = "<td class='td" . ($i%2 ? "1" : "2") . "'>";
  2014. echo "<tr>";
  2015. echo $tdWithClass;
  2016. echo "<input type='text' name='".$i."_field' style='width:200px;'/>";
  2017. echo "</td>";
  2018. echo $tdWithClass;
  2019. echo "<select name='".$i."_type' id='i".$i."_type' onchange='toggleAutoincrement(".$i.");'>";
  2020. foreach ($sqlite_datatypes as $t) {
  2021. echo "<option value='".htmlencode($t)."'>".htmlencode($t)."</option>";
  2022. }
  2023. echo "</select>";
  2024. echo "</td>";
  2025. echo $tdWithClass;
  2026. echo "<label><input type='checkbox' name='".$i."_primarykey' id='i".$i."_primarykey' onclick='toggleNull(".$i."); toggleAutoincrement(".$i.");'/> ".$lang['yes']."</label>";
  2027. echo "</td>";
  2028. if($db->getType() != "SQLiteDatabase")
  2029. {
  2030. echo $tdWithClass;
  2031. echo "<label><input type='checkbox' name='".$i."_autoincrement' id='i".$i."_autoincrement'/> ".$lang['yes']."</label>";
  2032. echo "</td>";
  2033. }
  2034. echo $tdWithClass;
  2035. echo "<label><input type='checkbox' name='".$i."_notnull' id='i".$i."_notnull'/> ".$lang['yes']."</label>";
  2036. echo "</td>";
  2037. echo $tdWithClass;
  2038. echo "<select name='".$i."_defaultoption' id='i".$i."_defaultoption' onchange=\"if(this.value!='defined' && this.value!='expr') document.getElementById('i".$i."_defaultvalue').value='';\">";
  2039. echo "<option value='none'>".$lang['none']."</option><option value='defined'>".$lang['as_defined'].":</option><option>NULL</option><option>CURRENT_TIME</option><option>CURRENT_DATE</option><option>CURRENT_TIMESTAMP</option><option value='expr'>".$lang['expression'].":</option>";
  2040. echo "</select>";
  2041. echo "<input type='text' name='".$i."_defaultvalue' id='i".$i."_defaultvalue' style='width:100px;' onchange=\"if(document.getElementById('i".$i."_defaultoption').value!='expr') document.getElementById('i".$i."_defaultoption').value='defined';\"/>";
  2042. echo "</td>";
  2043. echo "</tr>";
  2044. }
  2045. echo "<tr>";
  2046. echo "<td class='tdheader' style='text-align:right;' colspan='6'>";
  2047. echo "<input type='submit' value='".$lang['create']."' class='btn'/> ";
  2048. echo $params->getLink(array(), $lang['cancel']);
  2049. echo "</td>";
  2050. echo "</tr>";
  2051. echo "</table>";
  2052. echo "</form>";
  2053. if($db->getType() != "SQLiteDatabase") echo "<script type='text/javascript'>window.onload=initAutoincrement;</script>";
  2054. }
  2055. break;
  2056. //- Perform SQL query on table (=table_sql)
  2057. case "table_sql":
  2058. if(isset($_POST['query']) && $_POST['query']!="")
  2059. {
  2060. $delimiter = $_POST['delimiter'];
  2061. $queryStr = $_POST['queryval'];
  2062. //save the queries in history if necessary
  2063. if($maxSavedQueries!=0 && $maxSavedQueries!=false)
  2064. {
  2065. if(!isset($_SESSION[COOKIENAME.'query_history']))
  2066. $_SESSION[COOKIENAME.'query_history'] = array();
  2067. $_SESSION[COOKIENAME.'query_history'][md5(strtolower($queryStr))] = $queryStr;
  2068. if(sizeof($_SESSION[COOKIENAME.'query_history']) > $maxSavedQueries)
  2069. array_shift($_SESSION[COOKIENAME.'query_history']);
  2070. }
  2071. $query = explode_sql($delimiter, $queryStr); //explode the query string into individual queries based on the delimiter
  2072. for($i=0; $i<sizeof($query); $i++) //iterate through the queries exploded by the delimiter
  2073. {
  2074. if(str_replace(" ", "", str_replace("\n", "", str_replace("\r", "", $query[$i])))!="") //make sure this query is not an empty string
  2075. {
  2076. $queryTimer = new MicroTimer();
  2077. $table_result = $db->query($query[$i]);
  2078. echo "<div class='confirm'>";
  2079. echo "<b>".htmlencode($query[$i])."</b>";
  2080. if($table_result === NULL || $table_result === false)
  2081. {
  2082. echo "<br /><b>".$lang['err'].": ".htmlencode($db->getError())."</b></div>";
  2083. }
  2084. echo "</div><br/>";
  2085. if($row = $db->fetch($table_result, 'num'))
  2086. {
  2087. for($j=0; $j<sizeof($row);$j++)
  2088. $headers[$j] = $db->getColumnName($table_result,$j);
  2089. echo "<table border='0' cellpadding='2' cellspacing='1' class='viewTable'>";
  2090. echo "<tr>";
  2091. for($j=0; $j<sizeof($headers); $j++)
  2092. {
  2093. echo "<td class='tdheader'>";
  2094. echo htmlencode($headers[$j]);
  2095. echo "</td>";
  2096. }
  2097. echo "</tr>";
  2098. $rowCount = 0;
  2099. for(; $rowCount==0 || $row = $db->fetch($table_result, 'num'); $rowCount++)
  2100. {
  2101. $tdWithClass = "<td class='td".($rowCount%2 ? "1" : "2")."'>";
  2102. echo "<tr>";
  2103. for($z=0; $z<sizeof($headers); $z++)
  2104. {
  2105. echo $tdWithClass;
  2106. if($row[$z]==="")
  2107. echo "&nbsp;";
  2108. elseif($row[$z]===NULL)
  2109. echo "<i class='null'>NULL</i>";
  2110. else
  2111. echo htmlencode(subString($row[$z]));
  2112. echo "</td>";
  2113. }
  2114. echo "</tr>";
  2115. }
  2116. $queryTimer->stop();
  2117. echo "</table><br/><br/>";
  2118. if($table_result !== NULL && $table_result !== false)
  2119. {
  2120. echo "<div class='confirm' style='margin-bottom: 2em'>";
  2121. if($rowCount>0 || $db->getAffectedRows()==0)
  2122. {
  2123. printf($lang['show_rows'], $rowCount);
  2124. }
  2125. if($db->getAffectedRows()>0 || $rowCount==0)
  2126. {
  2127. echo $db->getAffectedRows()." ".$lang['rows_aff']." ";
  2128. }
  2129. printf($lang['query_time'], $queryTimer);
  2130. echo "</div>";
  2131. }
  2132. }
  2133. }
  2134. }
  2135. }
  2136. else
  2137. {
  2138. $delimiter = ";";
  2139. $queryStr = "SELECT * FROM ".$db->quote_id($target_table)." WHERE 1";
  2140. }
  2141. echo "<fieldset>";
  2142. echo "<legend><b>".sprintf($lang['run_sql'],htmlencode($db->getName()))."</b></legend>";
  2143. echo $params->getForm(array('action'=>'table_sql'));
  2144. if(isset($_SESSION[COOKIENAME.'query_history']) && sizeof($_SESSION[COOKIENAME.'query_history'])>0)
  2145. {
  2146. echo "<b>".$lang['recent_queries']."</b><ul>";
  2147. foreach($_SESSION[COOKIENAME.'query_history'] as $key => $value)
  2148. echo "<li><a onclick='sqleditorSetValue(this.textContent); return false;' href='#'>".htmlencode($value)."</a></li>";
  2149. echo "</ul><br/><br/>";
  2150. }
  2151. echo "<div style='float:left; width:70%;'>";
  2152. echo "<textarea style='width:97%; height:300px;' name='queryval' id='queryval' cols='50' rows='8'>".htmlencode($queryStr)."</textarea>";
  2153. echo "<script>sqleditor(document.getElementById('queryval'),".json_encode($db->getTableDefinitions()).",'".htmlencode($target_table)."');</script>";
  2154. echo "</div>";
  2155. echo "<div style='float:left; width:28%; padding-left:10px;'>";
  2156. echo $lang['fields']."<br/>";
  2157. echo "<select multiple='multiple' style='width:100%;' id='fieldcontainer'>";
  2158. $tableInfo = $db->getTableInfo($target_table);
  2159. for($i=0; $i<sizeof($tableInfo); $i++)
  2160. {
  2161. echo "<option value='".htmlencode($tableInfo[$i][1])."'>".htmlencode($tableInfo[$i][1])."</option>";
  2162. }
  2163. echo "</select>";
  2164. echo "<input type='button' value='&lt;&lt;' onclick='moveFields();' class='btn'/>";
  2165. echo "</div>";
  2166. echo "<div style='clear:both;'></div>";
  2167. echo $lang['delimit']." <input type='text' name='delimiter' value='".htmlencode($delimiter)."' style='width:50px;'/> ";
  2168. echo "<input type='submit' name='query' value='".$lang['go']."' class='btn'/>";
  2169. echo "</form>";
  2170. echo "</fieldset>";
  2171. break;
  2172. //- Empty table (=table_empty)
  2173. case "table_empty":
  2174. echo $params->getForm(array('action'=>'table_empty','confirm'=>'1'));
  2175. echo "<div class='confirm'>";
  2176. echo sprintf($lang['ques_empty'], htmlencode($target_table))."<br/><br/>";
  2177. echo "<input type='checkbox' name='vacuum' checked='checked'/> ".$lang['vac_on_empty']."<br/><br/>";
  2178. echo "<input type='submit' value='".$lang['confirm']."' class='btn'/> ";
  2179. echo $params->getLink(array('table'=>null), $lang['cancel']);
  2180. echo "</div>";
  2181. break;
  2182. //- Drop table (=table_drop)
  2183. case "table_drop":
  2184. echo $params->getForm(array('action'=>'table_drop','confirm'=>'1'));
  2185. echo "<div class='confirm'>";
  2186. echo sprintf($lang['ques_drop'], htmlencode($target_table))."<br/><br/>";
  2187. echo "<input type='checkbox' name='vacuum' checked='checked'/> ".$lang['vac_on_empty']."<br/><br/>";
  2188. echo "<input type='submit' value='".$lang['confirm']."' class='btn'/> ";
  2189. echo $params->getLink(array('table'=>null), $lang['cancel']);
  2190. echo "</div>";
  2191. break;
  2192. //- Drop view (=view_drop)
  2193. case "view_drop":
  2194. echo $params->getForm(array('action'=>'view_drop','confirm'=>'1'));
  2195. echo "<input type='hidden' name='viewname' value='".htmlencode($target_table)."'/>";
  2196. echo "<div class='confirm'>";
  2197. echo sprintf($lang['ques_drop_view'], htmlencode($target_table))."<br/><br/>";
  2198. echo "<input type='submit' value='".$lang['confirm']."' class='btn'/> ";
  2199. echo $params->getLink(array('table'=>null), $lang['cancel']);
  2200. echo "</div>";
  2201. break;
  2202. //- Export table (=table_export)
  2203. case "table_export":
  2204. echo $params->getForm();
  2205. echo "<fieldset style='float:left; width:260px; margin-right:20px;'><legend><b>".$lang['export']."</b></legend>";
  2206. echo "<input type='hidden' value='".htmlencode($target_table)."' name='single_table'/>";
  2207. echo "<label><input type='radio' name='export_type' checked='checked' value='sql' onclick='toggleExports(\"sql\");'/> ".$lang['sql']."</label>";
  2208. echo "<br/><label><input type='radio' name='export_type' value='csv' onclick='toggleExports(\"csv\");'/> ".$lang['csv']."</label>";
  2209. echo "</fieldset>";
  2210. echo "<fieldset style='float:left; max-width:350px;' id='exportoptions_sql'><legend><b>".$lang['options']."</b></legend>";
  2211. echo "<label><input type='checkbox' checked='checked' name='structure'/> ".$lang['export_struct']."</label> ".helpLink($lang['help5'])."<br/>";
  2212. echo "<label><input type='checkbox' checked='checked' name='data'/> ".$lang['export_data']."</label> ".helpLink($lang['help6'])."<br/>";
  2213. echo "<label><input type='checkbox' name='drop'/> ".$lang['add_drop']."</label> ".helpLink($lang['help7'])."<br/>";
  2214. echo "<label><input type='checkbox' checked='checked' name='transaction'/> ".$lang['add_transact']."</label> ".helpLink($lang['help8'])."<br/>";
  2215. echo "<label><input type='checkbox' checked='checked' name='comments'/> ".$lang['comments']."</label> ".helpLink($lang['help9'])."<br/>";
  2216. echo "</fieldset>";
  2217. echo "<fieldset style='float:left; max-width:350px; display:none;' id='exportoptions_csv'><legend><b>".$lang['options']."</b></legend>";
  2218. echo "<div style='float:left;'>".$lang['fld_terminated']."</div>";
  2219. echo "<input type='text' value=';' name='export_csv_fieldsterminated' style='float:right;'/>";
  2220. echo "<div style='clear:both;'></div>";
  2221. echo "<div style='float:left;'>".$lang['fld_enclosed']."</div>";
  2222. echo "<input type='text' value='\"' name='export_csv_fieldsenclosed' style='float:right;'/>";
  2223. echo "<div style='clear:both;'></div>";
  2224. echo "<div style='float:left;'>".$lang['fld_escaped']."</div>";
  2225. echo "<input type='text' value='\' name='export_csv_fieldsescaped' style='float:right;'/>";
  2226. echo "<div style='clear:both;'></div>";
  2227. echo "<div style='float:left;'>".$lang['rep_null']."</div>";
  2228. echo "<input type='text' value='NULL' name='export_csv_replacenull' style='float:right;'/>";
  2229. echo "<div style='clear:both;'></div>";
  2230. echo "<label><input type='checkbox' name='export_csv_crlf'/> ".$lang['rem_crlf']."</label><br/>";
  2231. echo "<label><input type='checkbox' checked='checked' name='export_csv_fieldnames'/> ".$lang['put_fld']."</label>";
  2232. echo "</fieldset>";
  2233. echo "<div style='clear:both;'></div>";
  2234. echo "<br/><br/>";
  2235. echo "<fieldset><legend><b>".$lang['save_as']."</b></legend>";
  2236. $file = pathinfo($db->getPath());
  2237. $name = $file['filename'];
  2238. echo "<input type='text' name='filename' value='".htmlencode($name)."_".htmlencode($target_table)."_".date("Y-m-d").".dump' style='width:400px;'/> <input type='submit' name='export' value='".$lang['export']."' class='btn'/>";
  2239. echo "</fieldset>";
  2240. echo "</form>";
  2241. echo "<div class='confirm' style='margin-top: 2em'>".sprintf($lang['backup_hint'],
  2242. $params->getLink(array('download' => $currentDB['path'], 'token' => $_SESSION[COOKIENAME.'token']), $lang["backup_hint_linktext"], '', $lang['backup']))."</div>";
  2243. break;
  2244. //- Import table (=table_import)
  2245. case "table_import":
  2246. if(isset($_POST['import']))
  2247. {
  2248. echo "<div class='confirm'>";
  2249. if($importSuccess===true)
  2250. echo $lang['import_suc'];
  2251. else
  2252. echo $lang['err'].': '.htmlencode($importSuccess);
  2253. echo "</div><br/>";
  2254. }
  2255. echo $params->getForm(array('action' => 'table_import'), 'post', true);
  2256. echo "<fieldset style='float:left; width:260px; margin-right:20px;'><legend><b>".$lang['import_into']." ".htmlencode($target_table)."</b></legend>";
  2257. echo "<label><input type='radio' name='import_type' checked='checked' value='sql' onclick='toggleImports(\"sql\");'/> ".$lang['sql']."</label>";
  2258. echo "<br/><label><input type='radio' name='import_type' value='csv' onclick='toggleImports(\"csv\");'/> ".$lang['csv']."</label>";
  2259. echo "</fieldset>";
  2260. echo "<fieldset style='float:left; max-width:350px;' id='importoptions_sql'><legend><b>".$lang['options']."</b></legend>";
  2261. echo $lang['no_opt'];
  2262. echo "</fieldset>";
  2263. echo "<fieldset style='float:left; max-width:350px; display:none;' id='importoptions_csv'><legend><b>".$lang['options']."</b></legend>";
  2264. echo "<input type='hidden' value='".htmlencode($target_table)."' name='single_table'/>";
  2265. echo "<div style='float:left;'>".$lang['fld_terminated']."</div>";
  2266. echo "<input type='text' value=';' name='import_csv_fieldsterminated' style='float:right;'/>";
  2267. echo "<div style='clear:both;'>";
  2268. echo "<div style='float:left;'>".$lang['fld_enclosed']."</div>";
  2269. echo "<input type='text' value='\"' name='import_csv_fieldsenclosed' style='float:right;'/>";
  2270. echo "<div style='clear:both;'>";
  2271. echo "<div style='float:left;'>".$lang['fld_escaped']."</div>";
  2272. echo "<input type='text' value='\' name='import_csv_fieldsescaped' style='float:right;'/>";
  2273. echo "<div style='clear:both;'>";
  2274. echo "<div style='float:left;'>".$lang['rep_null']."</div>";
  2275. echo "<input type='text' value='NULL' name='import_csv_replacenull' style='float:right;'/>";
  2276. echo "<div style='clear:both;'>";
  2277. echo "<label><input type='checkbox' checked='checked' name='import_csv_fieldnames'/> ".$lang['fld_names']."</label>";
  2278. echo "</fieldset>";
  2279. echo "<div style='clear:both;'></div>";
  2280. echo "<br/><br/>";
  2281. echo "<fieldset><legend><b>".$lang['import_f']."</b></legend>";
  2282. echo "<em>".$lang['max_file_size'].": ".number_format(fileUploadMaxSize()/1024/1024)." MiB</em> ".helpLink($lang['help11'])."<br />";
  2283. echo "<input type='file' value='".$lang['choose_f']."' name='file' style='background-color:transparent; border-style:none; margin:0; padding:0' onchange='checkFileSize(this)'/>";
  2284. echo "<input type='submit' value='".$lang['import']."' name='import' class='btn'/>";
  2285. echo "</fieldset>";
  2286. break;
  2287. //- Rename table (=table_rename)
  2288. case "table_rename":
  2289. echo $params->getForm(array('action'=>'table_rename', 'confirm'=>'1'));
  2290. printf($lang['rename_tbl'], htmlencode($target_table));
  2291. echo " <input type='text' name='newname' value='".htmlencode($target_table)."' style='width:200px;'/> <input type='submit' value='".$lang['rename']."' name='rename' class='btn'/>";
  2292. echo "</form>";
  2293. break;
  2294. //- Search table (=table_search)
  2295. case "table_search":
  2296. if(!isset($_GET['search']))
  2297. {
  2298. $tableInfo = $db->getTableInfo($target_table);
  2299. echo $params->getForm(array('action'=>'table_search', 'confirm'=>'1'));
  2300. echo "<table border='0' cellpadding='2' cellspacing='1' class='viewTable'>";
  2301. echo "<tr>";
  2302. echo "<td class='tdheader'>".$lang['fld']."</td>";
  2303. echo "<td class='tdheader'>".$lang['type']."</td>";
  2304. echo "<td class='tdheader'>".$lang['operator']."</td>";
  2305. echo "<td class='tdheader'>".$lang['val']."</td>";
  2306. echo "</tr>";
  2307. for($i=0; $i<sizeof($tableInfo); $i++)
  2308. {
  2309. $field = $tableInfo[$i][1];
  2310. $type = $tableInfo[$i]['type'];
  2311. $typeAffinity = get_type_affinity($type);
  2312. $tdWithClass = "<td class='td".($i%2 ? "1" : "2")."'>";
  2313. $tdWithClassLeft = "<td class='td".($i%2 ? "1" : "2")."' style='text-align:left;'>";
  2314. if(isset($_GET['oldSearch']) && isset($_SESSION[COOKIENAME.'search'][$_GET['oldSearch']]['values'][$field]))
  2315. $value = implode($_SESSION[COOKIENAME.'search'][$_GET['oldSearch']]['values'][$field], ",");
  2316. else
  2317. $value = '';
  2318. if(isset($_GET['oldSearch']) && isset($_SESSION[COOKIENAME.'search'][$_GET['oldSearch']]['operators'][$field]))
  2319. $operator = $_SESSION[COOKIENAME.'search'][$_GET['oldSearch']]['operators'][$field];
  2320. elseif($typeAffinity=="TEXT" || $typeAffinity=="NONE")
  2321. $operator = 'LIKE';
  2322. else
  2323. $operator = '=';
  2324. echo "<tr>";
  2325. echo $tdWithClassLeft;
  2326. echo htmlencode($field);
  2327. echo "</td>";
  2328. echo $tdWithClassLeft;
  2329. echo htmlencode($type);
  2330. echo "</td>";
  2331. echo $tdWithClassLeft;
  2332. echo "<select name='field_".$i."_operator' onchange='checkLike(\"field_".$i."_value\", this.options[this.selectedIndex].value); '>";
  2333. $operators = array('=', '>', '>=', '<', '<=', "= ''", "!= ''", '!=', 'LIKE', 'LIKE%','NOT LIKE', 'IN', 'NOT IN', 'IS NULL', 'IS NOT NULL');
  2334. $operatorsDisplay = array('LIKE%' => 'LIKE %...%', 'IN'=>'IN (..., ...)', 'NOT IN'=>'NOT IN (..., ...)');
  2335. $operatorsNumbersOnly = array('>', '>=', '<', '<=');
  2336. $operatorsTextOnly = array("= ''", "!= ''");
  2337. foreach($operators as $op)
  2338. {
  2339. if($typeAffinity!="INTEGER" && $typeAffinity!="REAL" && $typeAffinity!="NUMERIC" && in_array($op, $operatorsNumbersOnly))
  2340. continue;
  2341. if($typeAffinity!="TEXT" && $typeAffinity!="NONE" && in_array($op, $operatorsTextOnly))
  2342. continue;
  2343. $display = (isset($operatorsDisplay[$op]) ? $operatorsDisplay[$op] : $op);
  2344. echo "<option value='".htmlencode($op)."'".($operator==$op?" selected='selected'":'').">".htmlencode($display)."</option>";
  2345. }
  2346. echo "</select>";
  2347. echo "</td>";
  2348. echo $tdWithClassLeft;
  2349. if($typeAffinity=="INTEGER" || $typeAffinity=="REAL" || $typeAffinity=="NUMERIC")
  2350. echo "<input type='text' id='field_".$i."_value' name='field_".$i."_value' value='".htmlencode($value)."'/>";
  2351. else
  2352. echo "<textarea id='field_".$i."_value' name='field_".$i."_value' rows='1' cols='60'>".htmlencode($value)."</textarea>";
  2353. echo "</td>";
  2354. echo "</tr>";
  2355. }
  2356. echo "<tr>";
  2357. echo "<td class='tdheader' style='text-align:right;' colspan='4'>";
  2358. echo "<input type='submit' value='".$lang['srch']."' class='btn'/>";
  2359. echo "</td>";
  2360. echo "</tr>";
  2361. echo "</table>";
  2362. echo "</form>";
  2363. break;
  2364. }
  2365. elseif(isset($_SESSION[COOKIENAME.'search'][$_GET['search']]))
  2366. {
  2367. $params->search = $_GET['search'];
  2368. $search = $_SESSION[COOKIENAME.'search'][$_GET['search']];
  2369. // NOTICE: we do not break here!! we just do the same now like row_view-action does
  2370. }
  2371. //- Row actions
  2372. //- View row (=row_view)
  2373. case "row_view":
  2374. if(!isset($_GET['startRow']))
  2375. $_GET['startRow'] = 0;
  2376. if(isset($_SESSION[COOKIENAME.'currentTable']) && $_SESSION[COOKIENAME.'currentTable']!=$target_table)
  2377. {
  2378. unset($_SESSION[COOKIENAME.'sortRows']);
  2379. unset($_SESSION[COOKIENAME.'orderRows']);
  2380. }
  2381. if(isset($_GET['viewtype']))
  2382. {
  2383. $_SESSION[COOKIENAME.'viewtype'] = $_GET['viewtype'];
  2384. }
  2385. //- Query execution
  2386. if(!isset($_GET['sort']))
  2387. $_GET['sort'] = NULL;
  2388. if(!isset($_GET['order']))
  2389. $_GET['order'] = NULL;
  2390. $numRows = $params->numRows;
  2391. $startRow = $_GET['startRow'];
  2392. if(isset($_GET['sort']))
  2393. {
  2394. $_SESSION[COOKIENAME.'sortRows'] = $_GET['sort'];
  2395. $_SESSION[COOKIENAME.'currentTable'] = $target_table;
  2396. }
  2397. if(isset($_GET['order']))
  2398. {
  2399. $_SESSION[COOKIENAME.'orderRows'] = $_GET['order'];
  2400. $_SESSION[COOKIENAME.'currentTable'] = $target_table;
  2401. }
  2402. $query = "SELECT * ";
  2403. // select the primary key column(s) last (ROWID if there is no PK).
  2404. // this will be used to identify rows, e.g. when editing/deleting rows
  2405. $primary_key = $db->getPrimaryKey($target_table);
  2406. foreach($primary_key as $pk)
  2407. {
  2408. $query.= ', '.$db->quote_id($pk);
  2409. $query.= ', typeof('.$db->quote_id($pk).')';
  2410. }
  2411. $query .= " FROM ".$db->quote_id($target_table);
  2412. $queryDisp = "SELECT * FROM ".$db->quote_id($target_table);
  2413. $queryCount = "SELECT COUNT(*) AS count FROM ".$db->quote_id($target_table);
  2414. $queryAdd = "";
  2415. if(isset($search) && isset($search['where']))
  2416. {
  2417. $queryAdd = $search['where'];
  2418. $queryCount .= $search['where'];
  2419. }
  2420. if(isset($_SESSION[COOKIENAME.'sortRows']))
  2421. $queryAdd .= " ORDER BY ".$db->quote_id($_SESSION[COOKIENAME.'sortRows']);
  2422. if(isset($_SESSION[COOKIENAME.'orderRows']))
  2423. $queryAdd .= " ".$_SESSION[COOKIENAME.'orderRows'];
  2424. $queryAdd .= " LIMIT ".$startRow.", ".$numRows;
  2425. $query .= $queryAdd;
  2426. $queryDisp .= $queryAdd;
  2427. $resultRows = $db->select($queryCount);
  2428. $totalRows = $resultRows['count'];
  2429. $shownRows = min($resultRows['count']-$startRow, $numRows);
  2430. //- HTML: pagination buttons
  2431. $lastPage = intval($totalRows / $params->numRows);
  2432. $remainder = intval($totalRows % $params->numRows);
  2433. if($remainder==0)
  2434. $remainder = $params->numRows;
  2435. echo "<div style=''>";
  2436. //previous button
  2437. if($_GET['startRow']>0)
  2438. {
  2439. echo "<div style='float:left;'>";
  2440. echo $params->getForm(array('action'=>$_GET['action']),'get');
  2441. echo "<input type='hidden' name='startRow' value='0'/>";
  2442. echo "<input type='submit' value='&larr;&larr;' class='btn'/> ";
  2443. echo "</form>";
  2444. echo "</div>";
  2445. echo "<div style='float:left; overflow:hidden; margin-right:20px;'>";
  2446. echo $params->getForm(array('action'=>$_GET['action']),'get');
  2447. echo "<input type='hidden' name='startRow' value='".max(0,intval($_GET['startRow']-$params->numRows))."'/>";
  2448. echo "<input type='submit' value='&larr;' class='btn'/> ";
  2449. echo "</form>";
  2450. echo "</div>";
  2451. }
  2452. //show certain number buttons
  2453. echo "<div style='float:left;'>";
  2454. echo $params->getForm(array('action'=>$_GET['action'], 'numRows'=>null),'get');
  2455. echo "<input type='submit' value='".$lang['show']." : ' name='show' class='btn'/> ";
  2456. echo "<input type='text' name='numRows' style='width:50px;' value='".$params->numRows."'/> ";
  2457. echo $lang['rows_records'];
  2458. if(intval($_GET['startRow']+$params->numRows) < $totalRows)
  2459. echo "<input type='text' name='startRow' style='width:90px;' value='".intval($_GET['startRow']+$params->numRows)."'/>";
  2460. else
  2461. echo "<input type='text' name='startRow' style='width:90px;' value='0'/> ";
  2462. echo $lang['as_a'];
  2463. echo " <select name='viewtype'>";
  2464. if(!isset($_SESSION[COOKIENAME.'viewtype']) || $_SESSION[COOKIENAME.'viewtype']=="table")
  2465. {
  2466. echo "<option value='table' selected='selected'>".$lang['tbl']."</option>";
  2467. echo "<option value='chart'>".$lang['chart']."</option>";
  2468. }
  2469. else
  2470. {
  2471. echo "<option value='table'>".$lang['tbl']."</option>";
  2472. echo "<option value='chart' selected='selected'>".$lang['chart']."</option>";
  2473. }
  2474. echo "</select>";
  2475. echo "</form>";
  2476. echo "</div>";
  2477. //next button
  2478. if(intval($_GET['startRow']+$params->numRows)<$totalRows)
  2479. {
  2480. echo "<div style='float:left; margin-left:20px; '>";
  2481. echo $params->getForm(array('action'=>$_GET['action']),'get');
  2482. echo "<input type='hidden' name='startRow' value='".intval($_GET['startRow']+$params->numRows)."'/>";
  2483. echo "<input type='submit' value='&rarr;' class='btn'/> ";
  2484. echo "</form>";
  2485. echo "</div>";
  2486. echo "<div style='float:left; '>";
  2487. echo $params->getForm(array('action'=>$_GET['action']),'get');
  2488. echo "<input type='hidden' name='startRow' value='".intval($totalRows-$remainder)."'/>";
  2489. echo "<input type='submit' value='&rarr;&rarr;' class='btn'/> ";
  2490. echo "</form>";
  2491. echo "</div>";
  2492. }
  2493. echo "<div style='clear:both;'></div>";
  2494. echo "</div>";
  2495. //- Show results
  2496. if($shownRows>0)
  2497. {
  2498. $queryTimer = new MicroTimer();
  2499. $table_result = $db->query($query);
  2500. $queryTimer->stop();
  2501. echo "<br/><div class='confirm'>";
  2502. echo "<b>".$lang['showing_rows']." ".$startRow." - ".($startRow + $shownRows-1).", ".$lang['total'].": ".$totalRows." ";
  2503. printf($lang['query_time'], $queryTimer);
  2504. echo "</b><br/>";
  2505. echo "<span style='font-size:11px;'>".htmlencode($queryDisp)."</span>";
  2506. echo "</div><br/>";
  2507. if($target_table_type == 'view')
  2508. {
  2509. echo sprintf($lang['readonly_tbl'], htmlencode($target_table))." <a href='https://en.wikipedia.org/wiki/View_(SQL)' target='_blank'>https://en.wikipedia.org/wiki/View_(SQL)</a>";
  2510. echo "<br/><br/>";
  2511. }
  2512. $tableInfo = $db->getTableInfo($target_table);
  2513. $pkFirstCol = sizeof($tableInfo)+1;
  2514. //- Table view
  2515. if(!isset($_SESSION[COOKIENAME.'viewtype']) || $_SESSION[COOKIENAME.'viewtype']=="table")
  2516. {
  2517. echo $params->getForm(array('action'=>'row_editordelete'), 'post', false, 'checkForm');
  2518. echo "<table border='0' cellpadding='2' cellspacing='1' class='viewTable'>";
  2519. echo "<tr>";
  2520. echo "<td colspan='3' class='tdheader' style='text-align:center'>";
  2521. echo "<a href='".$params->getURL(array('action'=>$_GET['action'], 'fulltexts'=>($params->fulltexts?0:1) ))."' title='".$lang[($params->fulltexts?'no_full_texts':'full_texts')]."'>";
  2522. echo "<b>&".($params->fulltexts?'r':'l')."arr;</b>&nbsp;T&nbsp;<b>&".($params->fulltexts?'l':'r')."arr;</b></a>";
  2523. echo "</td>";
  2524. for($i=0; $i<sizeof($tableInfo); $i++)
  2525. {
  2526. echo "<td class='tdheader'>";
  2527. if(isset($_SESSION[COOKIENAME.'sortRows']))
  2528. $orderTag = ($_SESSION[COOKIENAME.'sortRows']==$tableInfo[$i]['name'] && $_SESSION[COOKIENAME.'orderRows']=="ASC") ? "DESC" : "ASC";
  2529. else
  2530. $orderTag = "ASC";
  2531. echo $params->getLink(array('action'=>$_GET['action'], 'sort'=>$tableInfo[$i]['name'], 'order'=>$orderTag ), htmlencode($tableInfo[$i]['name']));
  2532. if(isset($_SESSION[COOKIENAME.'sortRows']) && $_SESSION[COOKIENAME.'sortRows']==$tableInfo[$i]['name'])
  2533. echo (($_SESSION[COOKIENAME.'orderRows']=="ASC") ? " <b>&uarr;</b>" : " <b>&darr;</b>");
  2534. echo "</td>";
  2535. }
  2536. echo "</tr>";
  2537. for($i=0; $row = $db->fetch($table_result, 'num'); $i++)
  2538. {
  2539. // -g-> $pk will always be the last columns in each row of the array because we are doing "SELECT *, PK_1, typeof(PK_1), PK2, typeof(PK_2), ... FROM ..."
  2540. $pk_arr = array();
  2541. for($col = $pkFirstCol; array_key_exists($col, $row); $col=$col+2)
  2542. {
  2543. // in $col we have the type and in $col-1 the value
  2544. if($row[$col]=='integer' || $row[$col]=='real')
  2545. // json encode as int or float, not string
  2546. $pk_arr[] = $row[$col-1]+0;
  2547. else
  2548. // encode as json string
  2549. $pk_arr[] = $row[$col-1];
  2550. }
  2551. $pk = json_encode($pk_arr);
  2552. $tdWithClass = "<td class='td".($i%2 ? "1" : "2")."'>";
  2553. $tdWithClassLeft = "<td class='td".($i%2 ? "1" : "2")."' style='text-align:left;'>";
  2554. echo "<tr>";
  2555. if($target_table_type == 'table' && $db->isWritable() && $db->isDirWritable())
  2556. {
  2557. echo $tdWithClass;
  2558. echo "<input type='checkbox' name='check[]' value='".htmlencode($pk)."' id='check_".htmlencode($i)."'/>";
  2559. echo "</td>";
  2560. echo $tdWithClass;
  2561. // -g-> Here, we need to put the PK in as the link for both the edit and delete.
  2562. echo $params->getLink(array('action'=>'row_editordelete', 'pk'=>$pk, 'type'=>'edit'),"<span>".$lang['edit']."</span>",'edit', $lang['edit']);
  2563. echo "</td>";
  2564. echo $tdWithClass;
  2565. echo $params->getLink(array('action'=>'row_editordelete', 'pk'=>$pk, 'type'=>'delete'),"<span>".$lang['del']."</span>",'delete', $lang['del']);
  2566. echo "</td>";
  2567. } else {
  2568. echo "<td class='td".($i%2 ? "1" : "2")."' colspan='3'></td>";
  2569. }
  2570. for($j=0; $j<sizeof($tableInfo); $j++)
  2571. {
  2572. $typeAffinity = get_type_affinity($tableInfo[$j]['type']);
  2573. if($typeAffinity=="INTEGER" || $typeAffinity=="REAL" || $typeAffinity=="NUMERIC")
  2574. echo $tdWithClass;
  2575. else
  2576. echo $tdWithClassLeft;
  2577. if($row[$j]==="")
  2578. echo "&nbsp;";
  2579. elseif($row[$j]===NULL)
  2580. echo "<i class='null'>NULL</i>";
  2581. elseif(preg_match('/^BLOB/i', $tableInfo[$j]['type']))
  2582. {
  2583. echo "<div style='float:left; text-align: left; padding-right:2em'>";
  2584. echo $params->getLink(array('action'=>'row_get_blob', 'confirm'=>1, 'pk'=>$pk, 'column'=>$tableInfo[$j]['name'], 'download_blob'=>1),$lang["download"]).' | ';
  2585. echo $params->getLink(array('action'=>'row_get_blob', 'confirm'=>1, 'pk'=>$pk, 'column'=>$tableInfo[$j]['name'], 'download_blob'=>0),$lang["open_in_browser"],'','','_blank');
  2586. echo "</div><div style='float:right; text-align: right'>";
  2587. echo 'Size: '.number_format(strlen($row[$j])).' Bytes';
  2588. echo "</div>";
  2589. }
  2590. elseif(isset($search))
  2591. echo markSearchWords(subString($row[$j]),$tableInfo[$j]['name'], $search);
  2592. else
  2593. echo htmlencode(subString($row[$j]));
  2594. echo "</td>";
  2595. }
  2596. echo "</tr>";
  2597. }
  2598. echo "</table>";
  2599. if($target_table_type == 'table' && $db->isWritable() && $db->isDirWritable())
  2600. {
  2601. echo "<a onclick='checkAll()'>".$lang['chk_all']."</a> / <a onclick='uncheckAll()'>".$lang['unchk_all']."</a> <i>".$lang['with_sel'].":</i> ";
  2602. echo "<select name='type'>";
  2603. echo "<option value='edit'>".$lang['edit']."</option>";
  2604. echo "<option value='delete'>".$lang['del']."</option>";
  2605. echo "</select> ";
  2606. echo "<input type='submit' value='".$lang['go']."' name='massGo' class='btn'/>";
  2607. }
  2608. echo "</form>";
  2609. }
  2610. else
  2611. //- Chart view
  2612. {
  2613. if(!isset($_SESSION[COOKIENAME.$target_table.'chartlabels']))
  2614. {
  2615. // No label-column set. Try to pick a text-column as label-column.
  2616. for($i=0; $i<sizeof($tableInfo); $i++)
  2617. {
  2618. if(get_type_affinity($tableInfo[$i]['type'])=='TEXT')
  2619. {
  2620. $_SESSION[COOKIENAME.$target_table.'chartlabels'] = $i;
  2621. break;
  2622. }
  2623. }
  2624. }
  2625. if(!isset($_SESSION[COOKIENAME.$target_table.'chartlabels']))
  2626. // no text column found, use the first column
  2627. $_SESSION[COOKIENAME.$target_table.'chartlabels'] = 0;
  2628. if(!isset($_SESSION[COOKIENAME.$target_table.'chartvalues']))
  2629. {
  2630. // No value-column set. Pick the first numeric column if possible.
  2631. // If not possible, pick the first column that is not the label-column.
  2632. $potential_value_column = null;
  2633. for($i=0; $i<sizeof($tableInfo); $i++)
  2634. {
  2635. if($potential_value_column===null && $i != $_SESSION[COOKIENAME.$target_table.'chartlabels'])
  2636. // the first column (of any type) that is not the label-column
  2637. $potential_value_column = $i;
  2638. // check if the col is numeric
  2639. $typeAffinity = get_type_affinity($tableInfo[$i]['type']);
  2640. if($typeAffinity=='INTEGER' || $typeAffinity=='REAL' || $typeAffinity=='NUMERIC')
  2641. {
  2642. // this is defined as a numeric column, so prefer this as a value column over $potential_value_column
  2643. $_SESSION[COOKIENAME.$target_table.'chartvalues'] = $i;
  2644. break;
  2645. }
  2646. }
  2647. if(!isset($_SESSION[COOKIENAME.$target_table.'chartvalues']))
  2648. {
  2649. // we did not find a numeric column
  2650. if($potential_value_column!==null)
  2651. // use the $potential_value_column, i.e. the second column which is not the label-column
  2652. $_SESSION[COOKIENAME.$target_table.'chartvalues'] = $potential_value_column;
  2653. else
  2654. // it's hopeless, there is only 1 column
  2655. $_SESSION[COOKIENAME.$target_table.'chartvalues'] = 0;
  2656. }
  2657. }
  2658. if(!isset($_SESSION[COOKIENAME.'charttype']))
  2659. $_SESSION[COOKIENAME.'charttype'] = 'bar';
  2660. if(isset($_POST['chartsettings']))
  2661. {
  2662. $_SESSION[COOKIENAME.'charttype'] = $_POST['charttype'];
  2663. $_SESSION[COOKIENAME.$target_table.'chartlabels'] = $_POST['chartlabels'];
  2664. $_SESSION[COOKIENAME.$target_table.'chartvalues'] = $_POST['chartvalues'];
  2665. }
  2666. //- Chart javascript code
  2667. ?>
  2668. <script type='text/javascript' src='https://www.google.com/jsapi'></script>
  2669. <script type='text/javascript'>
  2670. google.load('visualization', '1.0', {'packages':['corechart']});
  2671. google.setOnLoadCallback(drawChart);
  2672. function drawChart()
  2673. {
  2674. var data = new google.visualization.DataTable();
  2675. data.addColumn('string', '<?php echo $tableInfo[$_SESSION[COOKIENAME.$target_table.'chartlabels']]['name']; ?>');
  2676. data.addColumn('number', '<?php echo $tableInfo[$_SESSION[COOKIENAME.$target_table.'chartvalues']]['name']; ?>');
  2677. data.addRows([
  2678. <?php
  2679. for($i=0; $row = $db->fetch($table_result); $i++)
  2680. {
  2681. $label = str_replace("'", "", htmlencode($row[$_SESSION[COOKIENAME.$target_table.'chartlabels']]));
  2682. $value = htmlencode($row[$_SESSION[COOKIENAME.$target_table.'chartvalues']]);
  2683. if($value==NULL || $value=="")
  2684. $value = 0;
  2685. echo "['".$label."', ".$value."]";
  2686. if($i<$totalRows-1)
  2687. echo ",";
  2688. }
  2689. $height = ($totalRows+1) * 30;
  2690. if($height>1000)
  2691. $height = 1000;
  2692. else if($height<300)
  2693. $height = 300;
  2694. if($_SESSION[COOKIENAME.'charttype']=="pie")
  2695. $height = 800;
  2696. ?>
  2697. ]);
  2698. var chartWidth = document.getElementById("main_column").offsetWidth - document.getElementById("chartsettingsbox").offsetWidth - 100;
  2699. if(chartWidth>1000)
  2700. chartWidth = 1000;
  2701. var options =
  2702. {
  2703. 'width':chartWidth,
  2704. 'height':<?php echo $height; ?>,
  2705. 'title':'<?php echo $tableInfo[$_SESSION[COOKIENAME.$target_table.'chartlabels']]['name']." vs ".$tableInfo[$_SESSION[COOKIENAME.$target_table.'chartvalues']]['name']; ?>'
  2706. };
  2707. <?php
  2708. if($_SESSION[COOKIENAME.'charttype']=="bar")
  2709. echo "var chart = new google.visualization.BarChart(document.getElementById('chart_div'));";
  2710. else if($_SESSION[COOKIENAME.'charttype']=="pie")
  2711. echo "var chart = new google.visualization.PieChart(document.getElementById('chart_div'));";
  2712. else
  2713. echo "var chart = new google.visualization.LineChart(document.getElementById('chart_div'));";
  2714. ?>
  2715. chart.draw(data, options);
  2716. }
  2717. </script>
  2718. <div id="chart_div" style="float:left;"><?php echo $lang['no_chart']; ?></div>
  2719. <?php
  2720. echo "<fieldset style='float:right; text-align:center;' id='chartsettingsbox'><legend><b>Chart Settings</b></legend>";
  2721. echo $params->getForm(array('action'=>$_GET['action']));
  2722. echo $lang['chart_type'].": <select name='charttype'>";
  2723. echo "<option value='bar'";
  2724. if($_SESSION[COOKIENAME.'charttype']=="bar")
  2725. echo " selected='selected'";
  2726. echo ">".$lang['chart_bar']."</option>";
  2727. echo "<option value='pie'";
  2728. if($_SESSION[COOKIENAME.'charttype']=="pie")
  2729. echo " selected='selected'";
  2730. echo ">".$lang['chart_pie']."</option>";
  2731. echo "<option value='line'";
  2732. if($_SESSION[COOKIENAME.'charttype']=="line")
  2733. echo " selected='selected'";
  2734. echo ">".$lang['chart_line']."</option>";
  2735. echo "</select>";
  2736. echo "<br/><br/>";
  2737. echo $lang['lbl'].": <select name='chartlabels'>";
  2738. for($i=0; $i<sizeof($tableInfo); $i++)
  2739. {
  2740. if(isset($_SESSION[COOKIENAME.$target_table.'chartlabels']) && $_SESSION[COOKIENAME.$target_table.'chartlabels']==$i)
  2741. echo "<option value='".$i."' selected='selected'>".htmlencode($tableInfo[$i]['name'])."</option>";
  2742. else
  2743. echo "<option value='".$i."'>".htmlencode($tableInfo[$i]['name'])."</option>";
  2744. }
  2745. echo "</select>";
  2746. echo "<br/><br/>";
  2747. echo $lang['val'].": <select name='chartvalues'>";
  2748. for($i=0; $i<sizeof($tableInfo); $i++)
  2749. {
  2750. if(isset($_SESSION[COOKIENAME.$target_table.'chartvalues']) && $_SESSION[COOKIENAME.$target_table.'chartvalues']==$i)
  2751. echo "<option value='".$i."' selected='selected'>".htmlencode($tableInfo[$i]['name'])."</option>";
  2752. else
  2753. echo "<option value='".$i."'>".htmlencode($tableInfo[$i]['name'])."</option>";
  2754. }
  2755. echo "</select>";
  2756. echo "<br/><br/>";
  2757. echo "<input type='submit' name='chartsettings' value='".$lang['update']."' class='btn'/>";
  2758. echo "</form>";
  2759. echo "</fieldset>";
  2760. echo "<div style='clear:both;'></div>";
  2761. //end chart view
  2762. }
  2763. }
  2764. else //no rows - do nothing
  2765. {
  2766. echo "<br/><div class='confirm'>";
  2767. if(isset($search) || $totalRows>0)
  2768. echo $lang['no_rows']."<br/><br/>";
  2769. elseif($target_table_type == 'table')
  2770. echo $lang['empty_tbl']." ".$params->getLink(array('action'=>'row_create'), $lang['click']) ." ".$lang['insert_rows'].'<br/><br/>';
  2771. echo "<span style='font-size:11px;'>".htmlencode($queryDisp)."</span>";
  2772. echo "</div><br/>";
  2773. }
  2774. if(isset($search))
  2775. echo "<br/><br/>".$params->getLink(array('action'=>'table_search','search'=>null,'oldSearch' => (isset($_GET['search'])?$_GET['search']:null)), $lang['srch_again']);
  2776. break;
  2777. //- Create new row (=row_create)
  2778. case "row_create":
  2779. echo $params->getForm(array('action'=>'row_create'), 'get');
  2780. echo $lang['restart_insert'];
  2781. echo " <select name='newRows'>";
  2782. for($i=1; $i<=40; $i++)
  2783. {
  2784. if(isset($_GET['newRows']) && $_GET['newRows']==$i)
  2785. echo "<option value='".$i."' selected='selected'>".$i."</option>";
  2786. else
  2787. echo "<option value='".$i."'>".$i."</option>";
  2788. }
  2789. echo "</select> ";
  2790. echo $lang['rows'];
  2791. echo " <input type='submit' value='".$lang['go']."' class='btn'/>";
  2792. echo "</form>";
  2793. echo "<br/>";
  2794. echo $params->getForm(array('action'=>'row_create','confirm'=>'1'), 'post', true);
  2795. $tableInfo = $db->getTableInfo($target_table);
  2796. if(isset($_GET['newRows']))
  2797. $num = $_GET['newRows'];
  2798. else
  2799. $num = 1;
  2800. echo "<input type='hidden' name='newRows' value='".$num."'/>";
  2801. for($j=0; $j<$num; $j++)
  2802. {
  2803. if($j>0)
  2804. echo "<label><input type='checkbox' value='ignore' name='".$j.":ignore' id='row_".$j."_ignore' checked='checked'/> ".$lang['ignore']."</label><br/>";
  2805. echo "<table border='0' cellpadding='2' cellspacing='1' class='viewTable'>";
  2806. echo "<tr>";
  2807. echo "<td class='tdheader'>".$lang['fld']."</td>";
  2808. echo "<td class='tdheader'>".$lang['type']."</td>";
  2809. echo "<td class='tdheader'>".$lang['func']."</td>";
  2810. echo "<td class='tdheader'>Null</td>";
  2811. echo "<td class='tdheader'>".$lang['val']."</td>";
  2812. echo "</tr>";
  2813. for($i=0; $i<sizeof($tableInfo); $i++)
  2814. {
  2815. $field = $tableInfo[$i]['name'];
  2816. $type = strtoupper($tableInfo[$i]['type']);
  2817. $typeAffinity = get_type_affinity($type);
  2818. if($tableInfo[$i]['dflt_value'] === "NULL")
  2819. $value = NULL;
  2820. else
  2821. $value = htmlencode(trim(trim($tableInfo[$i]['dflt_value']), "'"));
  2822. $tdWithClassLeft = "<td class='td".($i%2 ? "1" : "2")."' style='text-align:left;'>";
  2823. echo "<tr>";
  2824. echo $tdWithClassLeft;
  2825. echo htmlencode($field);
  2826. echo "</td>";
  2827. echo $tdWithClassLeft;
  2828. echo htmlencode($type);
  2829. echo "</td>";
  2830. echo $tdWithClassLeft;
  2831. echo "<select name='function_".$i."[]' onchange='notNull(\"row_".$j."_field_".$i."_null\");'>";
  2832. echo "<option value=''>&nbsp;</option>";
  2833. foreach (array_merge($sqlite_functions, $custom_functions) as $f) {
  2834. echo "<option value='".htmlencode($f)."'>".htmlencode($f)."</option>";
  2835. }
  2836. echo "</select>";
  2837. echo "</td>";
  2838. echo $tdWithClassLeft;
  2839. if($tableInfo[$i]['notnull']==0)
  2840. {
  2841. if($value===NULL)
  2842. echo "<input type='checkbox' name='".$i."_null[]' id='row_".$j."_field_".$i."_null' checked='checked' onclick='disableText(this, \"row_".$j."_field_".$i."_value\");'/>";
  2843. else
  2844. echo "<input type='checkbox' name='".$i."_null[]' id='row_".$j."_field_".$i."_null' onclick='disableText(this, \"row_".$j."_field_".$i."_value\");'/>";
  2845. }
  2846. echo "</td>";
  2847. echo $tdWithClassLeft;
  2848. if($typeAffinity=="INTEGER" || $typeAffinity=="REAL" || $typeAffinity=="NUMERIC")
  2849. echo "<input type='text' id='row_".$j."_field_".$i."_value' name='".$j.":".$i."' value='".$value."' onblur='changeIgnore(this, \"row_".$j."_ignore\");' onclick='notNull(\"row_".$j."_field_".$i."_null\");'/>";
  2850. elseif(preg_match('/^BLOB/', $type))
  2851. echo "<input type='file' id='row_".$j."_field_".$i."_value' name='".$j.":".$i."' onblur='changeIgnore(this, \"row_".$j."_ignore\");' onclick='notNull(\"row_".$j."_field_".$i."_null\");'/>";
  2852. else
  2853. echo "<textarea id='row_".$j."_field_".$i."_value' name='".$j.":".$i."' rows='5' cols='60' onclick='notNull(\"row_".$j."_field_".$i."_null\");' onblur='changeIgnore(this, \"row_".$j."_ignore\");'>".$value."</textarea>";
  2854. echo "</td>";
  2855. echo "</tr>";
  2856. }
  2857. echo "<tr>";
  2858. echo "<td class='tdheader' style='text-align:right;' colspan='5'>";
  2859. echo "<input type='submit' value='".$lang['insert']."' class='btn'/>";
  2860. echo "</td>";
  2861. echo "</tr>";
  2862. echo "</table><br/>";
  2863. }
  2864. echo "</form>";
  2865. break;
  2866. //- Edit or delete row (=row_editordelete)
  2867. case "row_editordelete":
  2868. if(isset($_POST['check']))
  2869. $pks = $_POST['check'];
  2870. else if(isset($_GET['pk']))
  2871. $pks = array($_GET['pk']);
  2872. else $pks[0] = "";
  2873. $str = implode(', ', $pks);
  2874. if($str=="") //nothing was selected so show an error
  2875. {
  2876. echo "<div class='confirm'>";
  2877. echo $lang['err'].": ".$lang['no_sel'];
  2878. echo "</div>";
  2879. echo "<br/><br/>".$params->getLink(array('action'=>'row_view'),$lang['return']);
  2880. }
  2881. else
  2882. {
  2883. if((isset($_POST['type']) && $_POST['type']=="edit") || (isset($_GET['type']) && $_GET['type']=="edit")) //edit
  2884. {
  2885. echo $params->getForm(array('action'=>'row_edit', 'confirm'=>'1', 'pk'=>json_encode($pks)),'post',true);
  2886. $tableInfo = $db->getTableInfo($target_table);
  2887. $primary_key = $db->getPrimaryKey($target_table);
  2888. for($j=0; $j<sizeof($pks); $j++)
  2889. {
  2890. $query = "SELECT * FROM ".$db->quote_id($target_table)." WHERE " . $db->wherePK($target_table, json_decode($pks[$j]));
  2891. $result1 = $db->select($query, 'num');
  2892. echo "<table border='0' cellpadding='2' cellspacing='1' class='viewTable'>";
  2893. echo "<tr>";
  2894. echo "<td class='tdheader'>".$lang['fld']."</td>";
  2895. echo "<td class='tdheader'>".$lang['type']."</td>";
  2896. echo "<td class='tdheader'>".$lang['func']."</td>";
  2897. echo "<td class='tdheader'>Null</td>";
  2898. echo "<td class='tdheader'>".$lang['val']."</td>";
  2899. echo "</tr>";
  2900. for($i=0; $i<sizeof($tableInfo); $i++)
  2901. {
  2902. $field = $tableInfo[$i]['name'];
  2903. $type = strtoupper($tableInfo[$i]['type']);
  2904. $typeAffinity = get_type_affinity($type);
  2905. $value = $result1[$i];
  2906. $tdWithClassLeft = "<td class='td".($i%2 ? "1" : "2")."' style='text-align:left;'>";
  2907. echo "<tr>";
  2908. echo $tdWithClassLeft;
  2909. echo htmlencode($field);
  2910. echo "</td>";
  2911. echo $tdWithClassLeft;
  2912. echo htmlencode($type);
  2913. echo "</td>";
  2914. echo $tdWithClassLeft;
  2915. echo "<select name='function_".$i."[]' onchange='notNull(\"row_".$j."_field_".$i."_null\");'>";
  2916. echo "<option value=''></option>";
  2917. foreach (array_merge($sqlite_functions, $custom_functions) as $f) {
  2918. echo "<option value='".htmlencode($f)."'>".htmlencode($f)."</option>";
  2919. }
  2920. echo "</select>";
  2921. echo "</td>";
  2922. echo $tdWithClassLeft;
  2923. if($tableInfo[$i]['notnull']==0)
  2924. {
  2925. if($value===NULL)
  2926. echo "<input type='checkbox' name='".$i."_null[]' id='row_".$j."_field_".$i."_null' checked='checked' onclick='disableText(this, \"row_".$j."_field_".$i."_value\");'/>";
  2927. else
  2928. echo "<input type='checkbox' name='".$i."_null[]' id='row_".$j."_field_".$i."_null' onclick='disableText(this, \"row_".$j."_field_".$i."_value\");'/>";
  2929. }
  2930. echo "</td>";
  2931. echo $tdWithClassLeft;
  2932. if($typeAffinity=="INTEGER" || $typeAffinity=="REAL" || $typeAffinity=="NUMERIC")
  2933. echo "<input type='text' id='row_".$j."_field_".$i."_value' name='".$i."[]' value='".htmlencode($value)."' onblur='changeIgnore(this, \"".$j."\", \"row_".$j."_field_".$i."_null\")' />";
  2934. elseif(preg_match('/^BLOB/', $type))
  2935. {
  2936. if($value!==NULL)
  2937. {
  2938. echo "<input type='radio' name='row_".$j."_field_".$i."_blob_use' value='old' checked='checked'>";
  2939. echo $params->getLink(array('action'=>'row_get_blob', 'confirm'=>1, 'pk'=>$pks[$j], 'column'=>$field, 'download_blob'=>1),$lang["download"]).' | ';
  2940. echo $params->getLink(array('action'=>'row_get_blob', 'confirm'=>1, 'pk'=>$pks[$j], 'column'=>$field, 'download_blob'=>0),$lang["open_in_browser"],'','','_blank').'<br/>';
  2941. echo "<input type='radio' name='row_".$j."_field_".$i."_blob_use' value='new' id='row_".$j."_field_".$i."_blob_new'>";
  2942. }
  2943. echo "<input type='file' id='row_".$j."_field_".$i."_value' name='".$j.":".$i."'
  2944. onblur='changeIgnore(this, \"row_".$j."_ignore\");'
  2945. onchange='document.getElementById(\"row_".$j."_field_".$i."_blob_new\").checked=true;'
  2946. onclick='notNull(\"row_".$j."_field_".$i."_null\");'
  2947. ".($value===NULL?" disabled='disabled'":"")."/>";
  2948. }
  2949. else
  2950. echo "<textarea id='row_".$j."_field_".$i."_value' name='".$i."[]' rows='1' cols='60' class='".htmlencode($field)."_textarea' onblur='changeIgnore(this, \"".$j."\", \"row_".$j."_field_".$i."_null\")'>".htmlencode($value)."</textarea>";
  2951. echo "</td>";
  2952. echo "</tr>";
  2953. }
  2954. echo "<tr>";
  2955. echo "<td class='tdheader' style='text-align:right;' colspan='5'>";
  2956. // Note: the 'Save changes' button must be first in the code so it is the one used when submitting the form with the Enter key (issue #215)
  2957. echo "<input type='submit' value='".$lang['save_ch']."' class='btn'/> ";
  2958. echo "<input type='submit' name='new_row' value='".$lang['new_insert']."' class='btn'/> ";
  2959. echo $params->getLink(array('action'=>'row_view'), $lang['cancel']);
  2960. echo "</td>";
  2961. echo "</tr>";
  2962. echo "</table>";
  2963. echo "<br/>";
  2964. }
  2965. echo "</form>";
  2966. }
  2967. else //delete
  2968. {
  2969. echo $params->getForm(array('action'=>'row_delete', 'confirm'=>'1', 'pk'=>json_encode($pks)));
  2970. echo "<div class='confirm'>";
  2971. printf($lang['ques_del_rows'], htmlencode($str), htmlencode($target_table));
  2972. echo "<br/><br/>";
  2973. echo "<input type='submit' value='".$lang['confirm']."' class='btn'/> ";
  2974. echo $params->getLink(array('action'=>'row_view'), $lang['cancel']);
  2975. echo "</div>";
  2976. }
  2977. }
  2978. break;
  2979. //- Column actions
  2980. //- View table structure (=column_view)
  2981. case "column_view":
  2982. $tableInfo = $db->getTableInfo($target_table);
  2983. echo $params->getForm(array('action'=>'column_confirm'), 'get', false, 'checkForm');
  2984. echo "<table border='0' cellpadding='2' cellspacing='1' class='viewTable'>";
  2985. echo "<tr>";
  2986. if($target_table_type == 'table' && $db->isWritable() && $db->isDirWritable())
  2987. echo "<td colspan='3'></td>";
  2988. echo "<td class='tdheader'>".$lang['col']." #</td>";
  2989. echo "<td class='tdheader'>".$lang['fld']."</td>";
  2990. echo "<td class='tdheader'>".$lang['type']."</td>";
  2991. echo "<td class='tdheader'>".$lang['not_null']."</td>";
  2992. echo "<td class='tdheader'>".$lang['def_val']."</td>";
  2993. echo "<td class='tdheader'>".$lang['prim_key']."</td>";
  2994. echo "</tr>";
  2995. $noPrimaryKey = true;
  2996. for($i=0; $i<sizeof($tableInfo); $i++)
  2997. {
  2998. $colVal = $tableInfo[$i][0];
  2999. $fieldVal = $tableInfo[$i][1];
  3000. $typeVal = $tableInfo[$i]['type'];
  3001. $notnullVal = $tableInfo[$i][3];
  3002. $defaultVal = $tableInfo[$i][4];
  3003. $primarykeyVal = $tableInfo[$i][5];
  3004. if(intval($notnullVal)!=0)
  3005. $notnullVal = $lang['yes'];
  3006. else
  3007. $notnullVal = $lang['no'];
  3008. if(intval($primarykeyVal)!=0)
  3009. {
  3010. $primarykeyVal = $lang['yes'];
  3011. $noPrimaryKey = false;
  3012. }
  3013. else
  3014. $primarykeyVal = $lang['no'];
  3015. $tdWithClass = "<td class='td".($i%2 ? "1" : "2")."'>";
  3016. $tdWithClassLeft = "<td class='td".($i%2 ? "1" : "2")."' style='text-align:left;'>";
  3017. echo "<tr>";
  3018. if($target_table_type == 'table' && $db->isWritable() && $db->isDirWritable())
  3019. {
  3020. echo $tdWithClass;
  3021. echo "<input type='checkbox' name='check[]' value='".htmlencode($fieldVal)."' id='check_".$i."'/>";
  3022. echo "</td>";
  3023. echo $tdWithClass;
  3024. echo $params->getLink(array('action'=>'column_edit', 'pk'=>$fieldVal),"<span>".$lang['edit']."</span>",'edit', $lang['edit']);
  3025. echo "</td>";
  3026. echo $tdWithClass;
  3027. echo $params->getLink(array('action'=>'column_confirm', 'action2'=>'column_delete', 'pk'=>$fieldVal),"<span>".$lang['del']."</span>",'delete', $lang['del']);
  3028. echo "</td>";
  3029. }
  3030. echo $tdWithClass;
  3031. echo htmlencode($colVal);
  3032. echo "</td>";
  3033. echo $tdWithClassLeft;
  3034. echo htmlencode($fieldVal);
  3035. echo "</td>";
  3036. echo $tdWithClassLeft;
  3037. echo htmlencode($typeVal);
  3038. echo "</td>";
  3039. echo $tdWithClassLeft;
  3040. echo htmlencode($notnullVal);
  3041. echo "</td>";
  3042. echo $tdWithClassLeft;
  3043. if($defaultVal===NULL)
  3044. echo "<i class='null'>".$lang['none']."</i>";
  3045. elseif($defaultVal==="NULL")
  3046. echo "<i class='null'>NULL</i>";
  3047. else
  3048. echo htmlencode($defaultVal);
  3049. echo "</td>";
  3050. echo $tdWithClassLeft;
  3051. echo htmlencode($primarykeyVal);
  3052. echo "</td>";
  3053. echo "</tr>";
  3054. }
  3055. echo "</table>";
  3056. if($target_table_type == 'table' && $db->isWritable() && $db->isDirWritable())
  3057. {
  3058. echo "<a onclick='checkAll()'>".$lang['chk_all']."</a> / <a onclick='uncheckAll()'>".$lang['unchk_all']."</a> <i>".$lang['with_sel'].":</i> ";
  3059. echo "<select name='action2'>";
  3060. //echo "<option value='edit'>".$lang['edit']."</option>";
  3061. echo "<option value='column_delete'>".$lang['del']."</option>";
  3062. if($noPrimaryKey)
  3063. echo "<option value='primarykey_add'>".$lang['prim_key']."</option>";
  3064. echo "</select> ";
  3065. echo "<input type='submit' value='".$lang['go']."' name='massGo' class='btn'/>";
  3066. }
  3067. echo "</form>";
  3068. if($target_table_type == 'table' && $db->isWritable() && $db->isDirWritable())
  3069. {
  3070. echo "<br/>";
  3071. echo $params->getForm(array('action'=>'column_create'), 'get');
  3072. echo $lang['add']." <input type='text' name='tablefields' style='width:30px;' value='1'/> ".$lang['tbl_end']." <input type='submit' value='".$lang['go']."' name='addfields' class='btn'/>";
  3073. echo "</form>";
  3074. }
  3075. $query = "SELECT sql FROM sqlite_master WHERE name=".$db->quote($target_table);
  3076. $master = $db->selectArray($query);
  3077. echo "<br/>";
  3078. echo "<br/>";
  3079. echo "<div class='confirm'>";
  3080. echo "<b>".$lang['query_used_'.$target_table_type]."</b><br/>";
  3081. echo "<span style='font-size:11px;'>".htmlencode($master[0]['sql'])."</span>";
  3082. echo "</div>";
  3083. echo "<br/>";
  3084. if($target_table_type != 'view')
  3085. {
  3086. echo "<br/><hr/><br/>";
  3087. $query = "PRAGMA index_list(".$db->quote_id($target_table).")";
  3088. $result = $db->selectArray($query);
  3089. if(sizeof($result)>0)
  3090. {
  3091. echo "<h2>".$lang['indexes'].":</h2>";
  3092. echo "<table border='0' cellpadding='2' cellspacing='1' class='viewTable'>";
  3093. echo "<tr>";
  3094. echo "<td colspan='1'>";
  3095. echo "</td>";
  3096. echo "<td class='tdheader'>".$lang['name']."</td>";
  3097. echo "<td class='tdheader'>".$lang['unique']."</td>";
  3098. echo "<td class='tdheader'>".$lang['seq_no']."</td>";
  3099. echo "<td class='tdheader'>".$lang['col']." #</td>";
  3100. echo "<td class='tdheader'>".$lang['fld']."</td>";
  3101. echo "</tr>";
  3102. for($i=0; $i<sizeof($result); $i++)
  3103. {
  3104. if($result[$i]['unique']==0)
  3105. $unique = $lang['no'];
  3106. else
  3107. $unique = $lang['yes'];
  3108. $query = "PRAGMA index_info(".$db->quote_id($result[$i]['name']).")";
  3109. $info = $db->selectArray($query);
  3110. $span = sizeof($info);
  3111. $tdWithClass = "<td class='td".($i%2 ? "1" : "2")."'>";
  3112. $tdWithClassLeft = "<td class='td".($i%2 ? "1" : "2")."' style='text-align:left;'>";
  3113. $tdWithClassSpan = "<td class='td".($i%2 ? "1" : "2")."' rowspan='".$span."'>";
  3114. $tdWithClassLeftSpan = "<td class='td".($i%2 ? "1" : "2")."' style='text-align:left;' rowspan='".$span."'>";
  3115. echo "<tr>";
  3116. echo $tdWithClassSpan;
  3117. echo $params->getLink(array('action'=>'index_delete', 'pk'=>$result[$i]['name']), "<span>".$lang['del']."</span>", 'delete', $lang['del']);
  3118. echo "</td>";
  3119. echo $tdWithClassLeftSpan;
  3120. echo $result[$i]['name'];
  3121. echo "</td>";
  3122. echo $tdWithClassLeftSpan;
  3123. echo $unique;
  3124. echo "</td>";
  3125. for($j=0; $j<$span; $j++)
  3126. {
  3127. if($j!=0)
  3128. echo "<tr>";
  3129. echo $tdWithClassLeft;
  3130. echo htmlencode($info[$j]['seqno']);
  3131. echo "</td>";
  3132. echo $tdWithClassLeft;
  3133. echo htmlencode($info[$j]['cid']);
  3134. echo "</td>";
  3135. echo $tdWithClassLeft;
  3136. echo htmlencode($info[$j]['name']);
  3137. echo "</td>";
  3138. echo "</tr>";
  3139. }
  3140. }
  3141. echo "</table><br/><br/>";
  3142. }
  3143. $query = "SELECT * FROM sqlite_master WHERE type='trigger' AND tbl_name=".$db->quote($target_table)." ORDER BY name";
  3144. $result = $db->selectArray($query);
  3145. //print_r($result);
  3146. if(sizeof($result)>0)
  3147. {
  3148. echo "<h2>".$lang['triggers'].":</h2>";
  3149. echo "<table border='0' cellpadding='2' cellspacing='1' class='viewTable'>";
  3150. echo "<tr>";
  3151. echo "<td colspan='1'>";
  3152. echo "</td>";
  3153. echo "<td class='tdheader'>".$lang['name']."</td>";
  3154. echo "<td class='tdheader'>".$lang['sql']."</td>";
  3155. echo "</tr>";
  3156. for($i=0; $i<sizeof($result); $i++)
  3157. {
  3158. $tdWithClass = "<td class='td".($i%2 ? "1" : "2")."'>";
  3159. echo "<tr>";
  3160. echo $tdWithClass;
  3161. echo $params->getLink(array('action'=>'trigger_delete', 'pk'=>$result[$i]['name']), "<span>".$lang['del']."</span>", 'delete', $lang['del']);
  3162. echo "</td>";
  3163. echo $tdWithClass;
  3164. echo htmlencode($result[$i]['name']);
  3165. echo "</td>";
  3166. echo $tdWithClass;
  3167. echo htmlencode($result[$i]['sql']);
  3168. echo "</td>";
  3169. }
  3170. echo "</table><br/><br/>";
  3171. }
  3172. if($db->isWritable() && $db->isDirWritable())
  3173. {
  3174. echo $params->getForm(array('action'=>'index_create'),'get');
  3175. echo "<br/><div class='tdheader'>";
  3176. echo $lang['create_index2']." <input type='text' name='numcolumns' style='width:30px;' value='1'/> ".$lang['cols']." <input type='submit' value='".$lang['go']."' name='addindex' class='btn'/>";
  3177. echo "</div>";
  3178. echo "</form>";
  3179. echo $params->getForm(array('action'=>'trigger_create'),'get');
  3180. echo "<br/><div class='tdheader'>";
  3181. echo $lang['create_trigger2']." <input type='submit' value='".$lang['go']."' name='addindex' class='btn'/>";
  3182. echo "</div>";
  3183. echo "</form>";
  3184. }
  3185. }
  3186. break;
  3187. //- Create column (=column_create)
  3188. case "column_create":
  3189. echo "<h2>".sprintf($lang['new_fld'],htmlencode($_GET['table']))."</h2>";
  3190. if($_GET['tablefields']=="" || intval($_GET['tablefields'])<=0)
  3191. echo $lang['specify_fields'];
  3192. else if($_GET['table']=="")
  3193. echo $lang['specify_tbl'];
  3194. else
  3195. {
  3196. $num = intval($_GET['tablefields']);
  3197. $name = $_GET['table'];
  3198. echo $params->getForm(array('action'=>'column_create', 'confirm'=>'1'));
  3199. echo "<input type='hidden' name='rows' value='".$num."'/>";
  3200. echo "<table border='0' cellpadding='2' cellspacing='1' class='viewTable'>";
  3201. echo "<tr>";
  3202. $headings = array($lang["fld"], $lang["type"], $lang["prim_key"]);
  3203. if($db->getType() != "SQLiteDatabase") $headings[] = $lang["autoincrement"];
  3204. $headings[] = $lang["not_null"];
  3205. $headings[] = $lang["def_val"];
  3206. for($k=0; $k<count($headings); $k++)
  3207. echo "<td class='tdheader'>" . $headings[$k] . "</td>";
  3208. echo "</tr>";
  3209. for($i=0; $i<$num; $i++)
  3210. {
  3211. $tdWithClass = "<td class='td" . ($i%2 ? "1" : "2") . "'>";
  3212. echo "<tr>";
  3213. echo $tdWithClass;
  3214. echo "<input type='text' name='".$i."_field' style='width:200px;'/>";
  3215. echo "</td>";
  3216. echo $tdWithClass;
  3217. echo "<select name='".$i."_type' id='i".$i."_type' onchange='toggleAutoincrement(".$i.");'>";
  3218. foreach ($sqlite_datatypes as $t) {
  3219. echo "<option value='".htmlencode($t)."'>".htmlencode($t)."</option>";
  3220. }
  3221. echo "</select>";
  3222. echo "</td>";
  3223. echo $tdWithClass;
  3224. echo "<label><input type='checkbox' name='".$i."_primarykey'/> ".$lang['yes']."</label>";
  3225. echo "</td>";
  3226. if($db->getType() != "SQLiteDatabase")
  3227. {
  3228. echo $tdWithClass;
  3229. echo "<label><input type='checkbox' name='".$i."_autoincrement' id='i".$i."_autoincrement'/> ".$lang['yes']."</label>";
  3230. echo "</td>";
  3231. }
  3232. echo $tdWithClass;
  3233. echo "<label><input type='checkbox' name='".$i."_notnull'/> ".$lang['yes']."</label>";
  3234. echo "</td>";
  3235. echo $tdWithClass;
  3236. echo "<select name='".$i."_defaultoption' id='i".$i."_defaultoption' onchange=\"if(this.value!='defined' && this.value!='expr') document.getElementById('i".$i."_defaultvalue').value='';\">";
  3237. echo "<option value='none'>".$lang['none']."</option><option value='defined'>".$lang['as_defined'].":</option><option>NULL</option><option>CURRENT_TIME</option><option>CURRENT_DATE</option><option>CURRENT_TIMESTAMP</option><option value='expr'>".$lang['expression'].":</option>";
  3238. echo "</select>";
  3239. echo "<input type='text' name='".$i."_defaultvalue' id='i".$i."_defaultvalue' style='width:100px;' onchange=\"if(document.getElementById('i".$i."_defaultoption').value!='expr') document.getElementById('i".$i."_defaultoption').value='defined';\"/>";
  3240. echo "</td>";
  3241. echo "</tr>";
  3242. }
  3243. echo "<tr>";
  3244. echo "<td class='tdheader' style='text-align:right;' colspan='6'>";
  3245. echo "<input type='submit' value='".$lang['add_flds']."' class='btn'/> ";
  3246. echo $params->getLink(array('action'=>'column_view'), $lang['cancel']);
  3247. echo "</td>";
  3248. echo "</tr>";
  3249. echo "</table>";
  3250. echo "</form>";
  3251. }
  3252. break;
  3253. //- Delete column (=column_confirm)
  3254. case "column_confirm":
  3255. if(isset($_GET['check']))
  3256. $pks = $_GET['check'];
  3257. elseif(isset($_GET['pk']))
  3258. $pks = array($_GET['pk']);
  3259. else $pks = array();
  3260. if(sizeof($pks)==0) //nothing was selected so show an error
  3261. {
  3262. echo "<div class='confirm'>";
  3263. echo $lang['err'].": ".$lang['no_sel'];
  3264. echo "</div>";
  3265. echo "<br/><br/>";
  3266. echo $params->getLink(array('action'=>'column_view'), $lang['return']);
  3267. }
  3268. else
  3269. {
  3270. $str = $pks[0];
  3271. $pkVal = $pks[0];
  3272. for($i=1; $i<sizeof($pks); $i++)
  3273. {
  3274. $str .= ", ".$pks[$i];
  3275. $pkVal .= ":".$pks[$i];
  3276. }
  3277. echo $params->getForm(array('action'=>$_GET['action2'], 'confirm'=>'1', 'pk'=>$pkVal));
  3278. echo "<div class='confirm'>";
  3279. printf($lang['ques_'.$_GET['action2']], htmlencode($str), htmlencode($target_table));
  3280. echo "<br/><br/>";
  3281. echo "<input type='submit' value='".$lang['confirm']."' class='btn'/> ";
  3282. echo $params->getLink(array('action'=>'column_view'), $lang['cancel']);
  3283. echo "</div>";
  3284. }
  3285. break;
  3286. //- Edit column (=column_edit)
  3287. case "column_edit":
  3288. echo "<h2>".sprintf($lang['edit_col'], htmlencode($_GET['pk']))." ".$lang['on_tbl']." '".htmlencode($target_table)."'</h2>";
  3289. echo $lang['sqlite_limit']."<br/><br/>";
  3290. if(!isset($_GET['pk']))
  3291. echo $lang['specify_col'];
  3292. else if (!$target_table)
  3293. echo $lang['specify_tbl'];
  3294. else
  3295. {
  3296. $tableInfo = $db->getTableInfo($target_table);
  3297. for($i=0; $i<sizeof($tableInfo); $i++)
  3298. {
  3299. if($tableInfo[$i][1]==$_GET['pk'])
  3300. {
  3301. $colVal = $tableInfo[$i][0];
  3302. $fieldVal = $tableInfo[$i][1];
  3303. $typeVal = $tableInfo[$i]['type'];
  3304. $notnullVal = $tableInfo[$i][3];
  3305. $defaultVal = $tableInfo[$i][4];
  3306. $primarykeyVal = $tableInfo[$i][5];
  3307. break;
  3308. }
  3309. }
  3310. if(!isset($fieldVal))
  3311. {
  3312. echo "<div class='confirm'>".$lang['err'].": ".sprintf($lang['col_inexistent'], htmlencode($_GET['pk']))."</div>";
  3313. }
  3314. else
  3315. {
  3316. $name = $target_table;
  3317. echo $params->getForm(array('action'=>'column_edit', 'confirm'=>'1'));
  3318. echo "<input type='hidden' name='oldvalue' value='".htmlencode($_GET['pk'])."'/>";
  3319. echo "<table border='0' cellpadding='2' cellspacing='1' class='viewTable'>";
  3320. echo "<tr>";
  3321. //$headings = array("Field", "Type", "Primary Key", "Autoincrement", "Not NULL", "Default Value");
  3322. $headings = array($lang["fld"], $lang["type"]);
  3323. for($k=0; $k<count($headings); $k++)
  3324. echo "<td class='tdheader'>".$headings[$k]."</td>";
  3325. echo "</tr>";
  3326. $i = 0;
  3327. $tdWithClass = "<td class='td" . ($i%2 ? "1" : "2") . "'>";
  3328. echo "<tr>";
  3329. echo $tdWithClass;
  3330. echo "<input type='text' name='".$i."_field' style='width:200px;' value='".htmlencode($fieldVal)."'/>";
  3331. echo "</td>";
  3332. echo $tdWithClass;
  3333. echo "<select name='".$i."_type' id='i".$i."_type' onchange='toggleAutoincrement(".$i.");'>";
  3334. if(!in_array($typeVal, $sqlite_datatypes))
  3335. echo "<option value='".htmlencode($typeVal)."' selected='selected'>".htmlencode($typeVal)."</option>";
  3336. foreach ($sqlite_datatypes as $t) {
  3337. if($t==$typeVal)
  3338. echo "<option value='".htmlencode($t)."' selected='selected'>".htmlencode($t)."</option>";
  3339. else
  3340. echo "<option value='".htmlencode($t)."'>".htmlencode($t)."</option>";
  3341. }
  3342. echo "</select>";
  3343. echo "</td>";
  3344. /*
  3345. echo $tdWithClass;
  3346. if($primarykeyVal)
  3347. echo "<input type='checkbox' name='".$i."_primarykey' checked='checked'/> Yes";
  3348. else
  3349. echo "<input type='checkbox' name='".$i."_primarykey'/> Yes";
  3350. echo "</td>";
  3351. echo $tdWithClass;
  3352. if(1==2)
  3353. echo "<input type='checkbox' name='".$i."_autoincrement' id='".$i."_autoincrement' checked='checked'/> Yes";
  3354. else
  3355. echo "<input type='checkbox' name='".$i."_autoincrement' id='".$i."_autoincrement'/> Yes";
  3356. echo "</td>";
  3357. echo $tdWithClass;
  3358. if($notnullVal)
  3359. echo "<input type='checkbox' name='".$i."_notnull' checked='checked'/> Yes";
  3360. else
  3361. echo "<input type='checkbox' name='".$i."_notnull'/> Yes";
  3362. echo "</td>";
  3363. echo $tdWithClass;
  3364. echo "<input type='text' name='".$i."_defaultvalue' value='".$defaultVal."' style='width:100px;'/>";
  3365. echo "</td>";
  3366. */
  3367. echo "</tr>";
  3368. echo "<tr>";
  3369. echo "<td class='tdheader' style='text-align:right;' colspan='6'>";
  3370. echo "<input type='submit' value='".$lang['save_ch']."' class='btn'/> ";
  3371. echo $params->getLink(array('action'=>'column_view'), $lang['cancel']);
  3372. echo "</td>";
  3373. echo "</tr>";
  3374. echo "</table>";
  3375. echo "</form>";
  3376. }
  3377. }
  3378. break;
  3379. //- Delete index (=index_delete)
  3380. case "index_delete":
  3381. echo $params->getForm(array('action'=>'index_delete', 'pk'=>$_GET['pk'], 'confirm'=>'1'));
  3382. echo "<div class='confirm'>";
  3383. echo sprintf($lang['ques_del_index'], htmlencode($_GET['pk']))."<br/><br/>";
  3384. echo "<input type='submit' value='".$lang['confirm']."' class='btn'/> ";
  3385. echo $params->getLink(array('action'=>'column_view'), $lang['cancel']);
  3386. echo "</div>";
  3387. echo "</form>";
  3388. break;
  3389. //- Delete trigger (=trigger_delete)
  3390. case "trigger_delete":
  3391. echo $params->getForm(array('action'=>'trigger_delete', 'pk'=>$_GET['pk'], 'confirm'=>'1'));
  3392. echo "<div class='confirm'>";
  3393. echo sprintf($lang['ques_del_trigger'], htmlencode($_GET['pk']))."<br/><br/>";
  3394. echo "<input type='submit' value='".$lang['confirm']."' class='btn'/> ";
  3395. echo $params->getLink(array('action'=>'column_view'), $lang['cancel']);
  3396. echo "</div>";
  3397. echo "</form>";
  3398. break;
  3399. //- Create trigger (=trigger_create)
  3400. case "trigger_create":
  3401. echo "<h2>".$lang['create_trigger']." '".htmlencode($_GET['table'])."'</h2>";
  3402. if($_GET['table']=="")
  3403. echo $lang['specify_tbl'];
  3404. else
  3405. {
  3406. echo $params->getForm(array('action'=>'trigger_create', 'confirm'=>'1'));
  3407. echo $lang['trigger_name'].": <input type='text' name='trigger_name'/><br/><br/>";
  3408. echo "<fieldset><legend>".$lang['db_event']."</legend>";
  3409. echo $lang['before']."/".$lang['after'].": ";
  3410. echo "<select name='beforeafter'>";
  3411. echo "<option value=''></option>";
  3412. echo "<option value='BEFORE'>".$lang['before']."</option>";
  3413. echo "<option value='AFTER'>".$lang['after']."</option>";
  3414. echo "<option value='INSTEAD OF'>".$lang['instead']."</option>";
  3415. echo "</select>";
  3416. echo "<br/><br/>";
  3417. echo $lang['event'].": ";
  3418. echo "<select name='event'>";
  3419. echo "<option value='DELETE'>".$lang['del']."</option>";
  3420. echo "<option value='INSERT'>".$lang['insert']."</option>";
  3421. echo "<option value='UPDATE'>".$lang['update']."</option>";
  3422. echo "</select>";
  3423. echo "</fieldset><br/><br/>";
  3424. echo "<fieldset><legend>".$lang['trigger_act']."</legend>";
  3425. echo "<label><input type='checkbox' name='foreachrow'/> ".$lang['each_row']."</label><br/><br/>";
  3426. echo $lang['when_exp'].":<br/>";
  3427. echo "<textarea name='whenexpression' style='width:500px; height:100px;' rows='8' cols='50'></textarea>";
  3428. echo "<br/><br/>";
  3429. echo $lang['trigger_step'].":<br/>";
  3430. echo "<textarea name='triggersteps' style='width:500px; height:100px;' rows='8' cols='50'></textarea>";
  3431. echo "</fieldset><br/><br/>";
  3432. echo "<input type='submit' value='".$lang['create_trigger2']."' class='btn'/> ";
  3433. echo $params->getLink(array('action'=>'column_view'), $lang['cancel']);
  3434. echo "</form>";
  3435. }
  3436. break;
  3437. //- Create index (=index_create)
  3438. case "index_create":
  3439. echo "<h2>".$lang['create_index']." '".htmlencode($_GET['table'])."'</h2>";
  3440. if($_GET['numcolumns']=="" || intval($_GET['numcolumns'])<=0)
  3441. echo $lang['specify_fields'];
  3442. else if($_GET['table']=="")
  3443. echo $lang['specify_tbl'];
  3444. else
  3445. {
  3446. echo $params->getForm(array('action'=>'index_create', 'confirm'=>'1'));
  3447. $num = intval($_GET['numcolumns']);
  3448. $tableInfo = $db->getTableInfo($_GET['table']);
  3449. echo "<fieldset><legend>".$lang['define_index']."</legend>";
  3450. echo "<label for='index_name'>".$lang['index_name'].":</label> <input type='text' name='name' id='index_name'/><br/>";
  3451. echo "<label for='index_duplicate'>".$lang['dup_val'].":</label>";
  3452. echo "<select name='duplicate' id='index_duplicate'>";
  3453. echo "<option value='yes'>".$lang['allow']."</option>";
  3454. echo "<option value='no'>".$lang['not_allow']."</option>";
  3455. echo "</select><br/>";
  3456. if(version_compare($db->getSQLiteVersion(),'3.8.0')>=0)
  3457. echo "<label for='index_where'>WHERE:</label> <input type='text' name='where' id='index_where'/> ".helpLink($lang['help10']);
  3458. echo "</fieldset>";
  3459. echo "<br/>";
  3460. echo "<fieldset><legend>".$lang['define_in_col']."</legend>";
  3461. for($i=0; $i<$num; $i++)
  3462. {
  3463. echo "<select name='".$i."_field'>";
  3464. echo "<option value=''>--".$lang['ignore']."--</option>";
  3465. for($j=0; $j<sizeof($tableInfo); $j++)
  3466. echo "<option value='".htmlencode($tableInfo[$j][1])."'>".htmlencode($tableInfo[$j][1])."</option>";
  3467. echo "</select> ";
  3468. echo "<select name='".$i."_order'>";
  3469. echo "<option value=''></option>";
  3470. echo "<option value=' ASC'>".$lang['asc']."</option>";
  3471. echo "<option value=' DESC'>".$lang['desc']."</option>";
  3472. echo "</select><br/>";
  3473. }
  3474. echo "</fieldset>";
  3475. echo "<br/><br/>";
  3476. echo "<input type='hidden' name='num' value='".$num."'/>";
  3477. echo "<input type='submit' value='".$lang['create_index1']."' class='btn'/> ";
  3478. echo $params->getLink(array('action'=>'column_view'), $lang['cancel']);
  3479. echo "</form>";
  3480. }
  3481. break;
  3482. }
  3483. echo "</div>";
  3484. }
  3485. //- HMTL: views for databases
  3486. if(!$target_table && !isset($_GET['confirm']) && (!isset($_GET['action']) || (isset($_GET['action']) && $_GET['action']!="table_create"))) //the absence of these fields means we are viewing the database homepage
  3487. {
  3488. //- Switch on $view (actually a series of if-else)
  3489. if($view=="structure")
  3490. {
  3491. //- Database structure, shows all the tables (=structure)
  3492. if($db->isWritable() && !$db->isDirWritable())
  3493. {
  3494. echo "<div class='confirm' style='margin:10px 0'>";
  3495. echo $lang['attention'].': '.$lang['directory_not_writable'];
  3496. echo "</div><br/>";
  3497. }
  3498. elseif(!$db->isWritable())
  3499. {
  3500. echo "<div class='confirm' style='margin:10px 0;'>";
  3501. echo $lang['attention'].': '.$lang['database_not_writable'];
  3502. echo "</div><br/>";
  3503. }
  3504. if ($auth->isPasswordDefault())
  3505. {
  3506. echo "<div class='confirm' style='margin:20px 0px;'>";
  3507. echo sprintf($lang['warn_passwd'],(is_readable('phpliteadmin.config.php')?'phpliteadmin.config.php':basename(__FILE__)))."<br />".$lang['warn0'];
  3508. echo "</div>";
  3509. }
  3510. echo "<b>".$lang['db_name']."</b>: ".htmlencode($db->getName())."<br/>";
  3511. echo "<b>".$lang['db_path']."</b>: ".htmlencode($db->getPath())."<br/>";
  3512. echo "<b>".$lang['db_size']."</b>: ".number_format($db->getSize())." KiB<br/>";
  3513. echo "<b>".$lang['db_mod']."</b>: ".$db->getDate()."<br/>";
  3514. echo "<b>".$lang['sqlite_v']."</b>: ".$db->getSQLiteVersion()."<br/>";
  3515. echo "<b>".$lang['sqlite_ext']."</b> ".helpLink($lang['help1']).": ".$db->getType()."<br/>";
  3516. echo "<b>".$lang['php_v']."</b>: ".phpversion()."<br/>";
  3517. echo "<b>".PROJECT." ".$lang["ver"]."</b>: ".VERSION;
  3518. echo " <a href='".PROJECT_URL."' target='_blank' id='oldVersion' style='display: none;' class='warning'>".$lang['new_version']."</a><br/><br/>";
  3519. echo "<script type='text/javascript'>checkVersion('".VERSION."','".VERSION_CHECK_URL."');</script>";
  3520. if(isset($_GET['sort']) && ($_GET['sort']=='type' || $_GET['sort']=='name'))
  3521. $_SESSION[COOKIENAME.'sortTables'] = $_GET['sort'];
  3522. if(isset($_GET['order']) && ($_GET['order']=='ASC' || $_GET['order']=='DESC'))
  3523. $_SESSION[COOKIENAME.'orderTables'] = $_GET['order'];
  3524. if(!isset($_SESSION[COOKIENAME.'sortTables']))
  3525. $_SESSION[COOKIENAME.'sortTables'] = 'name';
  3526. if(!isset($_SESSION[COOKIENAME.'orderTables']))
  3527. $_SESSION[COOKIENAME.'orderTables'] = 'ASC';
  3528. $tables = $db->getTables(true, false, $_SESSION[COOKIENAME.'sortTables'], $_SESSION[COOKIENAME.'orderTables']);
  3529. if(sizeof($tables)==0)
  3530. echo $lang['no_tbl']."<br/><br/>";
  3531. else
  3532. {
  3533. echo "<table border='0' cellpadding='2' cellspacing='1' class='viewTable'>";
  3534. echo "<tr>";
  3535. echo "<td class='tdheader'>";
  3536. if(isset($_SESSION[COOKIENAME.'sortTables']))
  3537. $orderTag = ($_SESSION[COOKIENAME.'sortTables']=="type" && $_SESSION[COOKIENAME.'orderTables']=="ASC") ? "DESC" : "ASC";
  3538. else
  3539. $orderTag = "ASC";
  3540. echo $params->getLink(array('sort'=>'type', 'order'=>$orderTag), $lang['type']);
  3541. echo helpLink($lang['help3']);
  3542. if(isset($_SESSION[COOKIENAME.'sortTables']) && $_SESSION[COOKIENAME.'sortTables']=="type")
  3543. echo (($_SESSION[COOKIENAME.'orderTables']=="ASC") ? " <b>&uarr;</b>" : " <b>&darr;</b>");
  3544. echo "</td>";
  3545. echo "<td class='tdheader'>";
  3546. if(isset($_SESSION[COOKIENAME.'sortTables']))
  3547. $orderTag = ($_SESSION[COOKIENAME.'sortTables']=="name" && $_SESSION[COOKIENAME.'orderTables']=="ASC") ? "DESC" : "ASC";
  3548. else
  3549. $orderTag = "ASC";
  3550. echo $params->getLink(array('sort'=>'name', 'order'=>$orderTag), $lang['name']);
  3551. if(isset($_SESSION[COOKIENAME.'sortTables']) && $_SESSION[COOKIENAME.'sortTables']=="name")
  3552. echo (($_SESSION[COOKIENAME.'orderTables']=="ASC") ? " <b>&uarr;</b>" : " <b>&darr;</b>");
  3553. echo "</td>";
  3554. echo "<td class='tdheader' colspan='10'>".$lang['act']."</td>";
  3555. echo "<td class='tdheader'>".$lang['rec']."</td>";
  3556. echo "</tr>";
  3557. $totalRecords = 0;
  3558. $skippedTables = false;
  3559. foreach($tables as $tableName => $tableType)
  3560. {
  3561. $records = $db->numRows($tableName, (!isset($_GET['forceCount'])));
  3562. if($records == '?')
  3563. {
  3564. $skippedTables = true;
  3565. $records = $params->getLink(array('forceCount'=>'1'), '?');
  3566. }
  3567. else
  3568. $totalRecords += $records;
  3569. $tdWithClass = "<td class='td".($i%2 ? "1" : "2")."'>";
  3570. $tdWithClassLeft = "<td class='td".($i%2 ? "1" : "2")."' style='text-align:left;'>";
  3571. echo "<tr>";
  3572. echo $tdWithClassLeft;
  3573. echo ($tableType=="table"? $lang['tbl'] : $lang['view']);
  3574. echo "</td>";
  3575. echo $tdWithClassLeft;
  3576. echo $params->getLink(array('table'=>$tableName, 'action'=>'row_view'), htmlencode($tableName));
  3577. echo "</td>";
  3578. echo $tdWithClass;
  3579. echo $params->getLink(array('table'=>$tableName, 'action'=>'row_view'), $lang['browse']);
  3580. echo "</td>";
  3581. echo $tdWithClass;
  3582. echo $params->getLink(array('table'=>$tableName, 'action'=>'column_view'), $lang['struct']);
  3583. echo "</td>";
  3584. echo $tdWithClass;
  3585. echo $params->getLink(array('table'=>$tableName, 'action'=>'table_sql'), $lang['sql']);
  3586. echo "</td>";
  3587. echo $tdWithClass;
  3588. echo $params->getLink(array('table'=>$tableName, 'action'=>'table_search'), $lang['srch']);
  3589. echo "</td>";
  3590. echo $tdWithClass;
  3591. if($tableType=="table" && $db->isWritable() && $db->isDirWritable())
  3592. echo $params->getLink(array('table'=>$tableName, 'action'=>'row_create'), $lang['insert']);
  3593. else
  3594. echo $lang['insert'];
  3595. echo "</td>";
  3596. echo $tdWithClass;
  3597. echo $params->getLink(array('table'=>$tableName, 'action'=>'table_export'), $lang['export']);
  3598. echo "</td>";
  3599. echo $tdWithClass;
  3600. if($tableType=="table" && $db->isWritable() && $db->isDirWritable())
  3601. echo $params->getLink(array('table'=>$tableName, 'action'=>'table_import'), $lang['import']);
  3602. else
  3603. echo $lang['import'];
  3604. echo "</td>";
  3605. echo $tdWithClass;
  3606. if($db->isWritable() && $db->isDirWritable())
  3607. echo $params->getLink(array('table'=>$tableName, 'action'=>'table_rename'), $lang['rename']);
  3608. else
  3609. echo $lang['rename'];
  3610. echo "</td>";
  3611. echo $tdWithClass;
  3612. if($tableType=="table" && $db->isWritable() && $db->isDirWritable())
  3613. echo $params->getLink(array('table'=>$tableName, 'action'=>'table_empty'), $lang['empty'], 'empty');
  3614. else
  3615. echo $lang['empty'];
  3616. echo "</td>";
  3617. echo $tdWithClass;
  3618. if($db->isWritable() && $db->isDirWritable())
  3619. echo $params->getLink(array('table'=>$tableName, 'action'=>'table_drop'), $lang['drop'], 'drop');
  3620. else
  3621. echo $lang['drop'];
  3622. echo "</td>";
  3623. echo $tdWithClass;
  3624. echo $records;
  3625. echo "</td>";
  3626. echo "</tr>";
  3627. }
  3628. echo "<tr>";
  3629. echo "<td class='tdheader' colspan='12'>".sizeof($tables)." ".$lang['total']."</td>";
  3630. echo "<td class='tdheader' colspan='1' style='text-align:right;'>".$totalRecords.($skippedTables?" ".$params->getLink(array('forceCount'=>'1'),'+ ?'):"")."</td>";
  3631. echo "</tr>";
  3632. echo "</table>";
  3633. echo "<br/>";
  3634. if($skippedTables)
  3635. echo "<div class='confirm' style='margin-bottom:20px;'>".sprintf($lang["counting_skipped"],"<a href='".$params->getURL(array('forceCount'=>'1'))."'>","</a>")."</div>";
  3636. }
  3637. if($db->isWritable() && $db->isDirWritable())
  3638. {
  3639. echo "<fieldset>";
  3640. echo "<legend><b>".$lang['create_tbl_db']." '".htmlencode($db->getName())."'</b></legend>";
  3641. echo $params->getForm(array('action'=>'table_create'), 'get');
  3642. echo $lang['name'].": <input type='text' name='tablename' style='width:200px;'/> ";
  3643. echo $lang['fld_num'].": <input type='text' name='tablefields' style='width:90px;'/> ";
  3644. echo "<input type='submit' name='createtable' value='".$lang['go']."' class='btn'/>";
  3645. echo "</form>";
  3646. echo "</fieldset>";
  3647. echo "<br/>";
  3648. echo "<fieldset>";
  3649. echo "<legend><b>".$lang['create_view']." '".htmlencode($db->getName())."'</b></legend>";
  3650. echo $params->getForm(array('action'=>'view_create', 'confirm'=>'1'));
  3651. echo $lang['name'].": <input type='text' name='viewname' style='width:200px;'/> ";
  3652. echo $lang['sel_state']." ".helpLink($lang['help4']).": <input type='text' name='select' style='width:400px;'/> ";
  3653. echo "<input type='submit' name='createtable' value='".$lang['go']."' class='btn'/>";
  3654. echo "</form>";
  3655. echo "</fieldset>";
  3656. }
  3657. }
  3658. else if($view=="sql")
  3659. {
  3660. //- Database SQL editor (=sql)
  3661. if(isset($_POST['query']) && $_POST['query']!="")
  3662. {
  3663. $delimiter = $_POST['delimiter'];
  3664. $queryStr = $_POST['queryval'];
  3665. //save the queries in history if necessary
  3666. if($maxSavedQueries!=0 && $maxSavedQueries!=false)
  3667. {
  3668. if(!isset($_SESSION[COOKIENAME.'query_history']))
  3669. $_SESSION[COOKIENAME.'query_history'] = array();
  3670. $_SESSION[COOKIENAME.'query_history'][md5(strtolower($queryStr))] = $queryStr;
  3671. if(sizeof($_SESSION[COOKIENAME.'query_history']) > $maxSavedQueries)
  3672. array_shift($_SESSION[COOKIENAME.'query_history']);
  3673. }
  3674. $query = explode_sql($delimiter, $queryStr); //explode the query string into individual queries based on the delimiter
  3675. for($i=0; $i<sizeof($query); $i++) //iterate through the queries exploded by the delimiter
  3676. {
  3677. if(str_replace(" ", "", str_replace("\n", "", str_replace("\r", "", $query[$i])))!="") //make sure this query is not an empty string
  3678. {
  3679. $queryTimer = new MicroTimer();
  3680. $table_result = $db->query($query[$i]);
  3681. echo "<div class='confirm'>";
  3682. echo "<b>".htmlencode($query[$i])."</b>";
  3683. if($table_result === NULL || $table_result === false)
  3684. {
  3685. echo "<br /><b>".$lang['err'].": ".htmlencode($db->getError())."</b></div>";
  3686. }
  3687. echo "</div><br/>";
  3688. if($row = $db->fetch($table_result, 'num'))
  3689. {
  3690. for($j=0; $j<sizeof($row);$j++)
  3691. $headers[$j] = $db->getColumnName($table_result,$j);
  3692. echo "<table border='0' cellpadding='2' cellspacing='1' class='viewTable'>";
  3693. echo "<tr>";
  3694. for($j=0; $j<sizeof($headers); $j++)
  3695. {
  3696. echo "<td class='tdheader'>";
  3697. echo htmlencode($headers[$j]);
  3698. echo "</td>";
  3699. }
  3700. echo "</tr>";
  3701. $rowCount = 0;
  3702. for(; $rowCount==0 || $row = $db->fetch($table_result, 'num'); $rowCount++)
  3703. {
  3704. $tdWithClass = "<td class='td".($rowCount%2 ? "1" : "2")."'>";
  3705. echo "<tr>";
  3706. for($z=0; $z<sizeof($headers); $z++)
  3707. {
  3708. echo $tdWithClass;
  3709. if($row[$z]==="")
  3710. echo "&nbsp;";
  3711. elseif($row[$z]===NULL)
  3712. echo "<i class='null'>NULL</i>";
  3713. else
  3714. echo htmlencode(subString($row[$z]));
  3715. echo "</td>";
  3716. }
  3717. echo "</tr>";
  3718. }
  3719. $queryTimer->stop();
  3720. echo "</table><br/><br/>";
  3721. if($table_result !== NULL && $table_result !== false)
  3722. {
  3723. echo "<div class='confirm' style='margin-bottom: 2em'>";
  3724. if($rowCount>0 || $db->getAffectedRows()==0)
  3725. {
  3726. printf($lang['show_rows'], $rowCount);
  3727. }
  3728. if($db->getAffectedRows()>0 || $rowCount==0)
  3729. {
  3730. echo $db->getAffectedRows()." ".$lang['rows_aff']." ";
  3731. }
  3732. printf($lang['query_time'], $queryTimer);
  3733. echo "</div>";
  3734. }
  3735. }
  3736. }
  3737. }
  3738. }
  3739. else
  3740. {
  3741. $delimiter = ";";
  3742. $queryStr = "";
  3743. }
  3744. echo "<fieldset>";
  3745. echo "<legend><b>".sprintf($lang['run_sql'],htmlencode($db->getName()))."</b></legend>";
  3746. echo $params->getForm(array('view'=>'sql'));
  3747. if(isset($_SESSION[COOKIENAME.'query_history']) && sizeof($_SESSION[COOKIENAME.'query_history'])>0)
  3748. {
  3749. echo "<b>".$lang['recent_queries']."</b><ul>";
  3750. foreach($_SESSION[COOKIENAME.'query_history'] as $key => $value)
  3751. {
  3752. echo "<li><a onclick='sqleditorSetValue(this.textContent); return false;' href='#'>".htmlencode($value)."</a></li>";
  3753. }
  3754. echo "</ul><br/><br/>";
  3755. }
  3756. echo "<textarea style='width:100%; height:300px;' name='queryval' id='queryval' cols='50' rows='8'>".htmlencode($queryStr)."</textarea>";
  3757. echo "<script>sqleditor(document.getElementById('queryval'),".json_encode($db->getTableDefinitions()).", null);</script>";
  3758. echo $lang['delimit']." <input type='text' name='delimiter' value='".htmlencode($delimiter)."' style='width:50px;'/> ";
  3759. echo "<input type='submit' name='query' value='".$lang['go']."' class='btn'/>";
  3760. echo "</form>";
  3761. echo "</fieldset>";
  3762. }
  3763. else if($view=="vacuum")
  3764. {
  3765. //- Vacuum database confirmation (=vacuum)
  3766. if(isset($_POST['vacuum']))
  3767. {
  3768. $query = "VACUUM";
  3769. $db->query($query);
  3770. echo "<div class='confirm'>";
  3771. printf($lang['db_vac'], htmlencode($db->getName()));
  3772. echo "</div><br/>";
  3773. }
  3774. echo $params->getForm(array('view'=>'vacuum'));
  3775. printf($lang['vac_desc'],htmlencode($db->getName()));
  3776. echo "<br/><br/>";
  3777. echo "<input type='submit' value='".$lang['vac']."' name='vacuum' class='btn'/>";
  3778. echo "</form>";
  3779. }
  3780. else if($view=="export")
  3781. {
  3782. //- Export view (=export)
  3783. echo $params->getForm(array('view'=>'export'));
  3784. echo "<fieldset style='float:left; width:260px; margin-right:20px;'><legend><b>".$lang['export']."</b></legend>";
  3785. echo "<select multiple='multiple' size='10' style='width:240px;' name='tables[]'>";
  3786. $tables = $db->getTables(true, false);
  3787. foreach($tables as $tableName => $tableType)
  3788. {
  3789. echo "<option value='".htmlencode($tableName)."' selected='selected'>".htmlencode($tableName)."</option>";
  3790. }
  3791. echo "</select>";
  3792. echo "<br/><br/>";
  3793. echo "<label><input type='radio' name='export_type' checked='checked' value='sql' onclick='toggleExports(\"sql\");'/> ".$lang['sql']."</label>";
  3794. echo "<br/><label><input type='radio' name='export_type' value='csv' onclick='toggleExports(\"csv\");'/> ".$lang['csv']."</label>";
  3795. echo "</fieldset>";
  3796. echo "<fieldset style='float:left; max-width:350px;' id='exportoptions_sql'><legend><b>".$lang['options']."</b></legend>";
  3797. echo "<label><input type='checkbox' checked='checked' name='structure'/> ".$lang['export_struct']."</label> ".helpLink($lang['help5'])."<br/>";
  3798. echo "<label><input type='checkbox' checked='checked' name='data'/> ".$lang['export_data']."</label> ".helpLink($lang['help6'])."<br/>";
  3799. echo "<label><input type='checkbox' name='drop'/> ".$lang['add_drop']."</label> ".helpLink($lang['help7'])."<br/>";
  3800. echo "<label><input type='checkbox' checked='checked' name='transaction'/> ".$lang['add_transact']."</label> ".helpLink($lang['help8'])."<br/>";
  3801. echo "<label><input type='checkbox' checked='checked' name='comments'/> ".$lang['comments']."</label> ".helpLink($lang['help9'])."<br/>";
  3802. echo "</fieldset>";
  3803. echo "<fieldset style='float:left; max-width:350px; display:none;' id='exportoptions_csv'><legend><b>".$lang['options']."</b></legend>";
  3804. echo "<div style='float:left;'>".$lang['fld_terminated']."</div>";
  3805. echo "<input type='text' value=';' name='export_csv_fieldsterminated' style='float:right;'/>";
  3806. echo "<div style='clear:both;'>";
  3807. echo "<div style='float:left;'>".$lang['fld_enclosed']."</div>";
  3808. echo "<input type='text' value='\"' name='export_csv_fieldsenclosed' style='float:right;'/>";
  3809. echo "<div style='clear:both;'>";
  3810. echo "<div style='float:left;'>".$lang['fld_escaped']."</div>";
  3811. echo "<input type='text' value='\' name='export_csv_fieldsescaped' style='float:right;'/>";
  3812. echo "<div style='clear:both;'>";
  3813. echo "<div style='float:left;'>".$lang['rep_null']."</div>";
  3814. echo "<input type='text' value='NULL' name='export_csv_replacenull' style='float:right;'/>";
  3815. echo "<div style='clear:both;'>";
  3816. echo "<label><input type='checkbox' name='export_csv_crlf'/> ".$lang['rem_crlf']."</label><br/>";
  3817. echo "<label><input type='checkbox' checked='checked' name='export_csv_fieldnames'/> ".$lang['put_fld']."</label>";
  3818. echo "</fieldset>";
  3819. echo "<div style='clear:both;'></div>";
  3820. echo "<br/><br/>";
  3821. echo "<fieldset><legend><b>".$lang['save_as']."</b></legend>";
  3822. $file = pathinfo($db->getPath());
  3823. $name = $file['filename'];
  3824. echo "<input type='text' name='filename' value='".htmlencode($name)."_".date("Y-m-d").".dump' style='width:400px;'/> <input type='submit' name='export' value='".$lang['export']."' class='btn'/>";
  3825. echo "</fieldset>";
  3826. echo "</form>";
  3827. echo "<div class='confirm' style='margin-top: 2em'>".sprintf($lang['backup_hint'],
  3828. $params->getLink(array('download'=>$currentDB['path'], 'token'=>$_SESSION[COOKIENAME.'token']), $lang["backup_hint_linktext"], '', $lang['backup'])
  3829. )."</div>";
  3830. }
  3831. else if($view=="import")
  3832. {
  3833. //- Import view (=import)
  3834. if(isset($_POST['import']))
  3835. {
  3836. echo "<div class='confirm'>";
  3837. if($importSuccess===true)
  3838. echo $lang['import_suc'];
  3839. else
  3840. echo $importSuccess;
  3841. echo "</div><br/>";
  3842. }
  3843. echo $params->getForm(array('view'=>'import'), 'post', true);
  3844. echo "<fieldset style='float:left; width:260px; margin-right:20px;'><legend><b>".$lang['import']."</b></legend>";
  3845. echo "<label><input type='radio' name='import_type' checked='checked' value='sql' onclick='toggleImports(\"sql\");'/> ".$lang['sql']."</label>";
  3846. echo "<br/><label><input type='radio' name='import_type' value='csv' onclick='toggleImports(\"csv\");'/> ".$lang['csv']."</label>";
  3847. echo "</fieldset>";
  3848. echo "<fieldset style='float:left; max-width:350px;' id='importoptions_sql'><legend><b>".$lang['options']."</b></legend>";
  3849. echo $lang['no_opt'];
  3850. echo "</fieldset>";
  3851. echo "<fieldset style='float:left; max-width:350px; display:none;' id='importoptions_csv'><legend><b>".$lang['options']."</b></legend>";
  3852. echo "<div style='float:left;'>".$lang['csv_tbl']."</div>";
  3853. echo "<select name='single_table' style='float:right;'>";
  3854. $tables = $db->getTables(true, false);
  3855. echo "<option value=''>(".$lang['create_tbl'].")</option>";
  3856. foreach($tables as $tableName => $tableType)
  3857. {
  3858. echo "<option value='".htmlencode($tableName)."'>".htmlencode($tableName)."</option>";
  3859. }
  3860. echo "</select>";
  3861. echo "<div style='clear:both;'>";
  3862. echo "<div style='float:left;'>".$lang['fld_terminated']."</div>";
  3863. echo "<input type='text' value=';' name='import_csv_fieldsterminated' style='float:right;'/>";
  3864. echo "<div style='clear:both;'>";
  3865. echo "<div style='float:left;'>".$lang['fld_enclosed']."</div>";
  3866. echo "<input type='text' value='\"' name='import_csv_fieldsenclosed' style='float:right;'/>";
  3867. echo "<div style='clear:both;'>";
  3868. echo "<div style='float:left;'>".$lang['fld_escaped']."</div>";
  3869. echo "<input type='text' value='\' name='import_csv_fieldsescaped' style='float:right;'/>";
  3870. echo "<div style='clear:both;'>";
  3871. echo "<div style='float:left;'>".$lang['null_represent']."</div>";
  3872. echo "<input type='text' value='NULL' name='import_csv_replacenull' style='float:right;'/>";
  3873. echo "<div style='clear:both;'>";
  3874. echo "<label><input type='checkbox' checked='checked' name='import_csv_fieldnames'/> ".$lang['fld_names']."</label>";
  3875. echo "</fieldset>";
  3876. echo "<div style='clear:both;'></div>";
  3877. echo "<br/><br/>";
  3878. echo "<fieldset><legend><b>".$lang['import_f']."</b></legend>";
  3879. echo "<em>".$lang['max_file_size'].": ".number_format(fileUploadMaxSize()/1024/1024)." MiB</em> ".helpLink($lang['help11'])."<br />";
  3880. echo "<input type='file' value='".$lang['choose_f']."' name='file' style='background-color:transparent; border-style:none; margin:0; padding:0' onchange='checkFileSize(this)'/>";
  3881. echo "<input type='submit' value='".$lang['import']."' name='import' class='btn'/>";
  3882. echo "</fieldset>";
  3883. }
  3884. else if($view=="rename")
  3885. {
  3886. //- Rename database confirmation (=rename)
  3887. echo $params->getForm(array('view'=>'rename', 'database_rename'=>'1'));
  3888. echo "<input type='hidden' name='oldname' value='".htmlencode($db->getPath())."'/>";
  3889. echo $lang['db_rename']." '".htmlencode($db->getPath())."' ".$lang['to']." <input type='text' name='newname' style='width:200px;' value='".htmlencode($db->getPath())."'/> <input type='submit' value='".$lang['rename']."' name='rename' class='btn'/>";
  3890. echo "</form>";
  3891. }
  3892. else if($view=="delete")
  3893. {
  3894. //- Delete database confirmation (=delete)
  3895. echo $params->getForm(array('database_delete'=>'1'));
  3896. echo "<div class='confirm'>";
  3897. echo sprintf($lang['ques_del_db'],htmlencode($db->getPath()))."<br/><br/>";
  3898. echo "<input name='database_delete' value='".htmlencode($db->getPath())."' type='hidden'/>";
  3899. echo "<input type='submit' value='".$lang['confirm']."' class='btn'/> ";
  3900. echo $params->getLink(array(), $lang['cancel']);
  3901. echo "</div>";
  3902. echo "</form>";
  3903. }
  3904. echo "</div>";
  3905. }
  3906. echo "</div>";
  3907. //- HTML: page footer
  3908. echo "<br/>";
  3909. echo "<span style='font-size:11px;'>".$lang['powered']." <a href='".PROJECT_URL."' target='_blank' style='font-size:11px;'>".PROJECT."</a> | ";
  3910. echo $lang['free_software']." <a href='".DONATE_URL."' target='_blank' style='font-size:11px;'>".$lang['please_donate']."</a> | ";
  3911. printf($lang['page_gen'], $pageTimer);
  3912. echo "</span>";
  3913. echo "</td></tr></table>";
  3914. $db->close(); //close the database
  3915. echo "</body>";
  3916. echo "</html>";
  3917. //- End of main code
  3918. // Authorization class
  3919. // Maintains user's logged-in state and security of application
  3920. //
  3921. class Authorization
  3922. {
  3923. private $authorized;
  3924. private $login_failed;
  3925. private $system_password_encrypted;
  3926. public function __construct()
  3927. {
  3928. // first, make sure a CSRF token is generated
  3929. $this->generateToken();
  3930. // second, check for possible CSRF attacks. to protect logins, this is done before checking login
  3931. $this->checkToken();
  3932. // the salt and password encrypting is probably unnecessary protection but is done just
  3933. // for the sake of being very secure
  3934. if(!isset($_SESSION[COOKIENAME.'_salt']) && !isset($_COOKIE[COOKIENAME.'_salt']))
  3935. {
  3936. // create a random salt for this session if a cookie doesn't already exist for it
  3937. $_SESSION[COOKIENAME.'_salt'] = self::generateSalt(22);
  3938. }
  3939. else if(!isset($_SESSION[COOKIENAME.'_salt']) && isset($_COOKIE[COOKIENAME.'_salt']))
  3940. {
  3941. // session doesn't exist, but cookie does so grab it
  3942. $_SESSION[COOKIENAME.'_salt'] = $_COOKIE[COOKIENAME.'_salt'];
  3943. }
  3944. // salted and encrypted password used for checking
  3945. $this->system_password_encrypted = md5(SYSTEMPASSWORD."_".$_SESSION[COOKIENAME.'_salt']);
  3946. $this->authorized =
  3947. // no password
  3948. SYSTEMPASSWORD == ''
  3949. // correct password stored in session
  3950. || isset($_SESSION[COOKIENAME.'password']) && hash_equals($_SESSION[COOKIENAME.'password'], $this->system_password_encrypted)
  3951. // correct password stored in cookie
  3952. || isset($_COOKIE[COOKIENAME]) && isset($_COOKIE[COOKIENAME.'_salt']) && hash_equals(md5(SYSTEMPASSWORD."_".$_COOKIE[COOKIENAME.'_salt']), $_COOKIE[COOKIENAME]);
  3953. }
  3954. public function attemptGrant($password, $remember)
  3955. {
  3956. $hashed_password = crypt(SYSTEMPASSWORD, '$2a$07$'.self::generateSalt(22).'$');
  3957. if (hash_equals($hashed_password, crypt($password, $hashed_password))) {
  3958. if ($remember) {
  3959. // user wants to be remembered, so set a cookie
  3960. $expire = time()+60*60*24*30; //set expiration to 1 month from now
  3961. setcookie(COOKIENAME, $this->system_password_encrypted, $expire, null, null, null, true);
  3962. setcookie(COOKIENAME."_salt", $_SESSION[COOKIENAME.'_salt'], $expire, null, null, null, true);
  3963. } else {
  3964. // user does not want to be remembered, so destroy any potential cookies
  3965. setcookie(COOKIENAME, "", time()-86400, null, null, null, true);
  3966. setcookie(COOKIENAME."_salt", "", time()-86400, null, null, null, true);
  3967. unset($_COOKIE[COOKIENAME]);
  3968. unset($_COOKIE[COOKIENAME.'_salt']);
  3969. }
  3970. $_SESSION[COOKIENAME.'password'] = $this->system_password_encrypted;
  3971. $this->authorized = true;
  3972. return true;
  3973. }
  3974. $this->login_failed = true;
  3975. return false;
  3976. }
  3977. public function revoke()
  3978. {
  3979. //destroy everything - cookies and session vars
  3980. setcookie(COOKIENAME, "", time()-86400, null, null, null, true);
  3981. setcookie(COOKIENAME."_salt", "", time()-86400, null, null, null, true);
  3982. unset($_COOKIE[COOKIENAME]);
  3983. unset($_COOKIE[COOKIENAME.'_salt']);
  3984. session_unset();
  3985. session_destroy();
  3986. $this->authorized = false;
  3987. // start a new session and generate a new CSRF token for the login form
  3988. session_start();
  3989. $this->generateToken();
  3990. }
  3991. public function isAuthorized()
  3992. {
  3993. return $this->authorized;
  3994. }
  3995. public function isFailedLogin()
  3996. {
  3997. return $this->login_failed;
  3998. }
  3999. public function isPasswordDefault()
  4000. {
  4001. return SYSTEMPASSWORD == 'admin';
  4002. }
  4003. private static function generateSalt($saltSize)
  4004. {
  4005. $set = 'ABCDEFGHiJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  4006. $setLast = strlen($set) - 1;
  4007. $salt = '';
  4008. while ($saltSize-- > 0) {
  4009. $salt .= $set[mt_rand(0, $setLast)];
  4010. }
  4011. return $salt;
  4012. }
  4013. private function generateToken()
  4014. {
  4015. // generate CSRF token
  4016. if (empty($_SESSION[COOKIENAME.'token']))
  4017. {
  4018. if (function_exists('random_bytes')) // introduced in PHP 7.0
  4019. {
  4020. $_SESSION[COOKIENAME.'token'] = bin2hex(random_bytes(32));
  4021. }
  4022. elseif (function_exists('openssl_random_pseudo_bytes')) // introduced in PHP 5.3.0
  4023. {
  4024. $_SESSION[COOKIENAME.'token'] = bin2hex(openssl_random_pseudo_bytes(32));
  4025. }
  4026. else
  4027. {
  4028. // For PHP 5.2.x - This case can be removed once we drop support for 5.2.x
  4029. $_SESSION[COOKIENAME.'token'] = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
  4030. }
  4031. }
  4032. }
  4033. private function checkToken()
  4034. {
  4035. // checking CSRF token
  4036. if($_SERVER['REQUEST_METHOD'] === 'POST' || isset($_GET['download'])) // all POST forms need tokens! downloads are protected as well
  4037. {
  4038. if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['token']))
  4039. $check_token=$_POST['token'];
  4040. elseif($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['token']))
  4041. $check_token=$_GET['token'];
  4042. if (!isset($check_token))
  4043. {
  4044. die("CSRF token missing");
  4045. }
  4046. elseif(!hash_equals($_SESSION[COOKIENAME.'token'], $check_token))
  4047. {
  4048. die("CSRF token is wrong - please try to login again");
  4049. }
  4050. }
  4051. }
  4052. }
  4053. // Database class
  4054. // Generic database abstraction class to manage interaction with database without worrying about SQLite vs. PHP versions
  4055. //
  4056. class Database
  4057. {
  4058. protected $db; //reference to the DB object
  4059. protected $type; //the extension for PHP that handles SQLite
  4060. protected $data;
  4061. protected $lastResult;
  4062. protected $alterError;
  4063. protected $debugOutput ='';
  4064. public function __construct($data)
  4065. {
  4066. global $lang, $params;
  4067. $this->data = $data;
  4068. try
  4069. {
  4070. if(!file_exists($this->data["path"]) && !is_writable(dirname($this->data["path"]))) //make sure the containing directory is writable if the database does not exist
  4071. {
  4072. echo "<div class='confirm' style='margin:20px;'>";
  4073. printf($lang['db_not_writeable'], htmlencode($this->data["path"]), htmlencode(dirname($this->data["path"])));
  4074. echo $params->getForm();
  4075. echo "<input type='submit' value='Log Out' name='".$lang['logout']."' class='btn'/>";
  4076. echo "</form>";
  4077. echo "</div><br/>";
  4078. exit();
  4079. }
  4080. $ver = $this->getVersion();
  4081. switch(true)
  4082. {
  4083. case ((!isset($data['type']) || $data['type']!=2) && (FORCETYPE=="PDO" || (FORCETYPE==false && class_exists("PDO") && in_array("sqlite", PDO::getAvailableDrivers()) && ($ver==-1 || $ver==3)))):
  4084. $this->db = new PDO("sqlite:".$this->data['path']);
  4085. if($this->db!=NULL)
  4086. {
  4087. $this->type = "PDO";
  4088. break;
  4089. }
  4090. case ((!isset($data['type']) || $data['type']!=2) && (FORCETYPE=="SQLite3" || (FORCETYPE==false && class_exists("SQLite3") && ($ver==-1 || $ver==3)))):
  4091. $this->db = new SQLite3($this->data['path']);
  4092. if($this->db!=NULL)
  4093. {
  4094. $this->type = "SQLite3";
  4095. break;
  4096. }
  4097. case (FORCETYPE=="SQLiteDatabase" || (FORCETYPE==false && class_exists("SQLiteDatabase") && ($ver==-1 || $ver==2))):
  4098. $this->db = new SQLiteDatabase($this->data['path']);
  4099. if($this->db!=NULL)
  4100. {
  4101. $this->type = "SQLiteDatabase";
  4102. break;
  4103. }
  4104. default:
  4105. $this->showError();
  4106. exit();
  4107. }
  4108. $this->query("PRAGMA foreign_keys = ON");
  4109. }
  4110. catch(Exception $e)
  4111. {
  4112. $this->showError();
  4113. exit();
  4114. }
  4115. }
  4116. public function registerUserFunction($ids)
  4117. {
  4118. // in case a single function id was passed
  4119. if (is_string($ids))
  4120. $ids = array($ids);
  4121. if ($this->type == 'PDO') {
  4122. foreach ($ids as $id) {
  4123. $this->db->sqliteCreateFunction($id, $id, -1);
  4124. }
  4125. } else { // type is Sqlite3 or SQLiteDatabase
  4126. foreach ($ids as $id) {
  4127. $this->db->createFunction($id, $id, -1);
  4128. }
  4129. }
  4130. }
  4131. public function getError($complete_msg = false)
  4132. {
  4133. global $lang, $debug;
  4134. $error = "unknown";
  4135. if($this->alterError!='')
  4136. {
  4137. $error = $this->alterError;
  4138. $this->alterError = "";
  4139. }
  4140. else if($this->type=="PDO")
  4141. {
  4142. $e = $this->db->errorInfo();
  4143. $error = $e[2];
  4144. }
  4145. else if($this->type=="SQLite3")
  4146. {
  4147. $error = $this->db->lastErrorMsg();
  4148. }
  4149. else
  4150. {
  4151. $error = sqlite_error_string($this->db->lastError());
  4152. }
  4153. if($complete_msg)
  4154. {
  4155. $error = $lang['err'].": ".htmlencode($error);
  4156. // do not suggest to report a bug when constraints fail
  4157. if(strpos($error, 'constraint failed')===false)
  4158. $error.="<br/>".$lang['bug_report'].' '.PROJECT_BUGTRACKER_LINK;
  4159. }
  4160. if($debug)
  4161. $error .= $this->getDebugOutput();
  4162. return $error;
  4163. }
  4164. function getDebugOutput()
  4165. {
  4166. return ($this->debugOutput != "" ? "<hr /><strong>DEBUG:</strong><br />".$this->debugOutput : $this->debugOutput);
  4167. }
  4168. public function showError()
  4169. {
  4170. global $lang;
  4171. $classPDO = class_exists("PDO");
  4172. $classSQLite3 = class_exists("SQLite3");
  4173. $classSQLiteDatabase = class_exists("SQLiteDatabase");
  4174. if($classPDO) // PDO is there, check if the SQLite driver for PDO is missing
  4175. $PDOSqliteDriver = (in_array("sqlite", PDO::getAvailableDrivers() ));
  4176. else
  4177. $PDOSqliteDriver = false;
  4178. echo "<div class='confirm' style='margin:20px;'>";
  4179. printf($lang['db_setup'], $this->getPath());
  4180. echo ".<br/><br/><i>".$lang['chk_ext']."...<br/><br/>";
  4181. echo "<b>PDO</b>: ".($classPDO ? $lang['installed'] : $lang['not_installed'])."<br/>";
  4182. echo "<b>PDO SQLite Driver</b>: ".($PDOSqliteDriver ? $lang['installed'] : $lang['not_installed'])."<br/>";
  4183. echo "<b>SQLite3</b>: ".($classSQLite3 ? $lang['installed'] : $lang['not_installed'])."<br/>";
  4184. echo "<b>SQLiteDatabase</b>: ".($classSQLiteDatabase ? $lang['installed'] : $lang['not_installed'])."<br/>";
  4185. echo "<br/>...".$lang['done'].".</i><br/><br/>";
  4186. if(!$classPDO && !$classSQLite3 && !$classSQLiteDatabase)
  4187. printf($lang['sqlite_ext_support'], PROJECT);
  4188. else
  4189. {
  4190. if(!$PDOSqliteDriver && !$classSQLite3 && $this->getVersion()==3)
  4191. printf($lang['sqlite_v_error'], 3, PROJECT, 2);
  4192. else if(!$classSQLiteDatabase && $this->getVersion()==2)
  4193. printf($lang['sqlite_v_error'], 2, PROJECT, 3);
  4194. else
  4195. echo $lang['report_issue'].' '.PROJECT_BUGTRACKER_LINK.'.';
  4196. }
  4197. echo "<p>See ".PROJECT_INSTALL_LINK." for help.</p>";
  4198. $this->print_db_list();
  4199. echo "</div>";
  4200. }
  4201. // print the list of databases
  4202. public function print_db_list()
  4203. {
  4204. global $databases, $lang, $params, $currentDB;
  4205. echo "<fieldset style='margin:15px;' class='databaseList'><legend><b>".$lang['db_ch']."</b></legend>";
  4206. if(sizeof($databases)<10) //if there aren't a lot of databases, just show them as a list of links instead of drop down menu
  4207. {
  4208. $i=0;
  4209. foreach($databases as $database)
  4210. {
  4211. $i++;
  4212. $name = $database['name'];
  4213. if(mb_strlen($name)>25)
  4214. $name = "...".mb_substr($name, mb_strlen($name)-22, 22);
  4215. echo '[' . ($database['readable'] ? 'r':' ' ) . ($database['writable'] && $database['writable_dir'] ? 'w':' ' ) . ']&nbsp;';
  4216. echo $params->getLink(array('database'=>$database['path'], 'table'=>null), htmlencode($name), ($database == $currentDB? 'active_db': '') );
  4217. echo "&nbsp;&nbsp;";
  4218. echo $params->getLink(array('download'=>$database['path'], 'table'=>null, 'token'=>$_SESSION[COOKIENAME.'token']), '[&darr;]', '', $lang['backup']);
  4219. if($i<sizeof($databases))
  4220. echo "<br/>";
  4221. }
  4222. }
  4223. else //there are a lot of databases - show a drop down menu
  4224. {
  4225. echo $params->getForm(array('table'=>null), 'get');
  4226. echo "<select name='database' onchange='this.form.submit()'>";
  4227. foreach($databases as $database)
  4228. {
  4229. $perms_string = htmlencode('[' . ($database['readable'] ? 'r':' ' ) . ($database['writable'] && $database['writable_dir'] ? 'w':' ' ) . '] ');
  4230. if($database == $currentDB)
  4231. echo "<option value='".htmlencode($database['path'])."' selected='selected'>".$perms_string.htmlencode($database['name'])."</option>";
  4232. else
  4233. echo "<option value='".htmlencode($database['path'])."'>".$perms_string.htmlencode($database['name'])."</option>";
  4234. }
  4235. echo "</select>";
  4236. echo "<noscript><input type='submit' value='".$lang['go']."' class='btn'></noscript>";
  4237. echo "</form>";
  4238. }
  4239. echo "</fieldset>";
  4240. }
  4241. public function __destruct()
  4242. {
  4243. if($this->db)
  4244. $this->close();
  4245. }
  4246. //get the exact PHP extension being used for SQLite
  4247. public function getType()
  4248. {
  4249. return $this->type;
  4250. }
  4251. // get the version of the SQLite library
  4252. public function getSQLiteVersion()
  4253. {
  4254. $queryVersion = $this->select("SELECT sqlite_version() AS sqlite_version");
  4255. return $queryVersion['sqlite_version'];
  4256. }
  4257. //get the name of the database
  4258. public function getName()
  4259. {
  4260. return $this->data["name"];
  4261. }
  4262. //get the filename of the database
  4263. public function getPath()
  4264. {
  4265. return $this->data["path"];
  4266. }
  4267. //is the db-file writable?
  4268. public function isWritable()
  4269. {
  4270. return $this->data["writable"];
  4271. }
  4272. //is the db-folder writable?
  4273. public function isDirWritable()
  4274. {
  4275. return $this->data["writable_dir"];
  4276. }
  4277. //get the version of the database
  4278. public function getVersion()
  4279. {
  4280. if(file_exists($this->data['path'])) //make sure file exists before getting its contents
  4281. {
  4282. $content = strtolower(file_get_contents($this->data['path'], NULL, NULL, 0, 40)); //get the first 40 characters of the database file
  4283. $p = strpos($content, "** this file contains an sqlite 2"); //this text is at the beginning of every SQLite2 database
  4284. if($p!==false) //the text is found - this is version 2
  4285. return 2;
  4286. else
  4287. return 3;
  4288. }
  4289. else //return -1 to indicate that it does not exist and needs to be created
  4290. {
  4291. return -1;
  4292. }
  4293. }
  4294. //get the size of the database (in KiB)
  4295. public function getSize()
  4296. {
  4297. return round(filesize($this->data["path"])*0.0009765625, 1);
  4298. }
  4299. //get the last modified time of database
  4300. public function getDate()
  4301. {
  4302. global $lang;
  4303. return date($lang['date_format'], filemtime($this->data['path']));
  4304. }
  4305. //get number of affected rows from last query
  4306. public function getAffectedRows()
  4307. {
  4308. if($this->type=="PDO")
  4309. if(!is_object($this->lastResult))
  4310. // in case it was an alter table statement, there is no lastResult object
  4311. return 0;
  4312. else
  4313. return $this->lastResult->rowCount();
  4314. else if($this->type=="SQLite3")
  4315. return $this->db->changes();
  4316. else if($this->type=="SQLiteDatabase")
  4317. return $this->db->changes();
  4318. }
  4319. public function getTypeOfTable($table)
  4320. {
  4321. $result = $this->select("SELECT `type` FROM `sqlite_master` WHERE `name`=" . $this->quote($table), 'assoc');
  4322. return $result['type'];
  4323. }
  4324. public function getTableInfo($table)
  4325. {
  4326. return $this->selectArray("PRAGMA table_info(".$this->quote_id($table).")");
  4327. }
  4328. // returns the list of tables (opt. incl. views) as
  4329. // array( Tablename => tableType ) with tableType being 'view' or 'table'
  4330. public function getTables($alsoViews=true, $alsoInternal=false, $orderBy='name', $orderDirection='ASC')
  4331. {
  4332. $query = "SELECT name, type FROM sqlite_master "
  4333. . "WHERE (type='table'".($alsoViews?" OR type='view'":"").") "
  4334. . "AND name!='' ".($alsoInternal? "":" AND name NOT LIKE 'sqlite_%' ")
  4335. . "ORDER BY ".$this->quote_id($orderBy)." ".$orderDirection;
  4336. $result = $this->selectArray($query);
  4337. $list = array();
  4338. for($i=0; $i<sizeof($result); $i++)
  4339. {
  4340. $list[$result[$i]['name']] = $result[$i]['type'];
  4341. }
  4342. return $list;
  4343. }
  4344. // returns an array of all tables and their columns as
  4345. // array( tablename => array(columName) )
  4346. public function getTableDefinitions()
  4347. {
  4348. $tables = $this->getTables(true, true);
  4349. $result = array();
  4350. foreach ($tables as $tableName => $tableType)
  4351. {
  4352. $tableInfo = $this->getTableInfo($tableName);
  4353. $columns = array();
  4354. foreach($tableInfo as $column)
  4355. $columns[] = $column['name'];
  4356. $result[$tableName] = $columns;
  4357. }
  4358. return $result;
  4359. }
  4360. public function close()
  4361. {
  4362. if($this->type=="PDO")
  4363. $this->db = NULL;
  4364. else if($this->type=="SQLite3")
  4365. $this->db->close();
  4366. else if($this->type=="SQLiteDatabase")
  4367. $this->db = NULL;
  4368. }
  4369. public function beginTransaction()
  4370. {
  4371. $this->query("BEGIN");
  4372. }
  4373. public function commitTransaction()
  4374. {
  4375. $this->query("COMMIT");
  4376. }
  4377. public function rollbackTransaction()
  4378. {
  4379. $this->query("ROLLBACK");
  4380. }
  4381. //generic query wrapper
  4382. //returns false on error and the query result on success
  4383. public function query($query, $ignoreAlterCase=false)
  4384. {
  4385. global $debug;
  4386. if(strtolower(substr(ltrim($query),0,5))=='alter' && $ignoreAlterCase==false) //this query is an ALTER query - call the necessary function
  4387. {
  4388. preg_match("/^\s*ALTER\s+TABLE\s+\"((?:[^\"]|\"\")+)\"\s+(.*)$/i",$query,$matches);
  4389. if(!isset($matches[1]) || !isset($matches[2]))
  4390. {
  4391. if($debug) echo "<span title='".htmlencode($query)."' onclick='this.innerHTML=\"".htmlencode(str_replace('"','\"',$query))."\"' style='cursor:pointer'>SQL?</span><br />";
  4392. return false;
  4393. }
  4394. $tablename = str_replace('""','"',$matches[1]);
  4395. $alterdefs = $matches[2];
  4396. if($debug) echo "ALTER TABLE QUERY=(".htmlencode($query)."), tablename=($tablename), alterdefs=($alterdefs)<br />";
  4397. $result = $this->alterTable($tablename, $alterdefs);
  4398. }
  4399. else //this query is normal - proceed as normal
  4400. {
  4401. $result = $this->db->query($query);
  4402. if($debug) echo "<span title='".htmlencode($query)."' onclick='this.innerHTML=\"".htmlencode(str_replace('"','\"',$query))."\"' style='cursor:pointer'>SQL?</span><br />";
  4403. }
  4404. if($result===false)
  4405. return false;
  4406. $this->lastResult = $result;
  4407. return $result;
  4408. }
  4409. //wrapper for an INSERT and returns the ID of the inserted row
  4410. public function insert($query)
  4411. {
  4412. $result = $this->query($query);
  4413. if($this->type=="PDO")
  4414. return $this->db->lastInsertId();
  4415. else if($this->type=="SQLite3")
  4416. return $this->db->lastInsertRowID();
  4417. else if($this->type=="SQLiteDatabase")
  4418. return $this->db->lastInsertRowid();
  4419. }
  4420. //returns an array for SELECT
  4421. public function select($query, $mode="both")
  4422. {
  4423. $result = $this->query($query);
  4424. if(!$result) //make sure the result is valid
  4425. return NULL;
  4426. if($this->type=="PDO")
  4427. {
  4428. if($mode=="assoc")
  4429. $mode = PDO::FETCH_ASSOC;
  4430. else if($mode=="num")
  4431. $mode = PDO::FETCH_NUM;
  4432. else
  4433. $mode = PDO::FETCH_BOTH;
  4434. $ret = $result->fetch($mode);
  4435. $result->closeCursor();
  4436. return $ret;
  4437. }
  4438. else if($this->type=="SQLite3")
  4439. {
  4440. if($mode=="assoc")
  4441. $mode = SQLITE3_ASSOC;
  4442. else if($mode=="num")
  4443. $mode = SQLITE3_NUM;
  4444. else
  4445. $mode = SQLITE3_BOTH;
  4446. $ret = $result->fetchArray($mode);
  4447. $result->finalize();
  4448. return $ret;
  4449. }
  4450. else if($this->type=="SQLiteDatabase")
  4451. {
  4452. if($mode=="assoc")
  4453. $mode = SQLITE_ASSOC;
  4454. else if($mode=="num")
  4455. $mode = SQLITE_NUM;
  4456. else
  4457. $mode = SQLITE_BOTH;
  4458. return $result->fetch($mode);
  4459. }
  4460. }
  4461. //returns an array of arrays after doing a SELECT
  4462. public function selectArray($query, $mode="both")
  4463. {
  4464. $result = $this->query($query);
  4465. //make sure the result is valid
  4466. if($result=== false || $result===NULL)
  4467. return NULL; // error
  4468. if(!is_object($result)) // no rows returned
  4469. return array();
  4470. if($this->type=="PDO")
  4471. {
  4472. if($mode=="assoc")
  4473. $mode = PDO::FETCH_ASSOC;
  4474. else if($mode=="num")
  4475. $mode = PDO::FETCH_NUM;
  4476. else
  4477. $mode = PDO::FETCH_BOTH;
  4478. $ret = $result->fetchAll($mode);
  4479. $result->closeCursor();
  4480. return $ret;
  4481. }
  4482. else if($this->type=="SQLite3")
  4483. {
  4484. if($mode=="assoc")
  4485. $mode = SQLITE3_ASSOC;
  4486. else if($mode=="num")
  4487. $mode = SQLITE3_NUM;
  4488. else
  4489. $mode = SQLITE3_BOTH;
  4490. $arr = array();
  4491. $i = 0;
  4492. while($res = $result->fetchArray($mode))
  4493. {
  4494. $arr[$i] = $res;
  4495. $i++;
  4496. }
  4497. $result->finalize();
  4498. return $arr;
  4499. }
  4500. else if($this->type=="SQLiteDatabase")
  4501. {
  4502. if($mode=="assoc")
  4503. $mode = SQLITE_ASSOC;
  4504. else if($mode=="num")
  4505. $mode = SQLITE_NUM;
  4506. else
  4507. $mode = SQLITE_BOTH;
  4508. return $result->fetchAll($mode);
  4509. }
  4510. }
  4511. //returns an array of the next row in $result
  4512. public function fetch($result, $mode="both")
  4513. {
  4514. //make sure the result is valid
  4515. if($result=== false || $result===NULL)
  4516. return NULL; // error
  4517. if(!is_object($result)) // no rows returned
  4518. return array();
  4519. if($this->type=="PDO")
  4520. {
  4521. if($mode=="assoc")
  4522. $mode = PDO::FETCH_ASSOC;
  4523. else if($mode=="num")
  4524. $mode = PDO::FETCH_NUM;
  4525. else
  4526. $mode = PDO::FETCH_BOTH;
  4527. return $result->fetch($mode);
  4528. }
  4529. else if($this->type=="SQLite3")
  4530. {
  4531. if($mode=="assoc")
  4532. $mode = SQLITE3_ASSOC;
  4533. else if($mode=="num")
  4534. $mode = SQLITE3_NUM;
  4535. else
  4536. $mode = SQLITE3_BOTH;
  4537. return $result->fetchArray($mode);
  4538. }
  4539. else if($this->type=="SQLiteDatabase")
  4540. {
  4541. if($mode=="assoc")
  4542. $mode = SQLITE_ASSOC;
  4543. else if($mode=="num")
  4544. $mode = SQLITE_NUM;
  4545. else
  4546. $mode = SQLITE_BOTH;
  4547. return $result->fetch($mode);
  4548. }
  4549. }
  4550. public function getColumnName($result, $colNum)
  4551. {
  4552. //make sure the result is valid
  4553. if($result=== false || $result===NULL || !is_object($result))
  4554. return ""; // error or no rows returned
  4555. if($this->type=="PDO")
  4556. {
  4557. $meta = $result->getColumnMeta($colNum);
  4558. return $meta['name'];
  4559. }
  4560. else if($this->type=="SQLite3")
  4561. {
  4562. return $result->columnName($colNum);
  4563. }
  4564. else if($this->type=="SQLiteDatabase")
  4565. {
  4566. return $result->fieldName($colNum);
  4567. }
  4568. }
  4569. // SQlite supports multiple ways of surrounding names in quotes:
  4570. // single-quotes, double-quotes, backticks, square brackets.
  4571. // As sqlite does not keep this strict, we also need to be flexible here.
  4572. // This function generates a regex that matches any of the possibilities.
  4573. private function sqlite_surroundings_preg($name,$preg_quote=true,$notAllowedCharsIfNone="'\"",$notAllowedName=false)
  4574. {
  4575. if($name=="*" || $name=="+")
  4576. {
  4577. if($notAllowedName!==false && $preg_quote)
  4578. $notAllowedName = preg_quote($notAllowedName,"/");
  4579. // use possesive quantifiers to save memory
  4580. // (There is a bug in PCRE starting in 8.13 and fixed in PCRE 8.36
  4581. // why we can't use posesive quantifiers - See issue #310).
  4582. if(version_compare(strstr(constant('PCRE_VERSION'), ' ', true), '8.36', '>=') ||
  4583. version_compare(strstr(constant('PCRE_VERSION'), ' ', true), '8.12', '<='))
  4584. $posessive='+';
  4585. else
  4586. $posessive='';
  4587. $nameSingle = ($notAllowedName!==false?"(?!".$notAllowedName."')":"")."(?:[^']$name+|'')$name".$posessive;
  4588. $nameDouble = ($notAllowedName!==false?"(?!".$notAllowedName."\")":"")."(?:[^\"]$name+|\"\")$name".$posessive;
  4589. $nameBacktick = ($notAllowedName!==false?"(?!".$notAllowedName."`)":"")."(?:[^`]$name+|``)$name".$posessive;
  4590. $nameSquare = ($notAllowedName!==false?"(?!".$notAllowedName."\])":"")."(?:[^\]]$name+|\]\])$name".$posessive;
  4591. $nameNo = ($notAllowedName!==false?"(?!".$notAllowedName."\s)":"")."[^".$notAllowedCharsIfNone."]$name";
  4592. }
  4593. else
  4594. {
  4595. if($preg_quote) $name = preg_quote($name,"/");
  4596. $nameSingle = str_replace("'","''",$name);
  4597. $nameDouble = str_replace('"','""',$name);
  4598. $nameBacktick = str_replace('`','``',$name);
  4599. $nameSquare = str_replace(']',']]',$name);
  4600. $nameNo = $name;
  4601. }
  4602. $preg = "(?:'".$nameSingle."'|". // single-quote surrounded or not in quotes (correct SQL for values/new names)
  4603. $nameNo."|". // not surrounded (correct SQL if not containing reserved words, spaces or some special chars)
  4604. "\"".$nameDouble."\"|". // double-quote surrounded (correct SQL for identifiers)
  4605. "`".$nameBacktick."`|". // backtick surrounded (MySQL-Style)
  4606. "\[".$nameSquare."\])"; // square-bracket surrounded (MS Access/SQL server-Style)
  4607. return $preg;
  4608. }
  4609. // Returns the last PREG error as a string, '' if no error occured
  4610. private function getPregError()
  4611. {
  4612. $error = preg_last_error();
  4613. switch ($error)
  4614. {
  4615. case PREG_NO_ERROR: return 'No error';
  4616. case PREG_INTERNAL_ERROR: return 'There is an internal error!';
  4617. case PREG_BACKTRACK_LIMIT_ERROR: return 'Backtrack limit was exhausted!';
  4618. case PREG_RECURSION_LIMIT_ERROR: return 'Recursion limit was exhausted!';
  4619. case PREG_BAD_UTF8_ERROR: return 'Bad UTF8 error!';
  4620. // PREG_BAD_UTF8_OFFSET_ERROR is introduced in PHP 5.3.0, which is not yet required by PLA, so we use its value 5 instead so long
  4621. case 5: return 'Bad UTF8 offset error!';
  4622. default: return 'Unknown Error';
  4623. }
  4624. }
  4625. // function that is called for an alter table statement in a query
  4626. // code borrowed with permission from http://code.jenseng.com/db/
  4627. // this has been completely debugged / rewritten by Christopher Kramer
  4628. public function alterTable($table, $alterdefs)
  4629. {
  4630. global $debug, $lang;
  4631. $this->alterError="";
  4632. $errormsg = sprintf($lang['alter_failed'],htmlencode($table)).' - ';
  4633. if($debug) $this->debugOutput .= "ALTER TABLE: table=($table), alterdefs=($alterdefs), PCRE version=(".PCRE_VERSION.")<hr /><br />";
  4634. if($alterdefs != '')
  4635. {
  4636. $recreateQueries = array();
  4637. $resultArr = $this->selectArray("SELECT sql,name,type FROM sqlite_master WHERE tbl_name = ".$this->quote($table));
  4638. if(sizeof($resultArr)<1)
  4639. {
  4640. $this->alterError = $errormsg . sprintf($lang['tbl_inexistent'], htmlencode($table));
  4641. if($debug) $this->debugOutput .= "ERROR: unknown table<hr /><br />";
  4642. return false;
  4643. }
  4644. for($i=0; $i<sizeof($resultArr); $i++)
  4645. {
  4646. $row = $resultArr[$i];
  4647. if($row['type'] != 'table' && $row['type'] != 'view')
  4648. {
  4649. if($row['sql']!='')
  4650. {
  4651. // store the CREATE statements of triggers and indexes to recreate them later
  4652. $recreateQueries[] = $row;
  4653. if($debug) $this->debugOutput .= "recreate=(".$row['sql'].";)<br />";
  4654. }
  4655. }
  4656. elseif($row['type']=='view') // workaround to rename views
  4657. {
  4658. $origsql = $row['sql'];
  4659. $preg_remove_create_view = "/^\s*+CREATE\s++VIEW\s++".$this->sqlite_surroundings_preg($table)."\s*+(AS\s++SELECT\s++.*+)$/is";
  4660. $origsql_no_create = preg_replace($preg_remove_create_view, '$1', $origsql, 1);
  4661. if($debug) $this->debugOutput .= "origsql=($origsql)<br />preg_remove_create_table=($preg_remove_create_view)<br />";
  4662. preg_match("/RENAME\s++TO\s++(?:\"((?:[^\"]|\"\")+)\"|'((?:[^']|'')+)')/is", $alterdefs, $matches);
  4663. if(isset($matches[1]) && $matches[1]!='')
  4664. $newname = $matches[1];
  4665. elseif(isset($matches[2]) && $matches[2]!='')
  4666. $newname = $matches[2];
  4667. else
  4668. {
  4669. $this->alterError = $errormsg . ' could not detect new view name. It needs to be in single or double quotes.';
  4670. if($debug) $this->debugOutput .= "ERROR: could not detect new view name<hr />";
  4671. return false;
  4672. }
  4673. $dropoldSQL = 'DROP VIEW '.$this->quote_id($table);
  4674. $createnewSQL = 'CREATE VIEW '.$this->quote_id($newname).' '.$origsql_no_create;
  4675. $alter_transaction = 'BEGIN; ' . $dropoldSQL .'; '. $createnewSQL . '; ' . 'COMMIT;';
  4676. if($debug) $this->debugOutput .= $alter_transaction;
  4677. return $this->multiQuery($alter_transaction);
  4678. }
  4679. else
  4680. {
  4681. // ALTER the table
  4682. $tmpname = 't'.time();
  4683. $origsql = $row['sql'];
  4684. $preg_remove_create_table = "/^\s*+CREATE\s++TABLE\s++".$this->sqlite_surroundings_preg($table)."\s*+(\(.*+)$/is";
  4685. $origsql_no_create = preg_replace($preg_remove_create_table, '$1', $origsql, 1);
  4686. if($debug) $this->debugOutput .= "origsql=($origsql)<br />preg_remove_create_table=($preg_remove_create_table)<br />";
  4687. if($origsql_no_create == $origsql)
  4688. {
  4689. $this->alterError = $errormsg . $lang['alter_tbl_name_not_replacable'];
  4690. if($debug) $this->debugOutput .= "ERROR: could not get rid of CREATE TABLE<hr />";
  4691. return false;
  4692. }
  4693. $createtemptableSQL = "CREATE TABLE ".$this->quote($tmpname)." ".$origsql_no_create;
  4694. if($debug) $this->debugOutput .= "createtemptableSQL=($createtemptableSQL)<br />";
  4695. $createindexsql = array();
  4696. $preg_alter_part = "/(?:DROP(?! PRIMARY KEY)|ADD(?! PRIMARY KEY)|CHANGE|RENAME TO|ADD PRIMARY KEY|DROP PRIMARY KEY)" // the ALTER command
  4697. ."(?:"
  4698. ."\s+\(".$this->sqlite_surroundings_preg("+",false,"\"'\[`)")."+\)" // stuff in brackets (in case of ADD PRIMARY KEY)
  4699. ."|" // or
  4700. ."\s+".$this->sqlite_surroundings_preg("+",false,",'\"\[`") // column names and stuff like this
  4701. .")*/i";
  4702. if($debug)
  4703. $this->debugOutput .= "preg_alter_part=(".$preg_alter_part.")<br />";
  4704. preg_match_all($preg_alter_part,$alterdefs,$matches);
  4705. $defs = $matches[0];
  4706. $result_oldcols = $this->getTableInfo($table);
  4707. $newcols = array();
  4708. $coltypes = array();
  4709. $primarykey = array();
  4710. foreach($result_oldcols as $column_info)
  4711. {
  4712. $newcols[$column_info['name']] = $column_info['name'];
  4713. $coltypes[$column_info['name']] = $column_info['type'];
  4714. if($column_info['pk'])
  4715. $primarykey[] = $column_info['name'];
  4716. }
  4717. $newcolumns = '';
  4718. $oldcolumns = '';
  4719. reset($newcols);
  4720. while(list($key, $val) = each($newcols))
  4721. {
  4722. $newcolumns .= ($newcolumns?', ':'').$this->quote_id($val);
  4723. $oldcolumns .= ($oldcolumns?', ':'').$this->quote_id($key);
  4724. }
  4725. $copytotempsql = 'INSERT INTO '.$this->quote_id($tmpname).'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$this->quote_id($table);
  4726. $dropoldsql = 'DROP TABLE '.$this->quote_id($table);
  4727. $createtesttableSQL = $createtemptableSQL;
  4728. if(count($defs)<1)
  4729. {
  4730. $this->alterError = $errormsg . $lang['alter_no_def'];
  4731. if($debug) $this->debugOutput .= "ERROR: defs&lt;1<hr /><br />";
  4732. return false;
  4733. }
  4734. foreach($defs as $def)
  4735. {
  4736. if($debug) $this->debugOutput .= "<hr />def=$def<br />";
  4737. $preg_parse_def =
  4738. "/^(DROP(?! PRIMARY KEY)|ADD(?! PRIMARY KEY)|CHANGE|RENAME TO|ADD PRIMARY KEY|DROP PRIMARY KEY)" // $matches[1]: command
  4739. ."(?:" // this is either
  4740. ."(?:\s+\((.+)\)\s*$)" // anything in brackets (for ADD PRIMARY KEY)
  4741. // then $matches[2] is what there is in brackets
  4742. ."|" // OR:
  4743. ."(?:\s+\"((?:[^\"]|\"\")+)\"|\s+'((?:[^']|'')+)')"// (first) column name, either in single or double quotes
  4744. // in case of RENAME TO, it is the new a table name
  4745. // $matches[3] will be the column/table name without the quotes if double quoted
  4746. // $matches[4] will be the column/table name without the quotes if single quoted
  4747. ."(" // $matches[5]: anything after the column name
  4748. ."(?:\s+'((?:[^']|'')+)')?" // $matches[6] (optional): a second column name surrounded with single quotes
  4749. // (the match does not contain the quotes)
  4750. ."\s*"
  4751. ."((?:[A-Z]+\s*)+(?:\(\s*[+-]?\s*[0-9]+(?:\s*,\s*[+-]?\s*[0-9]+)?\s*\))?)?\s*" // $matches[7] (optional): a type name
  4752. .".*".
  4753. ")"
  4754. ."?\s*$"
  4755. .")?\s*$/i"; // in case of DROP PRIMARY KEY, there is nothing after the command
  4756. if($debug) $this->debugOutput .= "preg_parse_def=$preg_parse_def<br />";
  4757. $parse_def = preg_match($preg_parse_def,$def,$matches);
  4758. if($parse_def===false)
  4759. {
  4760. $this->alterError = $errormsg . $lang['alter_parse_failed'];
  4761. if($debug) $this->debugOutput .= "ERROR: !parse_def<hr /><br />";
  4762. return false;
  4763. }
  4764. if(!isset($matches[1]))
  4765. {
  4766. $this->alterError = $errormsg . $lang['alter_action_not_recognized'];
  4767. if($debug) $this->debugOutput .= "ERROR: !isset(matches[1])<hr /><br />";
  4768. return false;
  4769. }
  4770. $action = strtolower($matches[1]);
  4771. if(($action == 'add' || $action == 'rename to') && isset($matches[4]) && $matches[4]!='')
  4772. $column = str_replace("''","'",$matches[4]); // enclosed in ''
  4773. elseif($action == 'add primary key' && isset($matches[2]) && $matches[2]!='')
  4774. $column = $matches[2];
  4775. elseif($action == 'drop primary key')
  4776. $column = ''; // DROP PRIMARY KEY has no column definition
  4777. elseif(isset($matches[3]) && $matches[3]!='')
  4778. $column = str_replace('""','"',$matches[3]); // enclosed in ""
  4779. else
  4780. $column = '';
  4781. $column_escaped = str_replace("'","''",$column);
  4782. if($debug) $this->debugOutput .= "action=($action), column=($column), column_escaped=($column_escaped)<br />";
  4783. /* we build a regex that devides the CREATE TABLE statement parts:
  4784. Part example Group Explanation
  4785. 1. CREATE TABLE t... ( $1
  4786. 2. 'col1' ..., 'col2' ..., 'colN' ..., $3 (with col1-colN being columns that are not changed and listed before the col to change)
  4787. 3. 'colX' ..., (with colX being the column to change/drop)
  4788. 4. 'colX+1' ..., ..., 'colK') $5 (with colX+1-colK being columns after the column to change/drop)
  4789. */
  4790. $preg_create_table = "\s*+(CREATE\s++TABLE\s++".preg_quote($this->quote($tmpname),"/")."\s*+\()"; // This is group $1 (keep unchanged)
  4791. $preg_column_definiton = "\s*+".$this->sqlite_surroundings_preg("+",true," '\"\[`,",$column)."(?:\s*+".$this->sqlite_surroundings_preg("*",false,"'\",`\[ ").")++"; // catches a complete column definition, even if it is
  4792. // 'column' TEXT NOT NULL DEFAULT 'we have a comma, here and a double ''quote!'
  4793. // this definition does NOT match columns with the column name $column
  4794. if($debug) $this->debugOutput .= "preg_column_definition=(".$preg_column_definiton.")<br />";
  4795. $preg_columns_before = // columns before the one changed/dropped (keep)
  4796. "(?:".
  4797. "(". // group $2. Keep this one unchanged!
  4798. "(?:".
  4799. "$preg_column_definiton,\s*+". // column definition + comma
  4800. ")*". // there might be any number of such columns here
  4801. $preg_column_definiton. // last column definition
  4802. ")". // end of group $2
  4803. ",\s*+" // the last comma of the last column before the column to change. Do not keep it!
  4804. .")?"; // there might be no columns before
  4805. if($debug) $this->debugOutput .= "preg_columns_before=(".$preg_columns_before.")<br />";
  4806. $preg_columns_after = "(,\s*(.+))?"; // the columns after the column to drop. This is group $3 (drop) or $4(change) (keep!)
  4807. // we could remove the comma using $6 instead of $5, but then we might have no comma at all.
  4808. // Keeping it leaves a problem if we drop the first column, so we fix that case in another regex.
  4809. $table_new = $table;
  4810. switch($action)
  4811. {
  4812. case 'add':
  4813. if($column=='')
  4814. {
  4815. $this->alterError = $errormsg . ' (add) - '. $lang['alter_no_add_col'];
  4816. return false;
  4817. }
  4818. $new_col_definition = "'$column_escaped' ".(isset($matches[5])?$matches[5]:'');
  4819. $preg_pattern_add = "/^".$preg_create_table. // the CREATE TABLE statement ($1)
  4820. "((?:(?!,\s*(?:PRIMARY\s+KEY\s*\(|CONSTRAINT\s|UNIQUE\s*\(|CHECK\s*\(|FOREIGN\s+KEY\s*\()).)*)". // column definitions ($2)
  4821. "(.*)\\)\s*$/si"; // table-constraints like PRIMARY KEY(a,b) ($3) and the closing bracket
  4822. // append the column definiton in the CREATE TABLE statement
  4823. $newSQL = preg_replace($preg_pattern_add, '$1$2, '.strtr($new_col_definition, array('\\' => '\\\\', '$' => '\$')).' $3', $createtesttableSQL).')';
  4824. $preg_error = $this->getPregError();
  4825. if($debug)
  4826. {
  4827. $this->debugOutput .= $createtesttableSQL."<hr /><br />";
  4828. $this->debugOutput .= $newSQL."<hr /><br />";
  4829. $this->debugOutput .= $preg_pattern_add."<hr /><br />";
  4830. }
  4831. if($newSQL==$createtesttableSQL) // pattern did not match, so column adding did not succed
  4832. {
  4833. $this->alterError = $errormsg . ' (add) - '.$lang['alter_pattern_mismatch'].'. PREG ERROR: '.$preg_error;
  4834. return false;
  4835. }
  4836. $createtesttableSQL = $newSQL;
  4837. break;
  4838. case 'change':
  4839. var_dump($matches);
  4840. if(!isset($matches[6]))
  4841. {
  4842. $this->alterError = $errormsg . ' (change) - '.$lang['alter_col_not_recognized'];
  4843. return false;
  4844. }
  4845. $new_col_name = $matches[6];
  4846. if(!isset($matches[7]))
  4847. $new_col_type = '';
  4848. else
  4849. $new_col_type = $matches[7];
  4850. $new_col_definition = "'$new_col_name' $new_col_type";
  4851. $preg_column_to_change = "\s*".$this->sqlite_surroundings_preg($column)."(?:\s+".preg_quote($coltypes[$column]).")?(\s+(?:".$this->sqlite_surroundings_preg("*",false,",'\"`\[").")+)?";
  4852. // replace this part (we want to change this column)
  4853. // group $3 contains the column constraints (keep!). the name & data type is replaced.
  4854. $preg_pattern_change = "/^".$preg_create_table.$preg_columns_before.$preg_column_to_change.$preg_columns_after."\s*\\)\s*$/s";
  4855. // replace the column definiton in the CREATE TABLE statement
  4856. $newSQL = preg_replace($preg_pattern_change, '$1$2,'.strtr($new_col_definition, array('\\' => '\\\\', '$' => '\$')).'$3$4)', $createtesttableSQL);
  4857. $preg_error = $this->getPregError();
  4858. // remove comma at the beginning if the first column is changed
  4859. // probably somebody is able to put this into the first regex (using lookahead probably).
  4860. $newSQL = preg_replace("/^\s*(CREATE\s+TABLE\s+".preg_quote($this->quote($tmpname),"/")."\s+\(),\s*/",'$1',$newSQL);
  4861. if($debug)
  4862. {
  4863. $this->debugOutput .= "preg_column_to_change=(".$preg_column_to_change.")<hr /><br />";
  4864. $this->debugOutput .= $createtesttableSQL."<hr /><br />";
  4865. $this->debugOutput .= $newSQL."<hr /><br />";
  4866. $this->debugOutput .= $preg_pattern_change."<hr /><br />";
  4867. }
  4868. if($newSQL==$createtesttableSQL || $newSQL=="") // pattern did not match, so column removal did not succed
  4869. {
  4870. $this->alterError = $errormsg . ' (change) - '.$lang['alter_pattern_mismatch'].'. PREG ERROR: '.$preg_error;
  4871. return false;
  4872. }
  4873. $createtesttableSQL = $newSQL;
  4874. $newcols[$column] = str_replace("''","'",$new_col_name);
  4875. break;
  4876. case 'drop':
  4877. $preg_column_to_drop = "\s*".$this->sqlite_surroundings_preg($column)."\s+(?:".$this->sqlite_surroundings_preg("*",false,",'\"\[`").")+"; // delete this part (we want to drop this column)
  4878. $preg_pattern_drop = "/^".$preg_create_table.$preg_columns_before.$preg_column_to_drop.$preg_columns_after."\s*\\)\s*$/s";
  4879. // remove the column out of the CREATE TABLE statement
  4880. $newSQL = preg_replace($preg_pattern_drop, '$1$2$3)', $createtesttableSQL);
  4881. $preg_error = $this->getPregError();
  4882. // remove comma at the beginning if the first column is removed
  4883. // probably somebody is able to put this into the first regex (using lookahead probably).
  4884. $newSQL = preg_replace("/^\s*(CREATE\s+TABLE\s+".preg_quote($this->quote($tmpname),"/")."\s+\(),\s*/",'$1',$newSQL);
  4885. if($debug)
  4886. {
  4887. $this->debugOutput .= $createtesttableSQL."<hr /><br />";
  4888. $this->debugOutput .= $newSQL."<hr /><br />";
  4889. $this->debugOutput .= $preg_pattern_drop."<hr /><br />";
  4890. }
  4891. if($newSQL==$createtesttableSQL || $newSQL=="") // pattern did not match, so column removal did not succed
  4892. {
  4893. $this->alterError = $errormsg . ' (drop) - '.$lang['alter_pattern_mismatch'].'. PREG ERROR: '.$preg_error;
  4894. return false;
  4895. }
  4896. $createtesttableSQL = $newSQL;
  4897. unset($newcols[$column]);
  4898. break;
  4899. case 'rename to':
  4900. // don't change column definition at all
  4901. $newSQL = $createtesttableSQL;
  4902. // only change the name of the table
  4903. $table_new = $column;
  4904. break;
  4905. case 'add primary key':
  4906. // we want to add a primary key for the column(s) stored in $column
  4907. $newSQL = preg_replace("/\)\s*$/", ", PRIMARY KEY (".$column.") )", $createtesttableSQL);
  4908. $createtesttableSQL = $newSQL;
  4909. break;
  4910. case 'drop primary key':
  4911. // we want to drop the primary key
  4912. if($debug) $this->debugOutput .= "DROP";
  4913. if(sizeof($primarykey)==1)
  4914. {
  4915. // if not compound primary key, might be a column constraint -> try removal
  4916. $column = $primarykey[0];
  4917. if($debug) $this->debugOutput .= "<br>Trying to drop column constraint for column $column <br>";
  4918. /*
  4919. TODO: This does not work yet:
  4920. CREATE TABLE 't12' ('t1' INTEGER CONSTRAINT "bla" NOT NULL CONSTRAINT 'pk' PRIMARY KEY ); ALTER TABLE "t12" DROP PRIMARY KEY
  4921. This does: ! !
  4922. CREATE TABLE 't12' ('t1' INTEGER CONSTRAINT bla NOT NULL CONSTRAINT 'pk' PRIMARY KEY ); ALTER TABLE "t12" DROP PRIMARY KEY
  4923. */
  4924. $preg_column_to_change = "(\s*".$this->sqlite_surroundings_preg($column).")". // column ($3)
  4925. "(?:". // opt. type and column constraints
  4926. "(\s+(?:".$this->sqlite_surroundings_preg("(?:[^PC,'\"`\[]|P(?!RIMARY\s+KEY)|".
  4927. "C(?!ONSTRAINT\s+".$this->sqlite_surroundings_preg("+",false," ,'\"\[`")."\s+PRIMARY\s+KEY))",false,",'\"`\[").")*)". // column constraints before PRIMARY KEY ($3)
  4928. // primary key constraint (remove this!):
  4929. "(?:CONSTRAINT\s+".$this->sqlite_surroundings_preg("+",false," ,'\"\[`")."\s+)?".
  4930. "PRIMARY\s+KEY".
  4931. "(?:\s+(?:ASC|DESC))?".
  4932. "(?:\s+ON\s+CONFLICT\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?".
  4933. "(?:\s+AUTOINCREMENT)?".
  4934. "((?:".$this->sqlite_surroundings_preg("*",false,",'\"`\[").")*)". // column constraints after PRIMARY KEY ($4)
  4935. ")";
  4936. // replace this part (we want to change this column)
  4937. // group $3 (column) $4 (constraints before) and $5 (constraints after) contain the part to keep
  4938. $preg_pattern_change = "/^".$preg_create_table.$preg_columns_before.$preg_column_to_change.$preg_columns_after."\s*\\)\s*$/si";
  4939. // replace the column definiton in the CREATE TABLE statement
  4940. $newSQL = preg_replace($preg_pattern_change, '$1$2,$3$4$5$6)', $createtesttableSQL);
  4941. // remove comma at the beginning if the first column is changed
  4942. // probably somebody is able to put this into the first regex (using lookahead probably).
  4943. $newSQL = preg_replace("/^\s*(CREATE\s+TABLE\s+".preg_quote($this->quote($tmpname),"/")."\s+\(),\s*/",'$1',$newSQL);
  4944. if($debug)
  4945. {
  4946. $this->debugOutput .= "preg_column_to_change=(".$preg_column_to_change.")<hr /><br />";
  4947. $this->debugOutput .= $createtesttableSQL."<hr /><br />";
  4948. $this->debugOutput .= $newSQL."<hr /><br />";
  4949. $this->debugOutput .= $preg_pattern_change."<hr /><br />";
  4950. }
  4951. if($newSQL!=$createtesttableSQL && $newSQL!="") // pattern did match, so PRIMARY KEY constraint removed :)
  4952. {
  4953. $createtesttableSQL = $newSQL;
  4954. if($debug) $this->debugOutput .= "<br>SUCCEEDED<br>";
  4955. }
  4956. else
  4957. {
  4958. if($debug) $this->debugOutput .= "NO LUCK";
  4959. // TODO: try removing table constraint
  4960. return false;
  4961. }
  4962. $createtesttableSQL = $newSQL;
  4963. } else
  4964. // TODO: Try removing table constraint
  4965. return false;
  4966. break;
  4967. default:
  4968. if($debug) $this->debugOutput .= 'ERROR: unknown alter operation!<hr /><br />';
  4969. $this->alterError = $errormsg . $lang['alter_unknown_operation'];
  4970. return false;
  4971. }
  4972. }
  4973. $droptempsql = 'DROP TABLE '.$this->quote_id($tmpname);
  4974. $createnewtableSQL = "CREATE TABLE ".$this->quote($table_new)." ".preg_replace("/^\s*CREATE\s+TABLE\s+'?".str_replace("'","''",preg_quote($tmpname,"/"))."'?\s+(.*)$/is", '$1', $createtesttableSQL, 1);
  4975. $newcolumns = '';
  4976. $oldcolumns = '';
  4977. reset($newcols);
  4978. while(list($key,$val) = each($newcols))
  4979. {
  4980. $newcolumns .= ($newcolumns?', ':'').$this->quote_id($val);
  4981. $oldcolumns .= ($oldcolumns?', ':'').$this->quote_id($key);
  4982. }
  4983. $copytonewsql = 'INSERT INTO '.$this->quote_id($table_new).'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$this->quote_id($tmpname);
  4984. }
  4985. }
  4986. $alter_transaction = 'BEGIN; ';
  4987. $alter_transaction .= $createtemptableSQL.'; '; //create temp table
  4988. $alter_transaction .= $copytotempsql.'; '; //copy to table
  4989. $alter_transaction .= $dropoldsql.'; '; //drop old table
  4990. $alter_transaction .= $createnewtableSQL.'; '; //recreate original table
  4991. $alter_transaction .= $copytonewsql.'; '; //copy back to original table
  4992. $alter_transaction .= $droptempsql.'; '; //drop temp table
  4993. $preg_index="/^\s*(CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:".$this->sqlite_surroundings_preg("+",false," '\"\[`")."\s*)*ON\s+)(".$this->sqlite_surroundings_preg($table).")(\s*\((?:".$this->sqlite_surroundings_preg("+",false," '\"\[`")."\s*)*\)\s*)\s*$/i";
  4994. foreach($recreateQueries as $recreate_query)
  4995. {
  4996. if($recreate_query['type']=='index')
  4997. {
  4998. // this is an index. We need to make sure the index is not on a column that we drop. If it is, we drop the index as well.
  4999. $indexInfos = $this->selectArray('PRAGMA index_info('.$this->quote_id($recreate_query['name']).')');
  5000. foreach($indexInfos as $indexInfo)
  5001. {
  5002. if(!isset($newcols[$indexInfo['name']]))
  5003. {
  5004. if($debug) $this->debugOutput .= 'Not recreating the following index: <hr /><br />'.htmlencode($recreate_query['sql']).'<hr /><br />';
  5005. // Index on a column that was dropped. Skip recreation.
  5006. continue 2;
  5007. }
  5008. }
  5009. }
  5010. // TODO: In case we renamed a column on which there is an index, we need to recreate the index with the column name adjusted.
  5011. // recreate triggers / indexes
  5012. if($table == $table_new)
  5013. {
  5014. // we had no RENAME TO, so we can recreate indexes/triggers just like the original ones
  5015. $alter_transaction .= $recreate_query['sql'].';';
  5016. } else
  5017. {
  5018. // we had a RENAME TO, so we need to exchange the table-name in the CREATE-SQL of triggers & indexes
  5019. switch ($recreate_query['type'])
  5020. {
  5021. case 'index':
  5022. $recreate_queryIndex = preg_replace($preg_index, '$1'.$this->quote_id(strtr($table_new, array('\\' => '\\\\', '$' => '\$'))).'$3 ', $recreate_query['sql']);
  5023. if($recreate_queryIndex!=$recreate_query['sql'] && $recreate_queryIndex != NULL)
  5024. $alter_transaction .= $recreate_queryIndex.';';
  5025. else
  5026. {
  5027. // the CREATE INDEX regex did not match. this normally should not happen
  5028. if($debug) $this->debugOutput .= 'ERROR: CREATE INDEX regex did not match!?<hr /><br />';
  5029. // just try to recreate the index originally (will fail most likely)
  5030. $alter_transaction .= $recreate_query['sql'].';';
  5031. }
  5032. break;
  5033. case 'trigger':
  5034. // TODO: IMPLEMENT
  5035. $alter_transaction .= $recreate_query['sql'].';';
  5036. break;
  5037. default:
  5038. if($debug) $this->debugOutput .= 'ERROR: Unknown type '.htmlencode($recreate_query['type']).'<hr /><br />';
  5039. $alter_transaction .= $recreate_query['sql'].';';
  5040. }
  5041. }
  5042. }
  5043. $alter_transaction .= 'COMMIT;';
  5044. if($debug) $this->debugOutput .= $alter_transaction;
  5045. return $this->multiQuery($alter_transaction);
  5046. }
  5047. }
  5048. //multiple query execution
  5049. //returns true on success, false otherwise. Use getError() to fetch the error.
  5050. public function multiQuery($query)
  5051. {
  5052. if($this->type=="PDO")
  5053. $success = $this->db->exec($query);
  5054. else if($this->type=="SQLite3")
  5055. $success = $this->db->exec($query);
  5056. else
  5057. $success = $this->db->queryExec($query, $error);
  5058. return $success;
  5059. }
  5060. // checks whether a table has a primary key
  5061. public function hasPrimaryKey($table)
  5062. {
  5063. $table_info = $this->getTableInfo($table);
  5064. foreach($table_info as $row_id => $row_data)
  5065. {
  5066. if($row_data['pk'])
  5067. {
  5068. return true;
  5069. }
  5070. }
  5071. return false;
  5072. }
  5073. // Returns an array of columns by which rows can be uniquely adressed.
  5074. // For tables with a rowid column, this is always array('rowid')
  5075. // for tables without rowid, this is an array of the primary key columns.
  5076. public function getPrimaryKey($table)
  5077. {
  5078. $primary_key = array();
  5079. // check if this table has a rowid
  5080. $getRowID = $this->select('SELECT ROWID FROM '.$this->quote_id($table).' LIMIT 0,1');
  5081. if(isset($getRowID[0]))
  5082. // it has, so we prefer addressing rows by rowid
  5083. return array('rowid');
  5084. else
  5085. {
  5086. // the table is without rowid, so use the primary key
  5087. $table_info = $this->getTableInfo($table);
  5088. if(is_array($table_info))
  5089. {
  5090. foreach($table_info as $row_id => $row_data)
  5091. {
  5092. if($row_data['pk'])
  5093. $primary_key[] = $row_data['name'];
  5094. }
  5095. }
  5096. }
  5097. return $primary_key;
  5098. }
  5099. // selects a row by a given key $pk, which is an array of values
  5100. // for the columns by which a row can be adressed (rowid or primary key)
  5101. public function wherePK($table, $pk)
  5102. {
  5103. $where = "";
  5104. $primary_key = $this->getPrimaryKey($table);
  5105. foreach($primary_key as $pk_index => $column)
  5106. {
  5107. if($where!="")
  5108. $where .= " AND ";
  5109. $where .= $this->quote_id($column) . ' = ';
  5110. if(is_int($pk[$pk_index]) || is_float($pk[$pk_index]))
  5111. $where .= $pk[$pk_index];
  5112. else
  5113. $where .= $this->quote($pk[$pk_index]);
  5114. }
  5115. return $where;
  5116. }
  5117. //get number of rows in table
  5118. public function numRows($table, $dontTakeLong = false)
  5119. {
  5120. // as Count(*) can be slow on huge tables without PK,
  5121. // if $dontTakeLong is set and the size is > 2MB only count() if there is a PK
  5122. if(!$dontTakeLong || $this->getSize() <= 2000 || $this->hasPrimaryKey($table))
  5123. {
  5124. $result = $this->select("SELECT Count(*) FROM ".$this->quote_id($table));
  5125. return $result[0];
  5126. } else
  5127. {
  5128. return '?';
  5129. }
  5130. }
  5131. //correctly escape a string to be injected into an SQL query
  5132. public function quote($value)
  5133. {
  5134. if($this->type=="PDO")
  5135. {
  5136. // PDO quote() escapes and adds quotes
  5137. return $this->db->quote($value);
  5138. }
  5139. else if($this->type=="SQLite3")
  5140. {
  5141. return "'".$this->db->escapeString($value)."'";
  5142. }
  5143. else
  5144. {
  5145. return "'".sqlite_escape_string($value)."'";
  5146. }
  5147. }
  5148. //correctly escape an identifier (column / table / trigger / index name) to be injected into an SQL query
  5149. public function quote_id($value)
  5150. {
  5151. // double-quotes need to be escaped by doubling them
  5152. $value = str_replace('"','""',$value);
  5153. return '"'.$value.'"';
  5154. }
  5155. //import sql
  5156. //returns true on success, error message otherwise
  5157. public function import_sql($query)
  5158. {
  5159. $import = $this->multiQuery($query);
  5160. if(!$import)
  5161. return $this->getError();
  5162. else
  5163. return true;
  5164. }
  5165. public function prepareQuery($query)
  5166. {
  5167. if($this->type=='PDO' || $this->type=='SQLite3')
  5168. return $this->db->prepare($query);
  5169. else
  5170. {
  5171. // here we are in trouble, SQLiteDatabase cannot prepare statements.
  5172. // we need to emulate prepare as best as we can
  5173. # todo: implement this
  5174. return null;
  5175. }
  5176. }
  5177. public function bindValue($handle, $parameter, $value, $type)
  5178. {
  5179. if($this->type=='SQLite3')
  5180. {
  5181. $types = array(
  5182. 'bool'=>SQLITE3_INTEGER,
  5183. 'int'=>SQLITE3_INTEGER,
  5184. 'float'=>SQLITE3_FLOAT,
  5185. 'text'=>SQLITE3_TEXT,
  5186. 'blob'=>SQLITE3_BLOB,
  5187. 'null'=>SQLITE3_NULL);
  5188. if(!isset($types[$type]))
  5189. $type = 'text';
  5190. // there is no SQLITE_BOOL, so check value and make sure it is 0/1
  5191. if($type=='bool')
  5192. {
  5193. if($value===1 || $value===true)
  5194. $value=1;
  5195. elseif($value===0 || $value===false)
  5196. $value=0;
  5197. else
  5198. return false;
  5199. }
  5200. return $handle->bindValue($parameter, $value, $types[$type]);
  5201. }
  5202. if($this->type=='PDO')
  5203. {
  5204. $types = array(
  5205. 'bool'=>PDO::PARAM_BOOL,
  5206. 'int'=>PDO::PARAM_INT,
  5207. 'float'=>PDO::PARAM_STR,
  5208. 'text'=>PDO::PARAM_STR,
  5209. 'blob'=>PDO::PARAM_LOB,
  5210. 'null'=>PDO::PARAM_NULL);
  5211. if(!isset($types[$type]))
  5212. $type = 'text';
  5213. // there is no PDO::PARAM_FLOAT, so we check it ourself
  5214. if($type=='float')
  5215. {
  5216. if(is_numeric($value))
  5217. $value = (float) $value;
  5218. else
  5219. return false;
  5220. }
  5221. return $handle->bindValue($parameter, $value, $types[$type]);
  5222. }
  5223. else
  5224. # todo: workaround
  5225. return false;
  5226. }
  5227. public function executePrepared($handle, $fetchResult=false)
  5228. {
  5229. if($this->type=='PDO')
  5230. {
  5231. $ok=$handle->execute();
  5232. if($fetchResult && $ok)
  5233. {
  5234. $res = $handle->fetchAll();
  5235. $handle->closeCursor();
  5236. return $res;
  5237. }
  5238. else
  5239. {
  5240. if($ok)
  5241. $handle->closeCursor();
  5242. return $ok;
  5243. }
  5244. }
  5245. elseif($this->type=='SQLite3')
  5246. {
  5247. $resultset=$handle->execute();
  5248. if($fetchResult && $resultset!==false)
  5249. {
  5250. $res = $resultset->fetchArray();
  5251. $resultset->finalize();
  5252. return $res;
  5253. }
  5254. else
  5255. {
  5256. if($resultset!==false)
  5257. $resultset->finalize();
  5258. if($resultset===false)
  5259. return false;
  5260. else
  5261. return true;
  5262. }
  5263. }
  5264. else
  5265. {
  5266. #todo.
  5267. return false;
  5268. }
  5269. }
  5270. //import csv
  5271. //returns true on success, error message otherwise
  5272. public function import_csv($filename, $table, $field_terminate, $field_enclosed, $field_escaped, $null, $fields_in_first_row)
  5273. {
  5274. @set_time_limit(-1);
  5275. $csv_handle = fopen($filename,'r');
  5276. $csv_insert = "BEGIN;\n";
  5277. $csv_number_of_rows = 0;
  5278. // PHP requires enclosure defined, but has no problem if it was not used
  5279. if($field_enclosed=="") $field_enclosed='"';
  5280. // PHP requires escaper defined
  5281. if($field_escaped=="") $field_escaped='\\';
  5282. // support tab delimiters
  5283. if($field_terminate=='\t') $field_terminate = "\t";
  5284. while($csv_handle!==false && !feof($csv_handle))
  5285. {
  5286. $csv_data = fgetcsv($csv_handle, 0, $field_terminate, $field_enclosed, $field_escaped);
  5287. if(is_array($csv_data) && ($csv_data[0] != NULL || count($csv_data)>1))
  5288. {
  5289. $csv_number_of_rows++;
  5290. if($csv_number_of_rows==1)
  5291. {
  5292. if($this->getTypeOfTable($table)!="table")
  5293. {
  5294. // First,Create a new table
  5295. $csv_insert .="CREATE TABLE ".$this->quote($table)." (";
  5296. $number_of_cols = count($csv_data);
  5297. foreach($csv_data as $csv_col => $csv_cell)
  5298. {
  5299. if($fields_in_first_row)
  5300. $csv_insert .= $this->quote($csv_cell);
  5301. else
  5302. $csv_insert.= $this->quote("col{$csv_col}");
  5303. if($csv_col < $number_of_cols-1)
  5304. $csv_insert .= ", ";
  5305. }
  5306. $csv_insert .=");";
  5307. } else {
  5308. $number_of_cols = count($this->getTableInfo($table));
  5309. }
  5310. if($fields_in_first_row)
  5311. continue;
  5312. }
  5313. $csv_insert .= "INSERT INTO ".$this->quote_id($table)." VALUES (";
  5314. for($csv_col = 0; $csv_col < $number_of_cols; $csv_col++)
  5315. {
  5316. if(isset($csv_data[$csv_col]))
  5317. $csv_cell = $csv_data[$csv_col];
  5318. else
  5319. $csv_cell = $null;
  5320. if($csv_cell == $null)
  5321. $csv_insert .= "NULL";
  5322. else
  5323. $csv_insert.= $this->quote($csv_cell);
  5324. if($csv_col < $number_of_cols-1)
  5325. $csv_insert .= ",";
  5326. }
  5327. $csv_insert .= ");\n";
  5328. if($csv_number_of_rows % 5000 == 0)
  5329. {
  5330. $csv_insert .= "COMMIT;\nBEGIN;\n";
  5331. }
  5332. }
  5333. }
  5334. if($csv_handle === false)
  5335. return "Error reading CSV file";
  5336. else
  5337. {
  5338. $csv_insert .= "COMMIT;";
  5339. fclose($csv_handle);
  5340. $import = $this->multiQuery($csv_insert);
  5341. if(!$import)
  5342. return $this->getError();
  5343. else
  5344. return true;
  5345. }
  5346. }
  5347. //export csv
  5348. public function export_csv($tables, $field_terminate, $field_enclosed, $field_escaped, $null, $crlf, $fields_in_first_row)
  5349. {
  5350. @set_time_limit(-1);
  5351. // we use \r\n if the _client_ OS is windows (as the exported file is downloaded to the client), \n otherwise
  5352. $crlf = (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Win')!==false ? "\r\n" : "\n");
  5353. $query = "SELECT * FROM sqlite_master WHERE type='table' or type='view' ORDER BY type DESC";
  5354. $result = $this->selectArray($query);
  5355. for($i=0; $i<sizeof($result); $i++)
  5356. {
  5357. $valid = false;
  5358. for($j=0; $j<sizeof($tables); $j++)
  5359. {
  5360. if($result[$i]['tbl_name']==$tables[$j])
  5361. $valid = true;
  5362. }
  5363. if($valid)
  5364. {
  5365. $temp = $this->getTableInfo($result[$i]['tbl_name']);
  5366. $cols = array();
  5367. for($z=0; $z<sizeof($temp); $z++)
  5368. $cols[$z] = $temp[$z][1];
  5369. if($fields_in_first_row)
  5370. {
  5371. for($z=0; $z<sizeof($cols); $z++)
  5372. {
  5373. echo $field_enclosed.$cols[$z].$field_enclosed;
  5374. // do not terminate the last column!
  5375. if($z < sizeof($cols)-1)
  5376. echo $field_terminate;
  5377. }
  5378. echo $crlf;
  5379. }
  5380. $query = "SELECT * FROM ".$this->quote_id($result[$i]['tbl_name']);
  5381. $table_result = $this->query($query);
  5382. $firstRow=true;
  5383. while($row = $this->fetch($table_result, "assoc"))
  5384. {
  5385. if(!$firstRow)
  5386. echo $crlf;
  5387. else
  5388. $firstRow=false;
  5389. for($y=0; $y<sizeof($cols); $y++)
  5390. {
  5391. $cell = $row[$cols[$y]];
  5392. if($crlf)
  5393. {
  5394. $cell = str_replace("\n","", $cell);
  5395. $cell = str_replace("\r","", $cell);
  5396. }
  5397. $cell = str_replace($field_terminate,$field_escaped.$field_terminate,$cell);
  5398. $cell = str_replace($field_enclosed,$field_escaped.$field_enclosed,$cell);
  5399. // do not enclose NULLs
  5400. if($cell == NULL)
  5401. echo $null;
  5402. else
  5403. echo $field_enclosed.$cell.$field_enclosed;
  5404. // do not terminate the last column!
  5405. if($y < sizeof($cols)-1)
  5406. echo $field_terminate;
  5407. }
  5408. }
  5409. if($i<sizeof($result)-1)
  5410. echo $crlf;
  5411. }
  5412. }
  5413. }
  5414. //export sql
  5415. public function export_sql($tables, $drop, $structure, $data, $transaction, $comments)
  5416. {
  5417. global $lang;
  5418. @set_time_limit(-1);
  5419. // we use \r\n if the _client_ OS is windows (as the exported file is downloaded to the client), \n otherwise
  5420. $crlf = (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Win')!==false ? "\r\n" : "\n");
  5421. if($comments)
  5422. {
  5423. echo "----".$crlf;
  5424. echo "-- ".PROJECT." ".$lang['db_dump']." (".PROJECT_URL.")".$crlf;
  5425. echo "-- ".PROJECT." ".$lang['ver'].": ".VERSION.$crlf;
  5426. echo "-- ".$lang['exported'].": ".date($lang['date_format']).$crlf;
  5427. echo "-- ".$lang['db_f'].": ".$this->getPath().$crlf;
  5428. echo "----".$crlf;
  5429. }
  5430. $query = "SELECT * FROM sqlite_master WHERE type='table' OR type='index' OR type='view' OR type='trigger' ORDER BY type='trigger', type='index', type='view', type='table'";
  5431. $result = $this->selectArray($query);
  5432. if($transaction)
  5433. echo "BEGIN TRANSACTION;".$crlf;
  5434. //iterate through each table
  5435. for($i=0; $i<sizeof($result); $i++)
  5436. {
  5437. $valid = false;
  5438. for($j=0; $j<sizeof($tables); $j++)
  5439. {
  5440. if($result[$i]['tbl_name']==$tables[$j])
  5441. $valid = true;
  5442. }
  5443. if($valid)
  5444. {
  5445. if($drop)
  5446. {
  5447. if($comments)
  5448. {
  5449. echo "\r\n----".$crlf;
  5450. echo "-- ".$lang['drop']." ".$result[$i]['type']." ".$lang['for']." ".$result[$i]['name'].$crlf;
  5451. echo "----".$crlf;
  5452. }
  5453. echo "DROP ".strtoupper($result[$i]['type'])." IF EXISTS ".$this->quote_id($result[$i]['name']).";".$crlf;
  5454. }
  5455. if($structure)
  5456. {
  5457. if($comments)
  5458. {
  5459. echo "\r\n----".$crlf;
  5460. if($result[$i]['type']=="table" || $result[$i]['type']=="view")
  5461. echo "-- ".ucfirst($result[$i]['type'])." ".$lang['struct_for']." ".$result[$i]['tbl_name'].$crlf;
  5462. else // index or trigger
  5463. echo "-- ".$lang['struct_for']." ".$result[$i]['type']." ".$result[$i]['name']." ".$lang['on_tbl']." ".$result[$i]['tbl_name'].$crlf;
  5464. echo "----".$crlf;
  5465. }
  5466. echo $result[$i]['sql'].";".$crlf;
  5467. }
  5468. if($data && $result[$i]['type']=="table")
  5469. {
  5470. $query = "SELECT * FROM ".$this->quote_id($result[$i]['tbl_name']);
  5471. $table_result = $this->query($query, "assoc");
  5472. if($comments)
  5473. {
  5474. $numRows = $this->numRows($result[$i]['tbl_name']);
  5475. echo "\r\n----".$crlf;
  5476. echo "-- ".$lang['data_dump']." ".$result[$i]['tbl_name'].", ".sprintf($lang['total_rows'], $numRows).$crlf;
  5477. echo "----".$crlf;
  5478. }
  5479. $temp = $this->getTableInfo($result[$i]['tbl_name']);
  5480. $cols = array();
  5481. $cols_quoted = array();
  5482. for($z=0; $z<sizeof($temp); $z++)
  5483. {
  5484. $cols[$z] = $temp[$z][1];
  5485. $cols_quoted[$z] = $this->quote_id($temp[$z][1]);
  5486. }
  5487. while($row = $this->fetch($table_result))
  5488. {
  5489. $vals = array();
  5490. for($y=0; $y<sizeof($cols); $y++)
  5491. {
  5492. if($row[$cols[$y]] === NULL)
  5493. $vals[$cols[$y]] = 'NULL';
  5494. else
  5495. $vals[$cols[$y]] = $this->quote($row[$cols[$y]]);
  5496. }
  5497. echo "INSERT INTO ".$this->quote_id($result[$i]['tbl_name'])." (".implode(",", $cols_quoted).") VALUES (".implode(",", $vals).");".$crlf;
  5498. }
  5499. }
  5500. }
  5501. }
  5502. if($transaction)
  5503. echo "COMMIT;".$crlf;
  5504. }
  5505. }
  5506. class GetParameters
  5507. {
  5508. private $_fields;
  5509. public function __construct(array $defaults = array())
  5510. {
  5511. $this->_fields = $defaults;
  5512. }
  5513. public function __set($key, $value)
  5514. {
  5515. $this->_fields[$key] = $value;
  5516. }
  5517. public function __isset($key)
  5518. {
  5519. return isset($this->_fields[$key]);
  5520. }
  5521. public function __unset($key)
  5522. {
  5523. unset($this->_fields[$key]);
  5524. }
  5525. public function __get($key)
  5526. {
  5527. return $this->_fields[$key];
  5528. }
  5529. public function getURL(array $assoc = array(), $html = true, $prefix='?')
  5530. {
  5531. $arg_sep = ($html?'&amp;':'&');
  5532. return $prefix . http_build_query(array_merge($this->_fields, $assoc), '', $arg_sep);
  5533. }
  5534. public function getLink(array $assoc = array(), $content = '[ link ]', $class = '', $title = '', $target='')
  5535. {
  5536. return '<a href="' . $this->getURL($assoc) . '"'
  5537. . ($class != '' ? ' class="' . $class . '"' : '')
  5538. . ($title != '' ? ' title="' . $title . '"' : '')
  5539. . ($target != '' ? ' target="' . $target . '"' : '')
  5540. . '>' . $content . '</a>';
  5541. }
  5542. public function getForm(array $assoc = array(), $method = 'post', $upload = false, $name = '', $csrf = true)
  5543. {
  5544. $hidden = '';
  5545. if($method == 'get')
  5546. {
  5547. $url = '';
  5548. foreach(array_merge($this->_fields, $assoc) as $key => $value)
  5549. {
  5550. if(!is_null($value))
  5551. $hidden .= '<input type="hidden" name="'.htmlencode($key).'" value="'.htmlencode($value).'" /> ';
  5552. }
  5553. }
  5554. else
  5555. $url = $this->getURL($assoc);
  5556. if($csrf && $method == 'post')
  5557. $hidden .= '<input type="hidden" name="token" value="'.$_SESSION[COOKIENAME.'token'].'" />';
  5558. return "<form action='". $url ."' method='" . $method . "'" .
  5559. ($name!=''? " name='". $name ."'" : '') .
  5560. ($upload? " enctype='multipart/form-data'" : '') . ">" .
  5561. $hidden;
  5562. }
  5563. public function redirect(array $assoc = array(), $message="")
  5564. {
  5565. if($message!="")
  5566. {
  5567. $_SESSION[COOKIENAME.'messages'][md5($message)] = $message;
  5568. $url = $this->getURL(array_merge($assoc, array('message'=>md5($message))), false);
  5569. }
  5570. else
  5571. $url = $this->getURL($assoc, false);
  5572. $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http');
  5573. header("Location: ".$protocol."://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].$url, true, 302);
  5574. exit;
  5575. }
  5576. }// class MicroTimer (issue #146)
  5577. // wraps calls to microtime(), calculating the elapsed time and rounding output
  5578. //
  5579. class Resources {
  5580. // set this to the file containing getInternalResource;
  5581. // currently unused in split mode; set to __FILE__ for built PLA.
  5582. public static $embedding_file = __FILE__;
  5583. private static $_resources = array(
  5584. 'css' => array(
  5585. 'mime' => 'text/css',
  5586. 'data' => 'resources/phpliteadmin.css',
  5587. ),
  5588. 'javascript' => array(
  5589. 'mime' => 'text/javascript',
  5590. 'data' => 'resources/phpliteadmin.js',
  5591. ),
  5592. 'favicon' => array(
  5593. 'mime' => 'image/x-icon',
  5594. 'data' => 'resources/favicon.ico',
  5595. 'base64' => 'true',
  5596. ),
  5597. );
  5598. // outputs the specified resource, if defined in this class.
  5599. // the main script should do no further output after calling this function.
  5600. public static function output($resource)
  5601. {
  5602. if (isset(self::$_resources[$resource])) {
  5603. $res =& self::$_resources[$resource];
  5604. if (function_exists('getInternalResource') && $data = getInternalResource($res['data'])) {
  5605. $filename = self::$embedding_file;
  5606. } else {
  5607. $filename = $res['data'];
  5608. }
  5609. // use last-modified time as etag; etag must be quoted
  5610. $etag = '"' . filemtime($filename) . '"';
  5611. // check headers for matching etag; if etag hasn't changed, use the cached version
  5612. if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == $etag) {
  5613. header('HTTP/1.0 304 Not Modified');
  5614. return;
  5615. }
  5616. header('Etag: ' . $etag);
  5617. // cache file for at most 30 days
  5618. header('Cache-control: max-age=2592000');
  5619. // output resource
  5620. header('Content-type: ' . $res['mime']);
  5621. if (isset($data)) {
  5622. if (isset($res['base64'])) {
  5623. echo base64_decode($data);
  5624. } else {
  5625. echo $data;
  5626. }
  5627. } else {
  5628. readfile($filename);
  5629. }
  5630. }
  5631. }
  5632. }
  5633. // returns data from internal resources, available in single-file mode
  5634. function getInternalResource($res) {
  5635. $resources = array('resources/phpliteadmin.css'=>array(0=>0,1=>4059,),'resources/phpliteadmin.js'=>array(0=>4059,1=>4542,),'resources/favicon.ico'=>array(0=>8601,1=>1448,),);
  5636. if (isset($resources[$res]) && $f = fopen(__FILE__, 'r')) {
  5637. fseek($f, __COMPILER_HALT_OFFSET__ + $resources[$res][0]);
  5638. $data = fread($f, $resources[$res][1]);
  5639. fclose($f);
  5640. return $data;
  5641. }
  5642. return false;
  5643. }
  5644. // resources embedded below, do not edit!
  5645. __halt_compiler() ?>body{margin:0px;padding:0px;font-family:Arial,Helvetica,sans-serif;font-size:14px;color:#000;background-color:#e0ebf6;overflow:auto}.body_tbl td{padding:9px 2px 9px 9px}.left_td{width:100px}a{color:#03F;text-decoration:none;cursor:pointer}a:hover{color:#06F}hr{height:1px;border:0;color:#bbb;background-color:#bbb;width:100%}h1{margin:0px;padding:5px;font-size:24px;background-color:#f3cece;text-align:center;color:#000;border-top-left-radius:5px;border-top-right-radius:5px;-moz-border-radius-topleft:5px;-moz-border-radius-topright:5px}#headerlinks{text-align:center;margin-bottom:10px;padding:5px 15px;border-color:#03F;border-width:1px;border-style:solid;border-left-style:none;border-right-style:none;font-size:12px;background-color:#e0ebf6;font-weight:bold}h1 #version{color:#000;font-size:16px}h1 #logo{color:#000}h2{margin:0px;padding:0px;font-size:14px;margin-bottom:20px}input,select,textarea,.CodeMirror{font-family:Arial,Helvetica,sans-serif;background-color:#eaeaea;color:#03F;border-color:#03F;border-style:solid;border-width:1px;margin:5px;border-radius:5px;-moz-border-radius:5px;padding:3px}input.btn{cursor:pointer}input.btn:hover{background-color:#ccc}fieldset label{min-width:200px;display:block;float:left}fieldset{padding:15px;border-color:#03F;border-width:1px;border-style:solid;border-radius:5px;-moz-border-radius:5px;background-color:#f9f9f9}#container{padding:10px}#leftNav{min-width:250px;padding:0px;border-color:#03F;border-width:1px;border-style:solid;background-color:#FFF;padding-bottom:15px;border-radius:5px;-moz-border-radius:5px}.databaseList select{max-width:200px}.viewTable tr td{padding:1px}#loginBox{width:500px;margin-left:auto;margin-right:auto;margin-top:50px;border-color:#03F;border-width:1px;border-style:solid;background-color:#FFF;border-radius:5px;-moz-border-radius:5px}#main{border-color:#03F;border-width:1px;border-style:solid;padding:15px;background-color:#FFF;border-bottom-left-radius:5px;border-bottom-right-radius:5px;border-top-right-radius:5px;-moz-border-radius-bottomleft:5px;-moz-border-radius-bottomright:5px;-moz-border-radius-topright:5px}.td1{background-color:#f9e3e3;text-align:right;font-size:12px;padding-left:10px;padding-right:10px}.td2{background-color:#f3cece;text-align:right;font-size:12px;padding-left:10px;padding-right:10px}.tdheader{border-color:#03F;border-width:1px;border-style:solid;font-weight:bold;font-size:12px;padding-left:10px;padding-right:10px;background-color:#e0ebf6;border-radius:5px;-moz-border-radius:5px}.confirm{border-color:#03F;border-width:1px;border-style:dashed;padding:15px;background-color:#e0ebf6}.tab{display:block;padding:5px;padding-right:8px;padding-left:8px;border-color:#03F;border-width:1px;border-style:solid;margin-right:5px;float:left;border-bottom-style:none;position:relative;top:1px;padding-bottom:4px;background-color:#eaeaea;border-top-left-radius:5px;border-top-right-radius:5px;-moz-border-radius-topleft:5px;-moz-border-radius-topright:5px}.tab_pressed{display:block;padding:5px;padding-right:8px;padding-left:8px;border-color:#03F;border-width:1px;border-style:solid;margin-right:5px;float:left;border-bottom-style:none;position:relative;top:1px;background-color:#FFF;cursor:default;border-top-left-radius:5px;border-top-right-radius:5px;-moz-border-radius-topleft:5px;-moz-border-radius-topright:5px}.helpq{font-size:11px;font-weight:normal}#help_container{padding:0px;font-size:12px;margin-left:auto;margin-right:auto;background-color:#fff}.help_outer{background-color:#FFF;padding:0px;height:300px;position:relative}.help_list{padding:10px;height:auto}.headd{font-size:14px;font-weight:bold;display:block;padding:10px;background-color:#e0ebf6;border-color:#03F;border-width:1px;border-style:solid;border-left-style:none;border-right-style:none}.help_inner{padding:10px}.help_top{display:block;position:absolute;right:10px;bottom:10px}.warning,.delete,.empty,.drop,.delete_db{color:red}.sidebar_table{font-size:11px}.active_table,.active_db{text-decoration:underline}.null{color:#888}.found{background:#FF0;text-decoration:none}
  5646. function initAutoincrement()
  5647. {var i=0;while(document.getElementById('i'+i+'_autoincrement')!=undefined)
  5648. {document.getElementById('i'+i+'_autoincrement').disabled=true;i++;}}
  5649. function toggleAutoincrement(i)
  5650. {var type=document.getElementById('i'+i+'_type');var primarykey=document.getElementById('i'+i+'_primarykey');var autoincrement=document.getElementById('i'+i+'_autoincrement');if(!autoincrement)return false;if(type.value=='INTEGER'&&primarykey.checked)
  5651. autoincrement.disabled=false;else
  5652. {autoincrement.disabled=true;autoincrement.checked=false;}}
  5653. function toggleNull(i)
  5654. {var pk=document.getElementById('i'+i+'_primarykey');var notnull=document.getElementById('i'+i+'_notnull');if(pk.checked)
  5655. {notnull.disabled=true;notnull.checked=true;}
  5656. else
  5657. {notnull.disabled=false;}}
  5658. function checkAll(field)
  5659. {var i=0;while(document.getElementById('check_'+i)!=undefined)
  5660. {document.getElementById('check_'+i).checked=true;i++;}}
  5661. function uncheckAll(field)
  5662. {var i=0;while(document.getElementById('check_'+i)!=undefined)
  5663. {document.getElementById('check_'+i).checked=false;i++;}}
  5664. function changeIgnore(area,e,u)
  5665. {if(area.value!="")
  5666. {if(document.getElementById(e)!=undefined)
  5667. document.getElementById(e).checked=false;if(document.getElementById(u)!=undefined)
  5668. document.getElementById(u).checked=false;}}
  5669. function moveFields()
  5670. {var fields=document.getElementById("fieldcontainer");var selected=[];for(var i=0;i<fields.options.length;i++)
  5671. if(fields.options[i].selected)
  5672. selected.push(fields.options[i].value);for(var i=0;i<selected.length;i++)
  5673. {var val='"'+selected[i].replace(/"/g,'""')+'"';if(i<selected.length-1)
  5674. val+=', ';sqleditorInsertValue(val);}}
  5675. function notNull(checker)
  5676. {document.getElementById(checker).checked=false;}
  5677. function disableText(checker,textie)
  5678. {if(checker.checked)
  5679. {document.getElementById(textie).value="";document.getElementById(textie).disabled=true;}
  5680. else
  5681. {document.getElementById(textie).disabled=false;}}
  5682. function toggleExports(val)
  5683. {document.getElementById("exportoptions_sql").style.display="none";document.getElementById("exportoptions_csv").style.display="none";document.getElementById("exportoptions_"+val).style.display="block";}
  5684. function toggleImports(val)
  5685. {document.getElementById("importoptions_sql").style.display="none";document.getElementById("importoptions_csv").style.display="none";document.getElementById("importoptions_"+val).style.display="block";}
  5686. function openHelp(section)
  5687. {PopupCenter('?help=1#'+section,"Help Section");}
  5688. var helpsec=false;function PopupCenter(pageURL,title)
  5689. {helpsec=window.open(pageURL,title,"toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=300");}
  5690. function checkLike(srchField,selOpt)
  5691. {if(selOpt=="LIKE%"){var textArea=document.getElementById(srchField);textArea.value="%"+textArea.value+"%";}}
  5692. function createCORSRequest(method,url)
  5693. {var xhr=new XMLHttpRequest();if("withCredentials"in xhr)
  5694. {xhr.open(method,url,true);}
  5695. else if(typeof XDomainRequest!="undefined")
  5696. {xhr=new XDomainRequest();xhr.open(method,url);}
  5697. else
  5698. {xhr=null;}
  5699. return xhr;}
  5700. function checkVersion(installed,url)
  5701. {var xhr=createCORSRequest('GET',url);if(!xhr)
  5702. return false;xhr.onload=function()
  5703. {if(xhr.responseText.split("\n").indexOf(installed)==-1)
  5704. {document.getElementById('oldVersion').style.display='inline';}};xhr.send();}
  5705. var codeEditor;function sqleditor(textarea,tableDefinitions,tableDefault)
  5706. {codeEditor=CodeMirror.fromTextArea(textarea,{lineNumbers:true,matchBrackets:true,indentUnit:4,lineWrapping:true,mode:"text/x-sqlite",extraKeys:{"Ctrl-Space":"autocomplete"},hint:CodeMirror.hint.sql,hintOptions:{completeSingle:false,completeOnSingleClick:true,defaultTable:tableDefault,tables:tableDefinitions}});codeEditor.on("inputRead",codemirrorAutocompleteOnInputRead);}
  5707. function sqleditorSetValue(text)
  5708. {codeEditor.doc.setValue(text);}
  5709. function sqleditorInsertValue(text)
  5710. {codeEditor.doc.replaceRange(text,codeEditor.doc.getCursor("from"),codeEditor.doc.getCursor("to"));}
  5711. function codemirrorAutocompleteOnInputRead(instance){if(instance.state.completionActive){return;}
  5712. var cur=instance.getCursor();var token=instance.getTokenAt(cur);var string='';if(token.string.match(/^[.`"\w@]\w*$/))
  5713. {string=token.string;}
  5714. if(string.length>0){CodeMirror.commands.autocomplete(instance);}}
  5715. function checkFileSize(input)
  5716. {if(input.files&&input.files.length==1)
  5717. {if(input.files[0].size>fileUploadMaxSize)
  5718. {alert(fileUploadMaxSizeErrorMsg+": "+(fileUploadMaxSize/1024/1024)+" MiB");return false;}}
  5719. return true;}AAABAAEAEBAAAAEAIAAoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwoKZQAAABMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABEMDJMAAAAdAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASDg7BAAAASAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAETDw9CCQkJ1QUFBb4AAABjAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgsLVgAAAO8YExP/AAAA7QAAALEAAAARAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQNDUsAAADJGBMT/xgTE/8AAAD/AAAAuAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZERE8DQoKwhgTE/8QDQ2sGBMT/xgTE/8AAAA/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwICHkAAAD/EQwMzQAAAMIAAAD/AAAA7gAAAGEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOCwtWAAAA8RgTE/8IBQW1AAAA/wAAAP8AAADlAAAAHQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0KCsEAAAD/EQ8PzAAAAMkAAAD/AAAA/wAAAHoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABDAAAA/xgTE/8TDw/FAAAA8gAAAP8AAADqAAAAJgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAALUAAAD/GBMT/wAAALkAAAD/AAAA/wAAAIkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfAAAA4wAAAP8GBgbFAAAA2QAAAP8AAADGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF4AAAD5AAAA/RgTE/8AAAD/AAAA0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQQAAAOIAAAD/AAAA/wAAAHYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAjAAAArgAAAG4AAAAAAAAAAAAAAAAAAAAA