pla.php 228 KB

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