phpliteadmin.php 228 KB

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