phpliteadmin.php 290 KB

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