functions.js 170 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118
  1. /* vim: set expandtab sw=4 ts=4 sts=4: */
  2. /**
  3. * general function, usually for data manipulation pages
  4. *
  5. */
  6. /**
  7. * @var sql_box_locked lock for the sqlbox textarea in the querybox
  8. */
  9. var sql_box_locked = false;
  10. /**
  11. * @var array holds elements which content should only selected once
  12. */
  13. var only_once_elements = [];
  14. /**
  15. * @var int ajax_message_count Number of AJAX messages shown since page load
  16. */
  17. var ajax_message_count = 0;
  18. /**
  19. * @var codemirror_editor object containing CodeMirror editor of the query editor in SQL tab
  20. */
  21. var codemirror_editor = false;
  22. /**
  23. * @var codemirror_editor object containing CodeMirror editor of the inline query editor
  24. */
  25. var codemirror_inline_editor = false;
  26. /**
  27. * @var sql_autocomplete_in_progress bool shows if Table/Column name autocomplete AJAX is in progress
  28. */
  29. var sql_autocomplete_in_progress = false;
  30. /**
  31. * @var sql_autocomplete object containing list of columns in each table
  32. */
  33. var sql_autocomplete = false;
  34. /**
  35. * @var sql_autocomplete_default_table string containing default table to autocomplete columns
  36. */
  37. var sql_autocomplete_default_table = '';
  38. /**
  39. * @var central_column_list array to hold the columns in central list per db.
  40. */
  41. var central_column_list = [];
  42. /**
  43. * @var primary_indexes array to hold 'Primary' index columns.
  44. */
  45. var primary_indexes = [];
  46. /**
  47. * @var unique_indexes array to hold 'Unique' index columns.
  48. */
  49. var unique_indexes = [];
  50. /**
  51. * @var indexes array to hold 'Index' columns.
  52. */
  53. var indexes = [];
  54. /**
  55. * @var fulltext_indexes array to hold 'Fulltext' columns.
  56. */
  57. var fulltext_indexes = [];
  58. /**
  59. * @var spatial_indexes array to hold 'Spatial' columns.
  60. */
  61. var spatial_indexes = [];
  62. /**
  63. * Make sure that ajax requests will not be cached
  64. * by appending a random variable to their parameters
  65. */
  66. $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
  67. var nocache = new Date().getTime() + '' + Math.floor(Math.random() * 1000000);
  68. if (typeof options.data === 'string') {
  69. options.data += '&_nocache=' + nocache + '&token=' + encodeURIComponent(PMA_commonParams.get('token'));
  70. } else if (typeof options.data === 'object') {
  71. options.data = $.extend(originalOptions.data, { '_nocache' : nocache, 'token': PMA_commonParams.get('token') });
  72. }
  73. });
  74. /*
  75. * Adds a date/time picker to an element
  76. *
  77. * @param object $this_element a jQuery object pointing to the element
  78. */
  79. function PMA_addDatepicker ($this_element, type, options) {
  80. var showTimepicker = true;
  81. if (type === 'date') {
  82. showTimepicker = false;
  83. }
  84. var defaultOptions = {
  85. showOn: 'button',
  86. buttonImage: themeCalendarImage, // defined in js/messages.php
  87. buttonImageOnly: true,
  88. stepMinutes: 1,
  89. stepHours: 1,
  90. showSecond: true,
  91. showMillisec: true,
  92. showMicrosec: true,
  93. showTimepicker: showTimepicker,
  94. showButtonPanel: false,
  95. dateFormat: 'yy-mm-dd', // yy means year with four digits
  96. timeFormat: 'HH:mm:ss.lc',
  97. constrainInput: false,
  98. altFieldTimeOnly: false,
  99. showAnim: '',
  100. beforeShow: function (input, inst) {
  101. // Remember that we came from the datepicker; this is used
  102. // in tbl_change.js by verificationsAfterFieldChange()
  103. $this_element.data('comes_from', 'datepicker');
  104. if ($(input).closest('.cEdit').length > 0) {
  105. setTimeout(function () {
  106. inst.dpDiv.css({
  107. top: 0,
  108. left: 0,
  109. position: 'relative'
  110. });
  111. }, 0);
  112. }
  113. setTimeout(function () {
  114. // Fix wrong timepicker z-index, doesn't work without timeout
  115. $('#ui-timepicker-div').css('z-index', $('#ui-datepicker-div').css('z-index'));
  116. // Integrate tooltip text into dialog
  117. var tooltip = $this_element.tooltip('instance');
  118. if (typeof tooltip !== 'undefined') {
  119. tooltip.disable();
  120. var $note = $('<p class="note"></div>');
  121. $note.text(tooltip.option('content'));
  122. $('div.ui-datepicker').append($note);
  123. }
  124. }, 0);
  125. },
  126. onSelect: function () {
  127. $this_element.data('datepicker').inline = true;
  128. },
  129. onClose: function (dateText, dp_inst) {
  130. // The value is no more from the date picker
  131. $this_element.data('comes_from', '');
  132. if (typeof $this_element.data('datepicker') !== 'undefined') {
  133. $this_element.data('datepicker').inline = false;
  134. }
  135. var tooltip = $this_element.tooltip('instance');
  136. if (typeof tooltip !== 'undefined') {
  137. tooltip.enable();
  138. }
  139. }
  140. };
  141. if (type == 'time') {
  142. $this_element.timepicker($.extend(defaultOptions, options));
  143. // Add a tip regarding entering MySQL allowed-values for TIME data-type
  144. PMA_tooltip($this_element, 'input', PMA_messages.strMysqlAllowedValuesTipTime);
  145. } else {
  146. $this_element.datetimepicker($.extend(defaultOptions, options));
  147. }
  148. }
  149. /**
  150. * Add a date/time picker to each element that needs it
  151. * (only when jquery-ui-timepicker-addon.js is loaded)
  152. */
  153. function addDateTimePicker () {
  154. if ($.timepicker !== undefined) {
  155. $('input.timefield, input.datefield, input.datetimefield').each(function () {
  156. var decimals = $(this).parent().attr('data-decimals');
  157. var type = $(this).parent().attr('data-type');
  158. var showMillisec = false;
  159. var showMicrosec = false;
  160. var timeFormat = 'HH:mm:ss';
  161. var hourMax = 23;
  162. // check for decimal places of seconds
  163. if (decimals > 0 && type.indexOf('time') !== -1) {
  164. if (decimals > 3) {
  165. showMillisec = true;
  166. showMicrosec = true;
  167. timeFormat = 'HH:mm:ss.lc';
  168. } else {
  169. showMillisec = true;
  170. timeFormat = 'HH:mm:ss.l';
  171. }
  172. }
  173. if (type === 'time') {
  174. hourMax = 99;
  175. }
  176. PMA_addDatepicker($(this), type, {
  177. showMillisec: showMillisec,
  178. showMicrosec: showMicrosec,
  179. timeFormat: timeFormat,
  180. hourMax: hourMax
  181. });
  182. // Add a tip regarding entering MySQL allowed-values
  183. // for TIME and DATE data-type
  184. if ($(this).hasClass('timefield')) {
  185. PMA_tooltip($(this), 'input', PMA_messages.strMysqlAllowedValuesTipTime);
  186. } else if ($(this).hasClass('datefield')) {
  187. PMA_tooltip($(this), 'input', PMA_messages.strMysqlAllowedValuesTipDate);
  188. }
  189. });
  190. }
  191. }
  192. /**
  193. * Handle redirect and reload flags sent as part of AJAX requests
  194. *
  195. * @param data ajax response data
  196. */
  197. function PMA_handleRedirectAndReload (data) {
  198. if (parseInt(data.redirect_flag) === 1) {
  199. // add one more GET param to display session expiry msg
  200. if (window.location.href.indexOf('?') === -1) {
  201. window.location.href += '?session_expired=1';
  202. } else {
  203. window.location.href += PMA_commonParams.get('arg_separator') + 'session_expired=1';
  204. }
  205. window.location.reload();
  206. } else if (parseInt(data.reload_flag) === 1) {
  207. window.location.reload();
  208. }
  209. }
  210. /**
  211. * Creates an SQL editor which supports auto completing etc.
  212. *
  213. * @param $textarea jQuery object wrapping the textarea to be made the editor
  214. * @param options optional options for CodeMirror
  215. * @param resize optional resizing ('vertical', 'horizontal', 'both')
  216. * @param lintOptions additional options for lint
  217. */
  218. function PMA_getSQLEditor ($textarea, options, resize, lintOptions) {
  219. if ($textarea.length > 0 && typeof CodeMirror !== 'undefined') {
  220. // merge options for CodeMirror
  221. var defaults = {
  222. lineNumbers: true,
  223. matchBrackets: true,
  224. extraKeys: { 'Ctrl-Space': 'autocomplete' },
  225. hintOptions: { 'completeSingle': false, 'completeOnSingleClick': true },
  226. indentUnit: 4,
  227. mode: 'text/x-mysql',
  228. lineWrapping: true
  229. };
  230. if (CodeMirror.sqlLint) {
  231. $.extend(defaults, {
  232. gutters: ['CodeMirror-lint-markers'],
  233. lint: {
  234. 'getAnnotations': CodeMirror.sqlLint,
  235. 'async': true,
  236. 'lintOptions': lintOptions
  237. }
  238. });
  239. }
  240. $.extend(true, defaults, options);
  241. // create CodeMirror editor
  242. var codemirrorEditor = CodeMirror.fromTextArea($textarea[0], defaults);
  243. // allow resizing
  244. if (! resize) {
  245. resize = 'vertical';
  246. }
  247. var handles = '';
  248. if (resize === 'vertical') {
  249. handles = 's';
  250. }
  251. if (resize === 'both') {
  252. handles = 'all';
  253. }
  254. if (resize === 'horizontal') {
  255. handles = 'e, w';
  256. }
  257. $(codemirrorEditor.getWrapperElement())
  258. .css('resize', resize)
  259. .resizable({
  260. handles: handles,
  261. resize: function () {
  262. codemirrorEditor.setSize($(this).width(), $(this).height());
  263. }
  264. });
  265. // enable autocomplete
  266. codemirrorEditor.on('inputRead', codemirrorAutocompleteOnInputRead);
  267. // page locking
  268. codemirrorEditor.on('change', function (e) {
  269. e.data = {
  270. value: 3,
  271. content: codemirrorEditor.isClean(),
  272. };
  273. AJAX.lockPageHandler(e);
  274. });
  275. return codemirrorEditor;
  276. }
  277. return null;
  278. }
  279. /**
  280. * Clear text selection
  281. */
  282. function PMA_clearSelection () {
  283. if (document.selection && document.selection.empty) {
  284. document.selection.empty();
  285. } else if (window.getSelection) {
  286. var sel = window.getSelection();
  287. if (sel.empty) {
  288. sel.empty();
  289. }
  290. if (sel.removeAllRanges) {
  291. sel.removeAllRanges();
  292. }
  293. }
  294. }
  295. /**
  296. * Create a jQuery UI tooltip
  297. *
  298. * @param $elements jQuery object representing the elements
  299. * @param item the item
  300. * (see https://api.jqueryui.com/tooltip/#option-items)
  301. * @param myContent content of the tooltip
  302. * @param additionalOptions to override the default options
  303. *
  304. */
  305. function PMA_tooltip ($elements, item, myContent, additionalOptions) {
  306. if ($('#no_hint').length > 0) {
  307. return;
  308. }
  309. var defaultOptions = {
  310. content: myContent,
  311. items: item,
  312. tooltipClass: 'tooltip',
  313. track: true,
  314. show: false,
  315. hide: false
  316. };
  317. $elements.tooltip($.extend(true, defaultOptions, additionalOptions));
  318. }
  319. /**
  320. * HTML escaping
  321. */
  322. function escapeHtml (unsafe) {
  323. if (typeof(unsafe) !== 'undefined') {
  324. return unsafe
  325. .toString()
  326. .replace(/&/g, '&amp;')
  327. .replace(/</g, '&lt;')
  328. .replace(/>/g, '&gt;')
  329. .replace(/"/g, '&quot;')
  330. .replace(/'/g, '&#039;');
  331. } else {
  332. return false;
  333. }
  334. }
  335. function escapeJsString (unsafe) {
  336. if (typeof(unsafe) !== 'undefined') {
  337. return unsafe
  338. .toString()
  339. .replace('\x00', '')
  340. .replace('\\', '\\\\')
  341. .replace('\'', '\\\'')
  342. .replace('&#039;', '\\\&#039;')
  343. .replace('"', '\"')
  344. .replace('&quot;', '\&quot;')
  345. .replace('\n', '\n')
  346. .replace('\r', '\r')
  347. .replace(/<\/script/gi, '</\' + \'script');
  348. } else {
  349. return false;
  350. }
  351. }
  352. function escapeBacktick (s) {
  353. return s.replace('`', '``');
  354. }
  355. function escapeSingleQuote (s) {
  356. return s.replace('\\', '\\\\').replace('\'', '\\\'');
  357. }
  358. function PMA_sprintf () {
  359. return sprintf.apply(this, arguments);
  360. }
  361. /**
  362. * Hides/shows the default value input field, depending on the default type
  363. * Ticks the NULL checkbox if NULL is chosen as default value.
  364. */
  365. function PMA_hideShowDefaultValue ($default_type) {
  366. if ($default_type.val() === 'USER_DEFINED') {
  367. $default_type.siblings('.default_value').show().focus();
  368. } else {
  369. $default_type.siblings('.default_value').hide();
  370. if ($default_type.val() === 'NULL') {
  371. var $null_checkbox = $default_type.closest('tr').find('.allow_null');
  372. $null_checkbox.prop('checked', true);
  373. }
  374. }
  375. }
  376. /**
  377. * Hides/shows the input field for column expression based on whether
  378. * VIRTUAL/PERSISTENT is selected
  379. *
  380. * @param $virtuality virtuality dropdown
  381. */
  382. function PMA_hideShowExpression ($virtuality) {
  383. if ($virtuality.val() === '') {
  384. $virtuality.siblings('.expression').hide();
  385. } else {
  386. $virtuality.siblings('.expression').show();
  387. }
  388. }
  389. /**
  390. * Show notices for ENUM columns; add/hide the default value
  391. *
  392. */
  393. function PMA_verifyColumnsProperties () {
  394. $('select.column_type').each(function () {
  395. PMA_showNoticeForEnum($(this));
  396. });
  397. $('select.default_type').each(function () {
  398. PMA_hideShowDefaultValue($(this));
  399. });
  400. $('select.virtuality').each(function () {
  401. PMA_hideShowExpression($(this));
  402. });
  403. }
  404. /**
  405. * Add a hidden field to the form to indicate that this will be an
  406. * Ajax request (only if this hidden field does not exist)
  407. *
  408. * @param $form object the form
  409. */
  410. function PMA_prepareForAjaxRequest ($form) {
  411. if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
  412. $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
  413. }
  414. }
  415. /**
  416. * Generate a new password and copy it to the password input areas
  417. *
  418. * @param passwd_form object the form that holds the password fields
  419. *
  420. * @return boolean always true
  421. */
  422. function suggestPassword (passwd_form) {
  423. // restrict the password to just letters and numbers to avoid problems:
  424. // "editors and viewers regard the password as multiple words and
  425. // things like double click no longer work"
  426. var pwchars = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWYXZ';
  427. var passwordlength = 16; // do we want that to be dynamic? no, keep it simple :)
  428. var passwd = passwd_form.generated_pw;
  429. var randomWords = new Int32Array(passwordlength);
  430. passwd.value = '';
  431. // First we're going to try to use a built-in CSPRNG
  432. if (window.crypto && window.crypto.getRandomValues) {
  433. window.crypto.getRandomValues(randomWords);
  434. } else if (window.msCrypto && window.msCrypto.getRandomValues) {
  435. // Because of course IE calls it msCrypto instead of being standard
  436. window.msCrypto.getRandomValues(randomWords);
  437. } else {
  438. // Fallback to Math.random
  439. for (var i = 0; i < passwordlength; i++) {
  440. randomWords[i] = Math.floor(Math.random() * pwchars.length);
  441. }
  442. }
  443. for (var i = 0; i < passwordlength; i++) {
  444. passwd.value += pwchars.charAt(Math.abs(randomWords[i]) % pwchars.length);
  445. }
  446. $jquery_passwd_form = $(passwd_form);
  447. passwd_form.elements.pma_pw.value = passwd.value;
  448. passwd_form.elements.pma_pw2.value = passwd.value;
  449. meter_obj = $jquery_passwd_form.find('meter[name="pw_meter"]').first();
  450. meter_obj_label = $jquery_passwd_form.find('span[name="pw_strength"]').first();
  451. checkPasswordStrength(passwd.value, meter_obj, meter_obj_label);
  452. return true;
  453. }
  454. /**
  455. * Version string to integer conversion.
  456. */
  457. function parseVersionString (str) {
  458. if (typeof(str) !== 'string') {
  459. return false;
  460. }
  461. var add = 0;
  462. // Parse possible alpha/beta/rc/
  463. var state = str.split('-');
  464. if (state.length >= 2) {
  465. if (state[1].substr(0, 2) === 'rc') {
  466. add = - 20 - parseInt(state[1].substr(2), 10);
  467. } else if (state[1].substr(0, 4) === 'beta') {
  468. add = - 40 - parseInt(state[1].substr(4), 10);
  469. } else if (state[1].substr(0, 5) === 'alpha') {
  470. add = - 60 - parseInt(state[1].substr(5), 10);
  471. } else if (state[1].substr(0, 3) === 'dev') {
  472. /* We don't handle dev, it's git snapshot */
  473. add = 0;
  474. }
  475. }
  476. // Parse version
  477. var x = str.split('.');
  478. // Use 0 for non existing parts
  479. var maj = parseInt(x[0], 10) || 0;
  480. var min = parseInt(x[1], 10) || 0;
  481. var pat = parseInt(x[2], 10) || 0;
  482. var hotfix = parseInt(x[3], 10) || 0;
  483. return maj * 100000000 + min * 1000000 + pat * 10000 + hotfix * 100 + add;
  484. }
  485. /**
  486. * Indicates current available version on main page.
  487. */
  488. function PMA_current_version (data) {
  489. if (data && data.version && data.date) {
  490. var current = parseVersionString($('span.version').text());
  491. var latest = parseVersionString(data.version);
  492. var url = 'https://www.phpmyadmin.net/files/' + escapeHtml(encodeURIComponent(data.version)) + '/';
  493. var version_information_message = document.createElement('span');
  494. version_information_message.className = 'latest';
  495. var version_information_message_link = document.createElement('a');
  496. version_information_message_link.href = url;
  497. version_information_message_link.className = 'disableAjax';
  498. version_information_message_link_text = document.createTextNode(data.version);
  499. version_information_message_link.appendChild(version_information_message_link_text);
  500. var prefix_message = document.createTextNode(PMA_messages.strLatestAvailable + ' ');
  501. version_information_message.appendChild(prefix_message);
  502. version_information_message.appendChild(version_information_message_link);
  503. if (latest > current) {
  504. var message = PMA_sprintf(
  505. PMA_messages.strNewerVersion,
  506. escapeHtml(data.version),
  507. escapeHtml(data.date)
  508. );
  509. var htmlClass = 'notice';
  510. if (Math.floor(latest / 10000) === Math.floor(current / 10000)) {
  511. /* Security update */
  512. htmlClass = 'error';
  513. }
  514. $('#newer_version_notice').remove();
  515. var maincontainer_div = document.createElement('div');
  516. maincontainer_div.id = 'newer_version_notice';
  517. maincontainer_div.className = htmlClass;
  518. var maincontainer_div_link = document.createElement('a');
  519. maincontainer_div_link.href = url;
  520. maincontainer_div_link.className = 'disableAjax';
  521. maincontainer_div_link_text = document.createTextNode(message);
  522. maincontainer_div_link.appendChild(maincontainer_div_link_text);
  523. maincontainer_div.appendChild(maincontainer_div_link);
  524. $('#maincontainer').append($(maincontainer_div));
  525. }
  526. if (latest === current) {
  527. version_information_message = document.createTextNode(' (' + PMA_messages.strUpToDate + ')');
  528. }
  529. /* Remove extra whitespace */
  530. var version_info = $('#li_pma_version').contents().get(2);
  531. version_info.textContent = $.trim(version_info.textContent);
  532. var $liPmaVersion = $('#li_pma_version');
  533. $liPmaVersion.find('span.latest').remove();
  534. $liPmaVersion.append($(version_information_message));
  535. }
  536. }
  537. /**
  538. * Loads Git revision data from ajax for index.php
  539. */
  540. function PMA_display_git_revision () {
  541. $('#is_git_revision').remove();
  542. $('#li_pma_version_git').remove();
  543. $.get(
  544. 'index.php',
  545. {
  546. 'server': PMA_commonParams.get('server'),
  547. 'git_revision': true,
  548. 'ajax_request': true,
  549. 'no_debug': true
  550. },
  551. function (data) {
  552. if (typeof data !== 'undefined' && data.success === true) {
  553. $(data.message).insertAfter('#li_pma_version');
  554. }
  555. }
  556. );
  557. }
  558. /**
  559. * for PhpMyAdmin\Display\ChangePassword
  560. * libraries/user_password.php
  561. *
  562. */
  563. function displayPasswordGenerateButton () {
  564. var generatePwdRow = $('<tr />').addClass('vmiddle');
  565. var titleCell = $('<td />').html(PMA_messages.strGeneratePassword).appendTo(generatePwdRow);
  566. var pwdCell = $('<td />').appendTo(generatePwdRow);
  567. var pwdButton = $('<input />')
  568. .attr({ type: 'button', id: 'button_generate_password', value: PMA_messages.strGenerate })
  569. .addClass('button')
  570. .on('click', function () {
  571. suggestPassword(this.form);
  572. });
  573. var pwdTextbox = $('<input />')
  574. .attr({ type: 'text', name: 'generated_pw', id: 'generated_pw' });
  575. pwdCell.append(pwdButton).append(pwdTextbox);
  576. $('#tr_element_before_generate_password').parent().append(generatePwdRow);
  577. var generatePwdDiv = $('<div />').addClass('item');
  578. var titleLabel = $('<label />').attr({ for: 'button_generate_password' })
  579. .html(PMA_messages.strGeneratePassword + ':')
  580. .appendTo(generatePwdDiv);
  581. var optionsSpan = $('<span/>').addClass('options')
  582. .appendTo(generatePwdDiv);
  583. pwdButton.clone(true).appendTo(optionsSpan);
  584. pwdTextbox.clone(true).appendTo(generatePwdDiv);
  585. $('#div_element_before_generate_password').parent().append(generatePwdDiv);
  586. }
  587. /**
  588. * selects the content of a given object, f.e. a textarea
  589. *
  590. * @param element object element of which the content will be selected
  591. * @param lock var variable which holds the lock for this element
  592. * or true, if no lock exists
  593. * @param only_once boolean if true this is only done once
  594. * f.e. only on first focus
  595. */
  596. function selectContent (element, lock, only_once) {
  597. if (only_once && only_once_elements[element.name]) {
  598. return;
  599. }
  600. only_once_elements[element.name] = true;
  601. if (lock) {
  602. return;
  603. }
  604. element.select();
  605. }
  606. /**
  607. * Displays a confirmation box before submitting a "DROP/DELETE/ALTER" query.
  608. * This function is called while clicking links
  609. *
  610. * @param theLink object the link
  611. * @param theSqlQuery object the sql query to submit
  612. *
  613. * @return boolean whether to run the query or not
  614. */
  615. function confirmLink (theLink, theSqlQuery) {
  616. // Confirmation is not required in the configuration file
  617. // or browser is Opera (crappy js implementation)
  618. if (PMA_messages.strDoYouReally === '' || typeof(window.opera) !== 'undefined') {
  619. return true;
  620. }
  621. var is_confirmed = confirm(PMA_sprintf(PMA_messages.strDoYouReally, theSqlQuery));
  622. if (is_confirmed) {
  623. if (typeof(theLink.href) !== 'undefined') {
  624. theLink.href += PMA_commonParams.get('arg_separator') + 'is_js_confirmed=1';
  625. } else if (typeof(theLink.form) !== 'undefined') {
  626. theLink.form.action += '?is_js_confirmed=1';
  627. }
  628. }
  629. return is_confirmed;
  630. } // end of the 'confirmLink()' function
  631. /**
  632. * Confirms a "DROP/DELETE/ALTER" query before
  633. * submitting it if required.
  634. * This function is called by the 'checkSqlQuery()' js function.
  635. *
  636. * @param theForm1 object the form
  637. * @param sqlQuery1 string the sql query string
  638. *
  639. * @return boolean whether to run the query or not
  640. *
  641. * @see checkSqlQuery()
  642. */
  643. function confirmQuery (theForm1, sqlQuery1) {
  644. // Confirmation is not required in the configuration file
  645. if (PMA_messages.strDoYouReally === '') {
  646. return true;
  647. }
  648. // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement
  649. //
  650. // TODO: find a way (if possible) to use the parser-analyser
  651. // for this kind of verification
  652. // For now, I just added a ^ to check for the statement at
  653. // beginning of expression
  654. var do_confirm_re_0 = new RegExp('^\\s*DROP\\s+(IF EXISTS\\s+)?(TABLE|PROCEDURE)\\s', 'i');
  655. var do_confirm_re_1 = new RegExp('^\\s*ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i');
  656. var do_confirm_re_2 = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
  657. var do_confirm_re_3 = new RegExp('^\\s*TRUNCATE\\s', 'i');
  658. if (do_confirm_re_0.test(sqlQuery1) ||
  659. do_confirm_re_1.test(sqlQuery1) ||
  660. do_confirm_re_2.test(sqlQuery1) ||
  661. do_confirm_re_3.test(sqlQuery1)) {
  662. var message;
  663. if (sqlQuery1.length > 100) {
  664. message = sqlQuery1.substr(0, 100) + '\n ...';
  665. } else {
  666. message = sqlQuery1;
  667. }
  668. var is_confirmed = confirm(PMA_sprintf(PMA_messages.strDoYouReally, message));
  669. // statement is confirmed -> update the
  670. // "is_js_confirmed" form field so the confirm test won't be
  671. // run on the server side and allows to submit the form
  672. if (is_confirmed) {
  673. theForm1.elements.is_js_confirmed.value = 1;
  674. return true;
  675. } else {
  676. // statement is rejected -> do not submit the form
  677. window.focus();
  678. return false;
  679. } // end if (handle confirm box result)
  680. } // end if (display confirm box)
  681. return true;
  682. } // end of the 'confirmQuery()' function
  683. /**
  684. * Displays an error message if the user submitted the sql query form with no
  685. * sql query, else checks for "DROP/DELETE/ALTER" statements
  686. *
  687. * @param theForm object the form
  688. *
  689. * @return boolean always false
  690. *
  691. * @see confirmQuery()
  692. */
  693. function checkSqlQuery (theForm) {
  694. // get the textarea element containing the query
  695. var sqlQuery;
  696. if (codemirror_editor) {
  697. codemirror_editor.save();
  698. sqlQuery = codemirror_editor.getValue();
  699. } else {
  700. sqlQuery = theForm.elements.sql_query.value;
  701. }
  702. var space_re = new RegExp('\\s+');
  703. if (typeof(theForm.elements.sql_file) !== 'undefined' &&
  704. theForm.elements.sql_file.value.replace(space_re, '') !== '') {
  705. return true;
  706. }
  707. if (typeof(theForm.elements.id_bookmark) !== 'undefined' &&
  708. (theForm.elements.id_bookmark.value !== null || theForm.elements.id_bookmark.value !== '') &&
  709. theForm.elements.id_bookmark.selectedIndex !== 0) {
  710. return true;
  711. }
  712. var result = false;
  713. // Checks for "DROP/DELETE/ALTER" statements
  714. if (sqlQuery.replace(space_re, '') !== '') {
  715. result = confirmQuery(theForm, sqlQuery);
  716. } else {
  717. alert(PMA_messages.strFormEmpty);
  718. }
  719. if (codemirror_editor) {
  720. codemirror_editor.focus();
  721. } else if (codemirror_inline_editor) {
  722. codemirror_inline_editor.focus();
  723. }
  724. return result;
  725. } // end of the 'checkSqlQuery()' function
  726. /**
  727. * Check if a form's element is empty.
  728. * An element containing only spaces is also considered empty
  729. *
  730. * @param object the form
  731. * @param string the name of the form field to put the focus on
  732. *
  733. * @return boolean whether the form field is empty or not
  734. */
  735. function emptyCheckTheField (theForm, theFieldName) {
  736. var theField = theForm.elements[theFieldName];
  737. var space_re = new RegExp('\\s+');
  738. return theField.value.replace(space_re, '') === '';
  739. } // end of the 'emptyCheckTheField()' function
  740. /**
  741. * Ensures a value submitted in a form is numeric and is in a range
  742. *
  743. * @param object the form
  744. * @param string the name of the form field to check
  745. * @param integer the minimum authorized value
  746. * @param integer the maximum authorized value
  747. *
  748. * @return boolean whether a valid number has been submitted or not
  749. */
  750. function checkFormElementInRange (theForm, theFieldName, message, min, max) {
  751. var theField = theForm.elements[theFieldName];
  752. var val = parseInt(theField.value, 10);
  753. if (typeof(min) === 'undefined') {
  754. min = 0;
  755. }
  756. if (typeof(max) === 'undefined') {
  757. max = Number.MAX_VALUE;
  758. }
  759. if (isNaN(val)) {
  760. theField.select();
  761. alert(PMA_messages.strEnterValidNumber);
  762. theField.focus();
  763. return false;
  764. } else if (val < min || val > max) {
  765. theField.select();
  766. alert(PMA_sprintf(message, val));
  767. theField.focus();
  768. return false;
  769. } else {
  770. theField.value = val;
  771. }
  772. return true;
  773. } // end of the 'checkFormElementInRange()' function
  774. function checkTableEditForm (theForm, fieldsCnt) {
  775. // TODO: avoid sending a message if user just wants to add a line
  776. // on the form but has not completed at least one field name
  777. var atLeastOneField = 0;
  778. var i;
  779. var elm;
  780. var elm2;
  781. var elm3;
  782. var val;
  783. var id;
  784. for (i = 0; i < fieldsCnt; i++) {
  785. id = '#field_' + i + '_2';
  786. elm = $(id);
  787. val = elm.val();
  788. if (val === 'VARCHAR' || val === 'CHAR' || val === 'BIT' || val === 'VARBINARY' || val === 'BINARY') {
  789. elm2 = $('#field_' + i + '_3');
  790. val = parseInt(elm2.val(), 10);
  791. elm3 = $('#field_' + i + '_1');
  792. if (isNaN(val) && elm3.val() !== '') {
  793. elm2.select();
  794. alert(PMA_messages.strEnterValidLength);
  795. elm2.focus();
  796. return false;
  797. }
  798. }
  799. if (atLeastOneField === 0) {
  800. id = 'field_' + i + '_1';
  801. if (!emptyCheckTheField(theForm, id)) {
  802. atLeastOneField = 1;
  803. }
  804. }
  805. }
  806. if (atLeastOneField === 0) {
  807. var theField = theForm.elements.field_0_1;
  808. alert(PMA_messages.strFormEmpty);
  809. theField.focus();
  810. return false;
  811. }
  812. // at least this section is under jQuery
  813. var $input = $('input.textfield[name=\'table\']');
  814. if ($input.val() === '') {
  815. alert(PMA_messages.strFormEmpty);
  816. $input.focus();
  817. return false;
  818. }
  819. return true;
  820. } // enf of the 'checkTableEditForm()' function
  821. /**
  822. * True if last click is to check a row.
  823. */
  824. var last_click_checked = false;
  825. /**
  826. * Zero-based index of last clicked row.
  827. * Used to handle the shift + click event in the code above.
  828. */
  829. var last_clicked_row = -1;
  830. /**
  831. * Zero-based index of last shift clicked row.
  832. */
  833. var last_shift_clicked_row = -1;
  834. var _idleSecondsCounter = 0;
  835. var IncInterval;
  836. var updateTimeout;
  837. AJAX.registerTeardown('functions.js', function () {
  838. clearTimeout(updateTimeout);
  839. clearInterval(IncInterval);
  840. $(document).off('mousemove');
  841. });
  842. AJAX.registerOnload('functions.js', function () {
  843. document.onclick = function () {
  844. _idleSecondsCounter = 0;
  845. };
  846. $(document).on('mousemove',function () {
  847. _idleSecondsCounter = 0;
  848. });
  849. document.onkeypress = function () {
  850. _idleSecondsCounter = 0;
  851. };
  852. function guid () {
  853. function s4 () {
  854. return Math.floor((1 + Math.random()) * 0x10000)
  855. .toString(16)
  856. .substring(1);
  857. }
  858. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  859. s4() + '-' + s4() + s4() + s4();
  860. }
  861. function SetIdleTime () {
  862. _idleSecondsCounter++;
  863. }
  864. function UpdateIdleTime () {
  865. var href = 'index.php';
  866. var guid = 'default';
  867. if (isStorageSupported('sessionStorage')) {
  868. guid = window.sessionStorage.guid;
  869. }
  870. var params = {
  871. 'ajax_request' : true,
  872. 'server' : PMA_commonParams.get('server'),
  873. 'db' : PMA_commonParams.get('db'),
  874. 'guid': guid,
  875. 'access_time':_idleSecondsCounter
  876. };
  877. $.ajax({
  878. type: 'POST',
  879. url: href,
  880. data: params,
  881. success: function (data) {
  882. if (data.success) {
  883. if (PMA_commonParams.get('LoginCookieValidity') - _idleSecondsCounter < 0) {
  884. /* There is other active window, let's reset counter */
  885. _idleSecondsCounter = 0;
  886. }
  887. var remaining = Math.min(
  888. /* Remaining login validity */
  889. PMA_commonParams.get('LoginCookieValidity') - _idleSecondsCounter,
  890. /* Remaining time till session GC */
  891. PMA_commonParams.get('session_gc_maxlifetime')
  892. );
  893. var interval = 1000;
  894. if (remaining > 5) {
  895. // max value for setInterval() function
  896. interval = Math.min((remaining - 1) * 1000, Math.pow(2, 31) - 1);
  897. }
  898. updateTimeout = window.setTimeout(UpdateIdleTime, interval);
  899. } else { // timeout occurred
  900. clearInterval(IncInterval);
  901. if (isStorageSupported('sessionStorage')) {
  902. window.sessionStorage.clear();
  903. }
  904. window.location.reload(true);
  905. }
  906. }
  907. });
  908. }
  909. if (PMA_commonParams.get('logged_in')) {
  910. IncInterval = window.setInterval(SetIdleTime, 1000);
  911. var session_timeout = Math.min(
  912. PMA_commonParams.get('LoginCookieValidity'),
  913. PMA_commonParams.get('session_gc_maxlifetime')
  914. );
  915. if (isStorageSupported('sessionStorage')) {
  916. window.sessionStorage.setItem('guid', guid());
  917. }
  918. var interval = (session_timeout - 5) * 1000;
  919. if (interval > Math.pow(2, 31) - 1) { // max value for setInterval() function
  920. interval = Math.pow(2, 31) - 1;
  921. }
  922. updateTimeout = window.setTimeout(UpdateIdleTime, interval);
  923. }
  924. });
  925. /**
  926. * Unbind all event handlers before tearing down a page
  927. */
  928. AJAX.registerTeardown('functions.js', function () {
  929. $(document).off('click', 'input:checkbox.checkall');
  930. });
  931. AJAX.registerOnload('functions.js', function () {
  932. /**
  933. * Row marking in horizontal mode (use "on" so that it works also for
  934. * next pages reached via AJAX); a tr may have the class noclick to remove
  935. * this behavior.
  936. */
  937. $(document).on('click', 'input:checkbox.checkall', function (e) {
  938. $this = $(this);
  939. var $tr = $this.closest('tr');
  940. var $table = $this.closest('table');
  941. if (!e.shiftKey || last_clicked_row === -1) {
  942. // usual click
  943. var $checkbox = $tr.find(':checkbox.checkall');
  944. var checked = $this.prop('checked');
  945. $checkbox.prop('checked', checked).trigger('change');
  946. if (checked) {
  947. $tr.addClass('marked');
  948. } else {
  949. $tr.removeClass('marked');
  950. }
  951. last_click_checked = checked;
  952. // remember the last clicked row
  953. last_clicked_row = last_click_checked ? $table.find('tr:not(.noclick)').index($tr) : -1;
  954. last_shift_clicked_row = -1;
  955. } else {
  956. // handle the shift click
  957. PMA_clearSelection();
  958. var start;
  959. var end;
  960. // clear last shift click result
  961. if (last_shift_clicked_row >= 0) {
  962. if (last_shift_clicked_row >= last_clicked_row) {
  963. start = last_clicked_row;
  964. end = last_shift_clicked_row;
  965. } else {
  966. start = last_shift_clicked_row;
  967. end = last_clicked_row;
  968. }
  969. $tr.parent().find('tr:not(.noclick)')
  970. .slice(start, end + 1)
  971. .removeClass('marked')
  972. .find(':checkbox')
  973. .prop('checked', false)
  974. .trigger('change');
  975. }
  976. // handle new shift click
  977. var curr_row = $table.find('tr:not(.noclick)').index($tr);
  978. if (curr_row >= last_clicked_row) {
  979. start = last_clicked_row;
  980. end = curr_row;
  981. } else {
  982. start = curr_row;
  983. end = last_clicked_row;
  984. }
  985. $tr.parent().find('tr:not(.noclick)')
  986. .slice(start, end)
  987. .addClass('marked')
  988. .find(':checkbox')
  989. .prop('checked', true)
  990. .trigger('change');
  991. // remember the last shift clicked row
  992. last_shift_clicked_row = curr_row;
  993. }
  994. });
  995. addDateTimePicker();
  996. /**
  997. * Add attribute to text boxes for iOS devices (based on bugID: 3508912)
  998. */
  999. if (navigator.userAgent.match(/(iphone|ipod|ipad)/i)) {
  1000. $('input[type=text]').attr('autocapitalize', 'off').attr('autocorrect', 'off');
  1001. }
  1002. });
  1003. /**
  1004. * Checks/unchecks all options of a <select> element
  1005. *
  1006. * @param string the form name
  1007. * @param string the element name
  1008. * @param boolean whether to check or to uncheck options
  1009. *
  1010. * @return boolean always true
  1011. */
  1012. function setSelectOptions (the_form, the_select, do_check) {
  1013. $('form[name=\'' + the_form + '\'] select[name=\'' + the_select + '\']').find('option').prop('selected', do_check);
  1014. return true;
  1015. } // end of the 'setSelectOptions()' function
  1016. /**
  1017. * Sets current value for query box.
  1018. */
  1019. function setQuery (query) {
  1020. if (codemirror_editor) {
  1021. codemirror_editor.setValue(query);
  1022. codemirror_editor.focus();
  1023. } else {
  1024. document.sqlform.sql_query.value = query;
  1025. document.sqlform.sql_query.focus();
  1026. }
  1027. }
  1028. /**
  1029. * Handles 'Simulate query' button on SQL query box.
  1030. *
  1031. * @return void
  1032. */
  1033. function PMA_handleSimulateQueryButton () {
  1034. var update_re = new RegExp('^\\s*UPDATE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+SET\\s', 'i');
  1035. var delete_re = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
  1036. var query = '';
  1037. if (codemirror_editor) {
  1038. query = codemirror_editor.getValue();
  1039. } else {
  1040. query = $('#sqlquery').val();
  1041. }
  1042. var $simulateDml = $('#simulate_dml');
  1043. if (update_re.test(query) || delete_re.test(query)) {
  1044. if (! $simulateDml.length) {
  1045. $('#button_submit_query')
  1046. .before('<input type="button" id="simulate_dml"' +
  1047. 'tabindex="199" value="' +
  1048. PMA_messages.strSimulateDML +
  1049. '" />');
  1050. }
  1051. } else {
  1052. if ($simulateDml.length) {
  1053. $simulateDml.remove();
  1054. }
  1055. }
  1056. }
  1057. /**
  1058. * Create quick sql statements.
  1059. *
  1060. */
  1061. function insertQuery (queryType) {
  1062. if (queryType === 'clear') {
  1063. setQuery('');
  1064. return;
  1065. } else if (queryType === 'format') {
  1066. if (codemirror_editor) {
  1067. $('#querymessage').html(PMA_messages.strFormatting +
  1068. '&nbsp;<img class="ajaxIcon" src="' +
  1069. pmaThemeImage + 'ajax_clock_small.gif" alt="">');
  1070. var href = 'db_sql_format.php';
  1071. var params = {
  1072. 'ajax_request': true,
  1073. 'sql': codemirror_editor.getValue()
  1074. };
  1075. $.ajax({
  1076. type: 'POST',
  1077. url: href,
  1078. data: params,
  1079. success: function (data) {
  1080. if (data.success) {
  1081. codemirror_editor.setValue(data.sql);
  1082. }
  1083. $('#querymessage').html('');
  1084. }
  1085. });
  1086. }
  1087. return;
  1088. } else if (queryType === 'saved') {
  1089. if (isStorageSupported('localStorage') && typeof window.localStorage.auto_saved_sql !== 'undefined') {
  1090. setQuery(window.localStorage.auto_saved_sql);
  1091. } else if (Cookies.get('auto_saved_sql')) {
  1092. setQuery(Cookies.get('auto_saved_sql'));
  1093. } else {
  1094. PMA_ajaxShowMessage(PMA_messages.strNoAutoSavedQuery);
  1095. }
  1096. return;
  1097. }
  1098. var query = '';
  1099. var myListBox = document.sqlform.dummy;
  1100. var table = document.sqlform.table.value;
  1101. if (myListBox.options.length > 0) {
  1102. sql_box_locked = true;
  1103. var columnsList = '';
  1104. var valDis = '';
  1105. var editDis = '';
  1106. var NbSelect = 0;
  1107. for (var i = 0; i < myListBox.options.length; i++) {
  1108. NbSelect++;
  1109. if (NbSelect > 1) {
  1110. columnsList += ', ';
  1111. valDis += ',';
  1112. editDis += ',';
  1113. }
  1114. columnsList += myListBox.options[i].value;
  1115. valDis += '[value-' + NbSelect + ']';
  1116. editDis += myListBox.options[i].value + '=[value-' + NbSelect + ']';
  1117. }
  1118. if (queryType === 'selectall') {
  1119. query = 'SELECT * FROM `' + table + '` WHERE 1';
  1120. } else if (queryType === 'select') {
  1121. query = 'SELECT ' + columnsList + ' FROM `' + table + '` WHERE 1';
  1122. } else if (queryType === 'insert') {
  1123. query = 'INSERT INTO `' + table + '`(' + columnsList + ') VALUES (' + valDis + ')';
  1124. } else if (queryType === 'update') {
  1125. query = 'UPDATE `' + table + '` SET ' + editDis + ' WHERE 1';
  1126. } else if (queryType === 'delete') {
  1127. query = 'DELETE FROM `' + table + '` WHERE 0';
  1128. }
  1129. setQuery(query);
  1130. sql_box_locked = false;
  1131. }
  1132. }
  1133. /**
  1134. * Inserts multiple fields.
  1135. *
  1136. */
  1137. function insertValueQuery () {
  1138. var myQuery = document.sqlform.sql_query;
  1139. var myListBox = document.sqlform.dummy;
  1140. if (myListBox.options.length > 0) {
  1141. sql_box_locked = true;
  1142. var columnsList = '';
  1143. var NbSelect = 0;
  1144. for (var i = 0; i < myListBox.options.length; i++) {
  1145. if (myListBox.options[i].selected) {
  1146. NbSelect++;
  1147. if (NbSelect > 1) {
  1148. columnsList += ', ';
  1149. }
  1150. columnsList += myListBox.options[i].value;
  1151. }
  1152. }
  1153. /* CodeMirror support */
  1154. if (codemirror_editor) {
  1155. codemirror_editor.replaceSelection(columnsList);
  1156. codemirror_editor.focus();
  1157. // IE support
  1158. } else if (document.selection) {
  1159. myQuery.focus();
  1160. var sel = document.selection.createRange();
  1161. sel.text = columnsList;
  1162. // MOZILLA/NETSCAPE support
  1163. } else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart === '0') {
  1164. var startPos = document.sqlform.sql_query.selectionStart;
  1165. var endPos = document.sqlform.sql_query.selectionEnd;
  1166. var SqlString = document.sqlform.sql_query.value;
  1167. myQuery.value = SqlString.substring(0, startPos) + columnsList + SqlString.substring(endPos, SqlString.length);
  1168. myQuery.focus();
  1169. } else {
  1170. myQuery.value += columnsList;
  1171. }
  1172. sql_box_locked = false;
  1173. }
  1174. }
  1175. /**
  1176. * Updates the input fields for the parameters based on the query
  1177. */
  1178. function updateQueryParameters () {
  1179. if ($('#parameterized').is(':checked')) {
  1180. var query = codemirror_editor ? codemirror_editor.getValue() : $('#sqlquery').val();
  1181. var allParameters = query.match(/:[a-zA-Z0-9_]+/g);
  1182. var parameters = [];
  1183. // get unique parameters
  1184. if (allParameters) {
  1185. $.each(allParameters, function (i, parameter) {
  1186. if ($.inArray(parameter, parameters) === -1) {
  1187. parameters.push(parameter);
  1188. }
  1189. });
  1190. } else {
  1191. $('#parametersDiv').text(PMA_messages.strNoParam);
  1192. return;
  1193. }
  1194. var $temp = $('<div />');
  1195. $temp.append($('#parametersDiv').children());
  1196. $('#parametersDiv').empty();
  1197. $.each(parameters, function (i, parameter) {
  1198. var paramName = parameter.substring(1);
  1199. var $param = $temp.find('#paramSpan_' + paramName);
  1200. if (! $param.length) {
  1201. $param = $('<span class="parameter" id="paramSpan_' + paramName + '" />');
  1202. $('<label for="param_' + paramName + '" />').text(parameter).appendTo($param);
  1203. $('<input type="text" name="parameters[' + parameter + ']" id="param_' + paramName + '" />').appendTo($param);
  1204. }
  1205. $('#parametersDiv').append($param);
  1206. });
  1207. } else {
  1208. $('#parametersDiv').empty();
  1209. }
  1210. }
  1211. /**
  1212. * Refresh/resize the WYSIWYG scratchboard
  1213. */
  1214. function refreshLayout () {
  1215. var $elm = $('#pdflayout');
  1216. var orientation = $('#orientation_opt').val();
  1217. var paper = 'A4';
  1218. var $paperOpt = $('#paper_opt');
  1219. if ($paperOpt.length === 1) {
  1220. paper = $paperOpt.val();
  1221. }
  1222. var posa = 'y';
  1223. var posb = 'x';
  1224. if (orientation === 'P') {
  1225. posa = 'x';
  1226. posb = 'y';
  1227. }
  1228. $elm.css('width', pdfPaperSize(paper, posa) + 'px');
  1229. $elm.css('height', pdfPaperSize(paper, posb) + 'px');
  1230. }
  1231. /**
  1232. * Initializes positions of elements.
  1233. */
  1234. function TableDragInit () {
  1235. $('.pdflayout_table').each(function () {
  1236. var $this = $(this);
  1237. var number = $this.data('number');
  1238. var x = $('#c_table_' + number + '_x').val();
  1239. var y = $('#c_table_' + number + '_y').val();
  1240. $this.css('left', x + 'px');
  1241. $this.css('top', y + 'px');
  1242. /* Make elements draggable */
  1243. $this.draggable({
  1244. containment: 'parent',
  1245. drag: function (evt, ui) {
  1246. var number = $this.data('number');
  1247. $('#c_table_' + number + '_x').val(parseInt(ui.position.left, 10));
  1248. $('#c_table_' + number + '_y').val(parseInt(ui.position.top, 10));
  1249. }
  1250. });
  1251. });
  1252. }
  1253. /**
  1254. * Resets drag and drop positions.
  1255. */
  1256. function resetDrag () {
  1257. $('.pdflayout_table').each(function () {
  1258. var $this = $(this);
  1259. var x = $this.data('x');
  1260. var y = $this.data('y');
  1261. $this.css('left', x + 'px');
  1262. $this.css('top', y + 'px');
  1263. });
  1264. }
  1265. /**
  1266. * User schema handlers.
  1267. */
  1268. $(function () {
  1269. /* Move in scratchboard on manual change */
  1270. $(document).on('change', '.position-change', function () {
  1271. var $this = $(this);
  1272. var $elm = $('#table_' + $this.data('number'));
  1273. $elm.css($this.data('axis'), $this.val() + 'px');
  1274. });
  1275. /* Refresh on paper size/orientation change */
  1276. $(document).on('change', '.paper-change', function () {
  1277. var $elm = $('#pdflayout');
  1278. if ($elm.css('visibility') === 'visible') {
  1279. refreshLayout();
  1280. TableDragInit();
  1281. }
  1282. });
  1283. /* Show/hide the WYSIWYG scratchboard */
  1284. $(document).on('click', '#toggle-dragdrop', function () {
  1285. var $elm = $('#pdflayout');
  1286. if ($elm.css('visibility') === 'hidden') {
  1287. refreshLayout();
  1288. TableDragInit();
  1289. $elm.css('visibility', 'visible');
  1290. $elm.css('display', 'block');
  1291. $('#showwysiwyg').val('1');
  1292. } else {
  1293. $elm.css('visibility', 'hidden');
  1294. $elm.css('display', 'none');
  1295. $('#showwysiwyg').val('0');
  1296. }
  1297. });
  1298. /* Reset scratchboard */
  1299. $(document).on('click', '#reset-dragdrop', function () {
  1300. resetDrag();
  1301. });
  1302. });
  1303. /**
  1304. * Returns paper sizes for a given format
  1305. */
  1306. function pdfPaperSize (format, axis) {
  1307. switch (format.toUpperCase()) {
  1308. case '4A0':
  1309. if (axis === 'x') {
  1310. return 4767.87;
  1311. } else {
  1312. return 6740.79;
  1313. }
  1314. break;
  1315. case '2A0':
  1316. if (axis === 'x') {
  1317. return 3370.39;
  1318. } else {
  1319. return 4767.87;
  1320. }
  1321. break;
  1322. case 'A0':
  1323. if (axis === 'x') {
  1324. return 2383.94;
  1325. } else {
  1326. return 3370.39;
  1327. }
  1328. break;
  1329. case 'A1':
  1330. if (axis === 'x') {
  1331. return 1683.78;
  1332. } else {
  1333. return 2383.94;
  1334. }
  1335. break;
  1336. case 'A2':
  1337. if (axis === 'x') {
  1338. return 1190.55;
  1339. } else {
  1340. return 1683.78;
  1341. }
  1342. break;
  1343. case 'A3':
  1344. if (axis === 'x') {
  1345. return 841.89;
  1346. } else {
  1347. return 1190.55;
  1348. }
  1349. break;
  1350. case 'A4':
  1351. if (axis === 'x') {
  1352. return 595.28;
  1353. } else {
  1354. return 841.89;
  1355. }
  1356. break;
  1357. case 'A5':
  1358. if (axis === 'x') {
  1359. return 419.53;
  1360. } else {
  1361. return 595.28;
  1362. }
  1363. break;
  1364. case 'A6':
  1365. if (axis === 'x') {
  1366. return 297.64;
  1367. } else {
  1368. return 419.53;
  1369. }
  1370. break;
  1371. case 'A7':
  1372. if (axis === 'x') {
  1373. return 209.76;
  1374. } else {
  1375. return 297.64;
  1376. }
  1377. break;
  1378. case 'A8':
  1379. if (axis === 'x') {
  1380. return 147.40;
  1381. } else {
  1382. return 209.76;
  1383. }
  1384. break;
  1385. case 'A9':
  1386. if (axis === 'x') {
  1387. return 104.88;
  1388. } else {
  1389. return 147.40;
  1390. }
  1391. break;
  1392. case 'A10':
  1393. if (axis === 'x') {
  1394. return 73.70;
  1395. } else {
  1396. return 104.88;
  1397. }
  1398. break;
  1399. case 'B0':
  1400. if (axis === 'x') {
  1401. return 2834.65;
  1402. } else {
  1403. return 4008.19;
  1404. }
  1405. break;
  1406. case 'B1':
  1407. if (axis === 'x') {
  1408. return 2004.09;
  1409. } else {
  1410. return 2834.65;
  1411. }
  1412. break;
  1413. case 'B2':
  1414. if (axis === 'x') {
  1415. return 1417.32;
  1416. } else {
  1417. return 2004.09;
  1418. }
  1419. break;
  1420. case 'B3':
  1421. if (axis === 'x') {
  1422. return 1000.63;
  1423. } else {
  1424. return 1417.32;
  1425. }
  1426. break;
  1427. case 'B4':
  1428. if (axis === 'x') {
  1429. return 708.66;
  1430. } else {
  1431. return 1000.63;
  1432. }
  1433. break;
  1434. case 'B5':
  1435. if (axis === 'x') {
  1436. return 498.90;
  1437. } else {
  1438. return 708.66;
  1439. }
  1440. break;
  1441. case 'B6':
  1442. if (axis === 'x') {
  1443. return 354.33;
  1444. } else {
  1445. return 498.90;
  1446. }
  1447. break;
  1448. case 'B7':
  1449. if (axis === 'x') {
  1450. return 249.45;
  1451. } else {
  1452. return 354.33;
  1453. }
  1454. break;
  1455. case 'B8':
  1456. if (axis === 'x') {
  1457. return 175.75;
  1458. } else {
  1459. return 249.45;
  1460. }
  1461. break;
  1462. case 'B9':
  1463. if (axis === 'x') {
  1464. return 124.72;
  1465. } else {
  1466. return 175.75;
  1467. }
  1468. break;
  1469. case 'B10':
  1470. if (axis === 'x') {
  1471. return 87.87;
  1472. } else {
  1473. return 124.72;
  1474. }
  1475. break;
  1476. case 'C0':
  1477. if (axis === 'x') {
  1478. return 2599.37;
  1479. } else {
  1480. return 3676.54;
  1481. }
  1482. break;
  1483. case 'C1':
  1484. if (axis === 'x') {
  1485. return 1836.85;
  1486. } else {
  1487. return 2599.37;
  1488. }
  1489. break;
  1490. case 'C2':
  1491. if (axis === 'x') {
  1492. return 1298.27;
  1493. } else {
  1494. return 1836.85;
  1495. }
  1496. break;
  1497. case 'C3':
  1498. if (axis === 'x') {
  1499. return 918.43;
  1500. } else {
  1501. return 1298.27;
  1502. }
  1503. break;
  1504. case 'C4':
  1505. if (axis === 'x') {
  1506. return 649.13;
  1507. } else {
  1508. return 918.43;
  1509. }
  1510. break;
  1511. case 'C5':
  1512. if (axis === 'x') {
  1513. return 459.21;
  1514. } else {
  1515. return 649.13;
  1516. }
  1517. break;
  1518. case 'C6':
  1519. if (axis === 'x') {
  1520. return 323.15;
  1521. } else {
  1522. return 459.21;
  1523. }
  1524. break;
  1525. case 'C7':
  1526. if (axis === 'x') {
  1527. return 229.61;
  1528. } else {
  1529. return 323.15;
  1530. }
  1531. break;
  1532. case 'C8':
  1533. if (axis === 'x') {
  1534. return 161.57;
  1535. } else {
  1536. return 229.61;
  1537. }
  1538. break;
  1539. case 'C9':
  1540. if (axis === 'x') {
  1541. return 113.39;
  1542. } else {
  1543. return 161.57;
  1544. }
  1545. break;
  1546. case 'C10':
  1547. if (axis === 'x') {
  1548. return 79.37;
  1549. } else {
  1550. return 113.39;
  1551. }
  1552. break;
  1553. case 'RA0':
  1554. if (axis === 'x') {
  1555. return 2437.80;
  1556. } else {
  1557. return 3458.27;
  1558. }
  1559. break;
  1560. case 'RA1':
  1561. if (axis === 'x') {
  1562. return 1729.13;
  1563. } else {
  1564. return 2437.80;
  1565. }
  1566. break;
  1567. case 'RA2':
  1568. if (axis === 'x') {
  1569. return 1218.90;
  1570. } else {
  1571. return 1729.13;
  1572. }
  1573. break;
  1574. case 'RA3':
  1575. if (axis === 'x') {
  1576. return 864.57;
  1577. } else {
  1578. return 1218.90;
  1579. }
  1580. break;
  1581. case 'RA4':
  1582. if (axis === 'x') {
  1583. return 609.45;
  1584. } else {
  1585. return 864.57;
  1586. }
  1587. break;
  1588. case 'SRA0':
  1589. if (axis === 'x') {
  1590. return 2551.18;
  1591. } else {
  1592. return 3628.35;
  1593. }
  1594. break;
  1595. case 'SRA1':
  1596. if (axis === 'x') {
  1597. return 1814.17;
  1598. } else {
  1599. return 2551.18;
  1600. }
  1601. break;
  1602. case 'SRA2':
  1603. if (axis === 'x') {
  1604. return 1275.59;
  1605. } else {
  1606. return 1814.17;
  1607. }
  1608. break;
  1609. case 'SRA3':
  1610. if (axis === 'x') {
  1611. return 907.09;
  1612. } else {
  1613. return 1275.59;
  1614. }
  1615. break;
  1616. case 'SRA4':
  1617. if (axis === 'x') {
  1618. return 637.80;
  1619. } else {
  1620. return 907.09;
  1621. }
  1622. break;
  1623. case 'LETTER':
  1624. if (axis === 'x') {
  1625. return 612.00;
  1626. } else {
  1627. return 792.00;
  1628. }
  1629. break;
  1630. case 'LEGAL':
  1631. if (axis === 'x') {
  1632. return 612.00;
  1633. } else {
  1634. return 1008.00;
  1635. }
  1636. break;
  1637. case 'EXECUTIVE':
  1638. if (axis === 'x') {
  1639. return 521.86;
  1640. } else {
  1641. return 756.00;
  1642. }
  1643. break;
  1644. case 'FOLIO':
  1645. if (axis === 'x') {
  1646. return 612.00;
  1647. } else {
  1648. return 936.00;
  1649. }
  1650. break;
  1651. } // end switch
  1652. return 0;
  1653. }
  1654. /**
  1655. * Get checkbox for foreign key checks
  1656. *
  1657. * @return string
  1658. */
  1659. function getForeignKeyCheckboxLoader () {
  1660. var html = '';
  1661. html += '<div>';
  1662. html += '<div class="load-default-fk-check-value">';
  1663. html += PMA_getImage('ajax_clock_small');
  1664. html += '</div>';
  1665. html += '</div>';
  1666. return html;
  1667. }
  1668. function loadForeignKeyCheckbox () {
  1669. // Load default foreign key check value
  1670. var params = {
  1671. 'ajax_request': true,
  1672. 'server': PMA_commonParams.get('server'),
  1673. 'get_default_fk_check_value': true
  1674. };
  1675. $.get('sql.php', params, function (data) {
  1676. var html = '<input type="hidden" name="fk_checks" value="0" />' +
  1677. '<input type="checkbox" name="fk_checks" id="fk_checks"' +
  1678. (data.default_fk_check_value ? ' checked="checked"' : '') + ' />' +
  1679. '<label for="fk_checks">' + PMA_messages.strForeignKeyCheck + '</label>';
  1680. $('.load-default-fk-check-value').replaceWith(html);
  1681. });
  1682. }
  1683. function getJSConfirmCommonParam (elem, params) {
  1684. var $elem = $(elem);
  1685. var sep = PMA_commonParams.get('arg_separator');
  1686. if (params) {
  1687. // Strip possible leading ?
  1688. if (params.substring(0,1) == '?') {
  1689. params = params.substr(1);
  1690. }
  1691. params += sep;
  1692. } else {
  1693. params = '';
  1694. }
  1695. params += 'is_js_confirmed=1' + sep + 'ajax_request=true' + sep + 'fk_checks=' + ($elem.find('#fk_checks').is(':checked') ? 1 : 0);
  1696. return params;
  1697. }
  1698. /**
  1699. * Unbind all event handlers before tearing down a page
  1700. */
  1701. AJAX.registerTeardown('functions.js', function () {
  1702. $(document).off('click', 'a.inline_edit_sql');
  1703. $(document).off('click', 'input#sql_query_edit_save');
  1704. $(document).off('click', 'input#sql_query_edit_discard');
  1705. $('input.sqlbutton').off('click');
  1706. if (codemirror_editor) {
  1707. codemirror_editor.off('blur');
  1708. } else {
  1709. $(document).off('blur', '#sqlquery');
  1710. }
  1711. $(document).off('change', '#parameterized');
  1712. $(document).off('click', 'input.sqlbutton');
  1713. $('#sqlquery').off('keydown');
  1714. $('#sql_query_edit').off('keydown');
  1715. if (codemirror_inline_editor) {
  1716. // Copy the sql query to the text area to preserve it.
  1717. $('#sql_query_edit').text(codemirror_inline_editor.getValue());
  1718. $(codemirror_inline_editor.getWrapperElement()).off('keydown');
  1719. codemirror_inline_editor.toTextArea();
  1720. codemirror_inline_editor = false;
  1721. }
  1722. if (codemirror_editor) {
  1723. $(codemirror_editor.getWrapperElement()).off('keydown');
  1724. }
  1725. });
  1726. /**
  1727. * Jquery Coding for inline editing SQL_QUERY
  1728. */
  1729. AJAX.registerOnload('functions.js', function () {
  1730. // If we are coming back to the page by clicking forward button
  1731. // of the browser, bind the code mirror to inline query editor.
  1732. bindCodeMirrorToInlineEditor();
  1733. $(document).on('click', 'a.inline_edit_sql', function () {
  1734. if ($('#sql_query_edit').length) {
  1735. // An inline query editor is already open,
  1736. // we don't want another copy of it
  1737. return false;
  1738. }
  1739. var $form = $(this).prev('form');
  1740. var sql_query = $form.find('input[name=\'sql_query\']').val().trim();
  1741. var $inner_sql = $(this).parent().prev().find('code.sql');
  1742. var old_text = $inner_sql.html();
  1743. var new_content = '<textarea name="sql_query_edit" id="sql_query_edit">' + escapeHtml(sql_query) + '</textarea>\n';
  1744. new_content += getForeignKeyCheckboxLoader();
  1745. new_content += '<input type="submit" id="sql_query_edit_save" class="button btnSave" value="' + PMA_messages.strGo + '"/>\n';
  1746. new_content += '<input type="button" id="sql_query_edit_discard" class="button btnDiscard" value="' + PMA_messages.strCancel + '"/>\n';
  1747. var $editor_area = $('div#inline_editor');
  1748. if ($editor_area.length === 0) {
  1749. $editor_area = $('<div id="inline_editor_outer"></div>');
  1750. $editor_area.insertBefore($inner_sql);
  1751. }
  1752. $editor_area.html(new_content);
  1753. loadForeignKeyCheckbox();
  1754. $inner_sql.hide();
  1755. bindCodeMirrorToInlineEditor();
  1756. return false;
  1757. });
  1758. $(document).on('click', 'input#sql_query_edit_save', function () {
  1759. // hide already existing success message
  1760. var sql_query;
  1761. if (codemirror_inline_editor) {
  1762. codemirror_inline_editor.save();
  1763. sql_query = codemirror_inline_editor.getValue();
  1764. } else {
  1765. sql_query = $(this).parent().find('#sql_query_edit').val();
  1766. }
  1767. var fk_check = $(this).parent().find('#fk_checks').is(':checked');
  1768. var $form = $('a.inline_edit_sql').prev('form');
  1769. var $fake_form = $('<form>', { action: 'import.php', method: 'post' })
  1770. .append($form.find('input[name=server], input[name=db], input[name=table], input[name=token]').clone())
  1771. .append($('<input/>', { type: 'hidden', name: 'show_query', value: 1 }))
  1772. .append($('<input/>', { type: 'hidden', name: 'is_js_confirmed', value: 0 }))
  1773. .append($('<input/>', { type: 'hidden', name: 'sql_query', value: sql_query }))
  1774. .append($('<input/>', { type: 'hidden', name: 'fk_checks', value: fk_check ? 1 : 0 }));
  1775. if (! checkSqlQuery($fake_form[0])) {
  1776. return false;
  1777. }
  1778. $('.success').hide();
  1779. $fake_form.appendTo($('body')).submit();
  1780. });
  1781. $(document).on('click', 'input#sql_query_edit_discard', function () {
  1782. var $divEditor = $('div#inline_editor_outer');
  1783. $divEditor.siblings('code.sql').show();
  1784. $divEditor.remove();
  1785. });
  1786. $(document).on('click', 'input.sqlbutton', function (evt) {
  1787. insertQuery(evt.target.id);
  1788. PMA_handleSimulateQueryButton();
  1789. return false;
  1790. });
  1791. $(document).on('change', '#parameterized', updateQueryParameters);
  1792. var $inputUsername = $('#input_username');
  1793. if ($inputUsername) {
  1794. if ($inputUsername.val() === '') {
  1795. $inputUsername.trigger('focus');
  1796. } else {
  1797. $('#input_password').trigger('focus');
  1798. }
  1799. }
  1800. });
  1801. /**
  1802. * "inputRead" event handler for CodeMirror SQL query editors for autocompletion
  1803. */
  1804. function codemirrorAutocompleteOnInputRead (instance) {
  1805. if (!sql_autocomplete_in_progress
  1806. && (!instance.options.hintOptions.tables || !sql_autocomplete)) {
  1807. if (!sql_autocomplete) {
  1808. // Reset after teardown
  1809. instance.options.hintOptions.tables = false;
  1810. instance.options.hintOptions.defaultTable = '';
  1811. sql_autocomplete_in_progress = true;
  1812. var href = 'db_sql_autocomplete.php';
  1813. var params = {
  1814. 'ajax_request': true,
  1815. 'server': PMA_commonParams.get('server'),
  1816. 'db': PMA_commonParams.get('db'),
  1817. 'no_debug': true
  1818. };
  1819. var columnHintRender = function (elem, self, data) {
  1820. $('<div class="autocomplete-column-name">')
  1821. .text(data.columnName)
  1822. .appendTo(elem);
  1823. $('<div class="autocomplete-column-hint">')
  1824. .text(data.columnHint)
  1825. .appendTo(elem);
  1826. };
  1827. $.ajax({
  1828. type: 'POST',
  1829. url: href,
  1830. data: params,
  1831. success: function (data) {
  1832. if (data.success) {
  1833. var tables = JSON.parse(data.tables);
  1834. sql_autocomplete_default_table = PMA_commonParams.get('table');
  1835. sql_autocomplete = [];
  1836. for (var table in tables) {
  1837. if (tables.hasOwnProperty(table)) {
  1838. var columns = tables[table];
  1839. table = {
  1840. text: table,
  1841. columns: []
  1842. };
  1843. for (var column in columns) {
  1844. if (columns.hasOwnProperty(column)) {
  1845. var displayText = columns[column].Type;
  1846. if (columns[column].Key === 'PRI') {
  1847. displayText += ' | Primary';
  1848. } else if (columns[column].Key === 'UNI') {
  1849. displayText += ' | Unique';
  1850. }
  1851. table.columns.push({
  1852. text: column,
  1853. displayText: column + ' | ' + displayText,
  1854. columnName: column,
  1855. columnHint: displayText,
  1856. render: columnHintRender
  1857. });
  1858. }
  1859. }
  1860. }
  1861. sql_autocomplete.push(table);
  1862. }
  1863. instance.options.hintOptions.tables = sql_autocomplete;
  1864. instance.options.hintOptions.defaultTable = sql_autocomplete_default_table;
  1865. }
  1866. },
  1867. complete: function () {
  1868. sql_autocomplete_in_progress = false;
  1869. }
  1870. });
  1871. } else {
  1872. instance.options.hintOptions.tables = sql_autocomplete;
  1873. instance.options.hintOptions.defaultTable = sql_autocomplete_default_table;
  1874. }
  1875. }
  1876. if (instance.state.completionActive) {
  1877. return;
  1878. }
  1879. var cur = instance.getCursor();
  1880. var token = instance.getTokenAt(cur);
  1881. var string = '';
  1882. if (token.string.match(/^[.`\w@]\w*$/)) {
  1883. string = token.string;
  1884. }
  1885. if (string.length > 0) {
  1886. CodeMirror.commands.autocomplete(instance);
  1887. }
  1888. }
  1889. /**
  1890. * Remove autocomplete information before tearing down a page
  1891. */
  1892. AJAX.registerTeardown('functions.js', function () {
  1893. sql_autocomplete = false;
  1894. sql_autocomplete_default_table = '';
  1895. });
  1896. /**
  1897. * Binds the CodeMirror to the text area used to inline edit a query.
  1898. */
  1899. function bindCodeMirrorToInlineEditor () {
  1900. var $inline_editor = $('#sql_query_edit');
  1901. if ($inline_editor.length > 0) {
  1902. if (typeof CodeMirror !== 'undefined') {
  1903. var height = $inline_editor.css('height');
  1904. codemirror_inline_editor = PMA_getSQLEditor($inline_editor);
  1905. codemirror_inline_editor.getWrapperElement().style.height = height;
  1906. codemirror_inline_editor.refresh();
  1907. codemirror_inline_editor.focus();
  1908. $(codemirror_inline_editor.getWrapperElement())
  1909. .on('keydown', catchKeypressesFromSqlInlineEdit);
  1910. } else {
  1911. $inline_editor
  1912. .focus()
  1913. .on('keydown', catchKeypressesFromSqlInlineEdit);
  1914. }
  1915. }
  1916. }
  1917. function catchKeypressesFromSqlInlineEdit (event) {
  1918. // ctrl-enter is 10 in chrome and ie, but 13 in ff
  1919. if ((event.ctrlKey || event.metaKey) && (event.keyCode === 13 || event.keyCode === 10)) {
  1920. $('#sql_query_edit_save').trigger('click');
  1921. }
  1922. }
  1923. /**
  1924. * Adds doc link to single highlighted SQL element
  1925. */
  1926. function PMA_doc_add ($elm, params) {
  1927. if (typeof mysql_doc_template === 'undefined') {
  1928. return;
  1929. }
  1930. var url = PMA_sprintf(
  1931. decodeURIComponent(mysql_doc_template),
  1932. params[0]
  1933. );
  1934. if (params.length > 1) {
  1935. url += '#' + params[1];
  1936. }
  1937. var content = $elm.text();
  1938. $elm.text('');
  1939. $elm.append('<a target="mysql_doc" class="cm-sql-doc" href="' + url + '">' + content + '</a>');
  1940. }
  1941. /**
  1942. * Generates doc links for keywords inside highlighted SQL
  1943. */
  1944. function PMA_doc_keyword (idx, elm) {
  1945. var $elm = $(elm);
  1946. /* Skip already processed ones */
  1947. if ($elm.find('a').length > 0) {
  1948. return;
  1949. }
  1950. var keyword = $elm.text().toUpperCase();
  1951. var $next = $elm.next('.cm-keyword');
  1952. if ($next) {
  1953. var next_keyword = $next.text().toUpperCase();
  1954. var full = keyword + ' ' + next_keyword;
  1955. var $next2 = $next.next('.cm-keyword');
  1956. if ($next2) {
  1957. var next2_keyword = $next2.text().toUpperCase();
  1958. var full2 = full + ' ' + next2_keyword;
  1959. if (full2 in mysql_doc_keyword) {
  1960. PMA_doc_add($elm, mysql_doc_keyword[full2]);
  1961. PMA_doc_add($next, mysql_doc_keyword[full2]);
  1962. PMA_doc_add($next2, mysql_doc_keyword[full2]);
  1963. return;
  1964. }
  1965. }
  1966. if (full in mysql_doc_keyword) {
  1967. PMA_doc_add($elm, mysql_doc_keyword[full]);
  1968. PMA_doc_add($next, mysql_doc_keyword[full]);
  1969. return;
  1970. }
  1971. }
  1972. if (keyword in mysql_doc_keyword) {
  1973. PMA_doc_add($elm, mysql_doc_keyword[keyword]);
  1974. }
  1975. }
  1976. /**
  1977. * Generates doc links for builtins inside highlighted SQL
  1978. */
  1979. function PMA_doc_builtin (idx, elm) {
  1980. var $elm = $(elm);
  1981. var builtin = $elm.text().toUpperCase();
  1982. if (builtin in mysql_doc_builtin) {
  1983. PMA_doc_add($elm, mysql_doc_builtin[builtin]);
  1984. }
  1985. }
  1986. /**
  1987. * Higlights SQL using CodeMirror.
  1988. */
  1989. function PMA_highlightSQL ($base) {
  1990. var $elm = $base.find('code.sql');
  1991. $elm.each(function () {
  1992. var $sql = $(this);
  1993. var $pre = $sql.find('pre');
  1994. /* We only care about visible elements to avoid double processing */
  1995. if ($pre.is(':visible')) {
  1996. var $highlight = $('<div class="sql-highlight cm-s-default"></div>');
  1997. $sql.append($highlight);
  1998. if (typeof CodeMirror !== 'undefined') {
  1999. CodeMirror.runMode($sql.text(), 'text/x-mysql', $highlight[0]);
  2000. $pre.hide();
  2001. $highlight.find('.cm-keyword').each(PMA_doc_keyword);
  2002. $highlight.find('.cm-builtin').each(PMA_doc_builtin);
  2003. }
  2004. }
  2005. });
  2006. }
  2007. /**
  2008. * Updates an element containing code.
  2009. *
  2010. * @param jQuery Object $base base element which contains the raw and the
  2011. * highlighted code.
  2012. *
  2013. * @param string htmlValue code in HTML format, displayed if code cannot be
  2014. * highlighted
  2015. *
  2016. * @param string rawValue raw code, used as a parameter for highlighter
  2017. *
  2018. * @return bool whether content was updated or not
  2019. */
  2020. function PMA_updateCode ($base, htmlValue, rawValue) {
  2021. var $code = $base.find('code');
  2022. if ($code.length === 0) {
  2023. return false;
  2024. }
  2025. // Determines the type of the content and appropriate CodeMirror mode.
  2026. var type = '';
  2027. var mode = '';
  2028. if ($code.hasClass('json')) {
  2029. type = 'json';
  2030. mode = 'application/json';
  2031. } else if ($code.hasClass('sql')) {
  2032. type = 'sql';
  2033. mode = 'text/x-mysql';
  2034. } else if ($code.hasClass('xml')) {
  2035. type = 'xml';
  2036. mode = 'application/xml';
  2037. } else {
  2038. return false;
  2039. }
  2040. // Element used to display unhighlighted code.
  2041. var $notHighlighted = $('<pre>' + htmlValue + '</pre>');
  2042. // Tries to highlight code using CodeMirror.
  2043. if (typeof CodeMirror !== 'undefined') {
  2044. var $highlighted = $('<div class="' + type + '-highlight cm-s-default"></div>');
  2045. CodeMirror.runMode(rawValue, mode, $highlighted[0]);
  2046. $notHighlighted.hide();
  2047. $code.html('').append($notHighlighted, $highlighted[0]);
  2048. } else {
  2049. $code.html('').append($notHighlighted);
  2050. }
  2051. return true;
  2052. }
  2053. /**
  2054. * Show a message on the top of the page for an Ajax request
  2055. *
  2056. * Sample usage:
  2057. *
  2058. * 1) var $msg = PMA_ajaxShowMessage();
  2059. * This will show a message that reads "Loading...". Such a message will not
  2060. * disappear automatically and cannot be dismissed by the user. To remove this
  2061. * message either the PMA_ajaxRemoveMessage($msg) function must be called or
  2062. * another message must be show with PMA_ajaxShowMessage() function.
  2063. *
  2064. * 2) var $msg = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
  2065. * This is a special case. The behaviour is same as above,
  2066. * just with a different message
  2067. *
  2068. * 3) var $msg = PMA_ajaxShowMessage('The operation was successful');
  2069. * This will show a message that will disappear automatically and it can also
  2070. * be dismissed by the user.
  2071. *
  2072. * 4) var $msg = PMA_ajaxShowMessage('Some error', false);
  2073. * This will show a message that will not disappear automatically, but it
  2074. * can be dismissed by the user after he has finished reading it.
  2075. *
  2076. * @param string message string containing the message to be shown.
  2077. * optional, defaults to 'Loading...'
  2078. * @param mixed timeout number of milliseconds for the message to be visible
  2079. * optional, defaults to 5000. If set to 'false', the
  2080. * notification will never disappear
  2081. * @param string type string to dictate the type of message shown.
  2082. * optional, defaults to normal notification.
  2083. * If set to 'error', the notification will show message
  2084. * with red background.
  2085. * If set to 'success', the notification will show with
  2086. * a green background.
  2087. * @return jQuery object jQuery Element that holds the message div
  2088. * this object can be passed to PMA_ajaxRemoveMessage()
  2089. * to remove the notification
  2090. */
  2091. function PMA_ajaxShowMessage (message, timeout, type) {
  2092. /**
  2093. * @var self_closing Whether the notification will automatically disappear
  2094. */
  2095. var self_closing = true;
  2096. /**
  2097. * @var dismissable Whether the user will be able to remove
  2098. * the notification by clicking on it
  2099. */
  2100. var dismissable = true;
  2101. // Handle the case when a empty data.message is passed.
  2102. // We don't want the empty message
  2103. if (message === '') {
  2104. return true;
  2105. } else if (! message) {
  2106. // If the message is undefined, show the default
  2107. message = PMA_messages.strLoading;
  2108. dismissable = false;
  2109. self_closing = false;
  2110. } else if (message === PMA_messages.strProcessingRequest) {
  2111. // This is another case where the message should not disappear
  2112. dismissable = false;
  2113. self_closing = false;
  2114. }
  2115. // Figure out whether (or after how long) to remove the notification
  2116. if (timeout === undefined) {
  2117. timeout = 5000;
  2118. } else if (timeout === false) {
  2119. self_closing = false;
  2120. }
  2121. // Determine type of message, add styling as required
  2122. if (type === 'error') {
  2123. message = '<div class="error">' + message + '</div>';
  2124. } else if (type === 'success') {
  2125. message = '<div class="success">' + message + '</div>';
  2126. }
  2127. // Create a parent element for the AJAX messages, if necessary
  2128. if ($('#loading_parent').length === 0) {
  2129. $('<div id="loading_parent"></div>')
  2130. .prependTo('#page_content');
  2131. }
  2132. // Update message count to create distinct message elements every time
  2133. ajax_message_count++;
  2134. // Remove all old messages, if any
  2135. $('span.ajax_notification[id^=ajax_message_num]').remove();
  2136. /**
  2137. * @var $retval a jQuery object containing the reference
  2138. * to the created AJAX message
  2139. */
  2140. var $retval = $(
  2141. '<span class="ajax_notification" id="ajax_message_num_' +
  2142. ajax_message_count +
  2143. '"></span>'
  2144. )
  2145. .hide()
  2146. .appendTo('#loading_parent')
  2147. .html(message)
  2148. .show();
  2149. // If the notification is self-closing we should create a callback to remove it
  2150. if (self_closing) {
  2151. $retval
  2152. .delay(timeout)
  2153. .fadeOut('medium', function () {
  2154. if ($(this).is(':data(tooltip)')) {
  2155. $(this).tooltip('destroy');
  2156. }
  2157. // Remove the notification
  2158. $(this).remove();
  2159. });
  2160. }
  2161. // If the notification is dismissable we need to add the relevant class to it
  2162. // and add a tooltip so that the users know that it can be removed
  2163. if (dismissable) {
  2164. $retval.addClass('dismissable').css('cursor', 'pointer');
  2165. /**
  2166. * Add a tooltip to the notification to let the user know that (s)he
  2167. * can dismiss the ajax notification by clicking on it.
  2168. */
  2169. PMA_tooltip(
  2170. $retval,
  2171. 'span',
  2172. PMA_messages.strDismiss
  2173. );
  2174. }
  2175. PMA_highlightSQL($retval);
  2176. return $retval;
  2177. }
  2178. /**
  2179. * Removes the message shown for an Ajax operation when it's completed
  2180. *
  2181. * @param jQuery object jQuery Element that holds the notification
  2182. *
  2183. * @return nothing
  2184. */
  2185. function PMA_ajaxRemoveMessage ($this_msgbox) {
  2186. if ($this_msgbox !== undefined && $this_msgbox instanceof jQuery) {
  2187. $this_msgbox
  2188. .stop(true, true)
  2189. .fadeOut('medium');
  2190. if ($this_msgbox.is(':data(tooltip)')) {
  2191. $this_msgbox.tooltip('destroy');
  2192. } else {
  2193. $this_msgbox.remove();
  2194. }
  2195. }
  2196. }
  2197. /**
  2198. * Requests SQL for previewing before executing.
  2199. *
  2200. * @param jQuery Object $form Form containing query data
  2201. *
  2202. * @return void
  2203. */
  2204. function PMA_previewSQL ($form) {
  2205. var form_url = $form.attr('action');
  2206. var sep = PMA_commonParams.get('arg_separator');
  2207. var form_data = $form.serialize() +
  2208. sep + 'do_save_data=1' +
  2209. sep + 'preview_sql=1' +
  2210. sep + 'ajax_request=1';
  2211. var $msgbox = PMA_ajaxShowMessage();
  2212. $.ajax({
  2213. type: 'POST',
  2214. url: form_url,
  2215. data: form_data,
  2216. success: function (response) {
  2217. PMA_ajaxRemoveMessage($msgbox);
  2218. if (response.success) {
  2219. var $dialog_content = $('<div/>')
  2220. .append(response.sql_data);
  2221. var button_options = {};
  2222. button_options[PMA_messages.strClose] = function () {
  2223. $(this).dialog('close');
  2224. };
  2225. var $response_dialog = $dialog_content.dialog({
  2226. minWidth: 550,
  2227. maxHeight: 400,
  2228. modal: true,
  2229. buttons: button_options,
  2230. title: PMA_messages.strPreviewSQL,
  2231. close: function () {
  2232. $(this).remove();
  2233. },
  2234. open: function () {
  2235. // Pretty SQL printing.
  2236. PMA_highlightSQL($(this));
  2237. }
  2238. });
  2239. } else {
  2240. PMA_ajaxShowMessage(response.message);
  2241. }
  2242. },
  2243. error: function () {
  2244. PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest);
  2245. }
  2246. });
  2247. }
  2248. /**
  2249. * check for reserved keyword column name
  2250. *
  2251. * @param jQuery Object $form Form
  2252. *
  2253. * @returns true|false
  2254. */
  2255. function PMA_checkReservedWordColumns ($form) {
  2256. var is_confirmed = true;
  2257. $.ajax({
  2258. type: 'POST',
  2259. url: 'tbl_structure.php',
  2260. data: $form.serialize() + PMA_commonParams.get('arg_separator') + 'reserved_word_check=1',
  2261. success: function (data) {
  2262. if (typeof data.success !== 'undefined' && data.success === true) {
  2263. is_confirmed = confirm(data.message);
  2264. }
  2265. },
  2266. async:false
  2267. });
  2268. return is_confirmed;
  2269. }
  2270. // This event only need to be fired once after the initial page load
  2271. $(function () {
  2272. /**
  2273. * Allows the user to dismiss a notification
  2274. * created with PMA_ajaxShowMessage()
  2275. */
  2276. $(document).on('click', 'span.ajax_notification.dismissable', function () {
  2277. PMA_ajaxRemoveMessage($(this));
  2278. });
  2279. /**
  2280. * The below two functions hide the "Dismiss notification" tooltip when a user
  2281. * is hovering a link or button that is inside an ajax message
  2282. */
  2283. $(document).on('mouseover', 'span.ajax_notification a, span.ajax_notification button, span.ajax_notification input', function () {
  2284. if ($(this).parents('span.ajax_notification').is(':data(tooltip)')) {
  2285. $(this).parents('span.ajax_notification').tooltip('disable');
  2286. }
  2287. });
  2288. $(document).on('mouseout', 'span.ajax_notification a, span.ajax_notification button, span.ajax_notification input', function () {
  2289. if ($(this).parents('span.ajax_notification').is(':data(tooltip)')) {
  2290. $(this).parents('span.ajax_notification').tooltip('enable');
  2291. }
  2292. });
  2293. });
  2294. /**
  2295. * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
  2296. */
  2297. function PMA_showNoticeForEnum (selectElement) {
  2298. var enum_notice_id = selectElement.attr('id').split('_')[1];
  2299. enum_notice_id += '_' + (parseInt(selectElement.attr('id').split('_')[2], 10) + 1);
  2300. var selectedType = selectElement.val();
  2301. if (selectedType === 'ENUM' || selectedType === 'SET') {
  2302. $('p#enum_notice_' + enum_notice_id).show();
  2303. } else {
  2304. $('p#enum_notice_' + enum_notice_id).hide();
  2305. }
  2306. }
  2307. /**
  2308. * Creates a Profiling Chart. Used in sql.js
  2309. * and in server_status_monitor.js
  2310. */
  2311. function PMA_createProfilingChart (target, data) {
  2312. // create the chart
  2313. var factory = new JQPlotChartFactory();
  2314. var chart = factory.createChart(ChartType.PIE, target);
  2315. // create the data table and add columns
  2316. var dataTable = new DataTable();
  2317. dataTable.addColumn(ColumnType.STRING, '');
  2318. dataTable.addColumn(ColumnType.NUMBER, '');
  2319. dataTable.setData(data);
  2320. var windowWidth = $(window).width();
  2321. var location = 's';
  2322. if (windowWidth > 768) {
  2323. var location = 'se';
  2324. }
  2325. // draw the chart and return the chart object
  2326. chart.draw(dataTable, {
  2327. seriesDefaults: {
  2328. rendererOptions: {
  2329. showDataLabels: true
  2330. }
  2331. },
  2332. highlighter: {
  2333. tooltipLocation: 'se',
  2334. sizeAdjust: 0,
  2335. tooltipAxes: 'pieref',
  2336. formatString: '%s, %.9Ps'
  2337. },
  2338. legend: {
  2339. show: true,
  2340. location: location,
  2341. rendererOptions: {
  2342. numberColumns: 2
  2343. }
  2344. },
  2345. // from http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines#Color_Palette
  2346. seriesColors: [
  2347. '#fce94f',
  2348. '#fcaf3e',
  2349. '#e9b96e',
  2350. '#8ae234',
  2351. '#729fcf',
  2352. '#ad7fa8',
  2353. '#ef2929',
  2354. '#888a85',
  2355. '#c4a000',
  2356. '#ce5c00',
  2357. '#8f5902',
  2358. '#4e9a06',
  2359. '#204a87',
  2360. '#5c3566',
  2361. '#a40000',
  2362. '#babdb6',
  2363. '#2e3436'
  2364. ]
  2365. });
  2366. return chart;
  2367. }
  2368. /**
  2369. * Formats a profiling duration nicely (in us and ms time).
  2370. * Used in server_status_monitor.js
  2371. *
  2372. * @param integer Number to be formatted, should be in the range of microsecond to second
  2373. * @param integer Accuracy, how many numbers right to the comma should be
  2374. * @return string The formatted number
  2375. */
  2376. function PMA_prettyProfilingNum (num, acc) {
  2377. if (!acc) {
  2378. acc = 2;
  2379. }
  2380. acc = Math.pow(10, acc);
  2381. if (num * 1000 < 0.1) {
  2382. num = Math.round(acc * (num * 1000 * 1000)) / acc + 'µ';
  2383. } else if (num < 0.1) {
  2384. num = Math.round(acc * (num * 1000)) / acc + 'm';
  2385. } else {
  2386. num = Math.round(acc * num) / acc;
  2387. }
  2388. return num + 's';
  2389. }
  2390. /**
  2391. * Formats a SQL Query nicely with newlines and indentation. Depends on Codemirror and MySQL Mode!
  2392. *
  2393. * @param string Query to be formatted
  2394. * @return string The formatted query
  2395. */
  2396. function PMA_SQLPrettyPrint (string) {
  2397. if (typeof CodeMirror === 'undefined') {
  2398. return string;
  2399. }
  2400. var mode = CodeMirror.getMode({}, 'text/x-mysql');
  2401. var stream = new CodeMirror.StringStream(string);
  2402. var state = mode.startState();
  2403. var token;
  2404. var tokens = [];
  2405. var output = '';
  2406. var tabs = function (cnt) {
  2407. var ret = '';
  2408. for (var i = 0; i < 4 * cnt; i++) {
  2409. ret += ' ';
  2410. }
  2411. return ret;
  2412. };
  2413. // "root-level" statements
  2414. var statements = {
  2415. 'select': ['select', 'from', 'on', 'where', 'having', 'limit', 'order by', 'group by'],
  2416. 'update': ['update', 'set', 'where'],
  2417. 'insert into': ['insert into', 'values']
  2418. };
  2419. // don't put spaces before these tokens
  2420. var spaceExceptionsBefore = { ';': true, ',': true, '.': true, '(': true };
  2421. // don't put spaces after these tokens
  2422. var spaceExceptionsAfter = { '.': true };
  2423. // Populate tokens array
  2424. var str = '';
  2425. while (! stream.eol()) {
  2426. stream.start = stream.pos;
  2427. token = mode.token(stream, state);
  2428. if (token !== null) {
  2429. tokens.push([token, stream.current().toLowerCase()]);
  2430. }
  2431. }
  2432. var currentStatement = tokens[0][1];
  2433. if (! statements[currentStatement]) {
  2434. return string;
  2435. }
  2436. // Holds all currently opened code blocks (statement, function or generic)
  2437. var blockStack = [];
  2438. // Holds the type of block from last iteration (the current is in blockStack[0])
  2439. var previousBlock;
  2440. // If a new code block is found, newBlock contains its type for one iteration and vice versa for endBlock
  2441. var newBlock;
  2442. var endBlock;
  2443. // How much to indent in the current line
  2444. var indentLevel = 0;
  2445. // Holds the "root-level" statements
  2446. var statementPart;
  2447. var lastStatementPart = statements[currentStatement][0];
  2448. blockStack.unshift('statement');
  2449. // Iterate through every token and format accordingly
  2450. for (var i = 0; i < tokens.length; i++) {
  2451. previousBlock = blockStack[0];
  2452. // New block => push to stack
  2453. if (tokens[i][1] === '(') {
  2454. if (i < tokens.length - 1 && tokens[i + 1][0] === 'statement-verb') {
  2455. blockStack.unshift(newBlock = 'statement');
  2456. } else if (i > 0 && tokens[i - 1][0] === 'builtin') {
  2457. blockStack.unshift(newBlock = 'function');
  2458. } else {
  2459. blockStack.unshift(newBlock = 'generic');
  2460. }
  2461. } else {
  2462. newBlock = null;
  2463. }
  2464. // Block end => pop from stack
  2465. if (tokens[i][1] === ')') {
  2466. endBlock = blockStack[0];
  2467. blockStack.shift();
  2468. } else {
  2469. endBlock = null;
  2470. }
  2471. // A subquery is starting
  2472. if (i > 0 && newBlock === 'statement') {
  2473. indentLevel++;
  2474. output += '\n' + tabs(indentLevel) + tokens[i][1] + ' ' + tokens[i + 1][1].toUpperCase() + '\n' + tabs(indentLevel + 1);
  2475. currentStatement = tokens[i + 1][1];
  2476. i++;
  2477. continue;
  2478. }
  2479. // A subquery is ending
  2480. if (endBlock === 'statement' && indentLevel > 0) {
  2481. output += '\n' + tabs(indentLevel);
  2482. indentLevel--;
  2483. }
  2484. // One less indentation for statement parts (from, where, order by, etc.) and a newline
  2485. statementPart = statements[currentStatement].indexOf(tokens[i][1]);
  2486. if (statementPart !== -1) {
  2487. if (i > 0) {
  2488. output += '\n';
  2489. }
  2490. output += tabs(indentLevel) + tokens[i][1].toUpperCase();
  2491. output += '\n' + tabs(indentLevel + 1);
  2492. lastStatementPart = tokens[i][1];
  2493. // Normal indentation and spaces for everything else
  2494. } else {
  2495. if (! spaceExceptionsBefore[tokens[i][1]] &&
  2496. ! (i > 0 && spaceExceptionsAfter[tokens[i - 1][1]]) &&
  2497. output.charAt(output.length - 1) !== ' ') {
  2498. output += ' ';
  2499. }
  2500. if (tokens[i][0] === 'keyword') {
  2501. output += tokens[i][1].toUpperCase();
  2502. } else {
  2503. output += tokens[i][1];
  2504. }
  2505. }
  2506. // split columns in select and 'update set' clauses, but only inside statements blocks
  2507. if ((lastStatementPart === 'select' || lastStatementPart === 'where' || lastStatementPart === 'set') &&
  2508. tokens[i][1] === ',' && blockStack[0] === 'statement') {
  2509. output += '\n' + tabs(indentLevel + 1);
  2510. }
  2511. // split conditions in where clauses, but only inside statements blocks
  2512. if (lastStatementPart === 'where' &&
  2513. (tokens[i][1] === 'and' || tokens[i][1] === 'or' || tokens[i][1] === 'xor')) {
  2514. if (blockStack[0] === 'statement') {
  2515. output += '\n' + tabs(indentLevel + 1);
  2516. }
  2517. // Todo: Also split and or blocks in newlines & indentation++
  2518. // if (blockStack[0] === 'generic')
  2519. // output += ...
  2520. }
  2521. }
  2522. return output;
  2523. }
  2524. /**
  2525. * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
  2526. * return a jQuery object yet and hence cannot be chained
  2527. *
  2528. * @param string question
  2529. * @param string url URL to be passed to the callbackFn to make
  2530. * an Ajax call to
  2531. * @param function callbackFn callback to execute after user clicks on OK
  2532. * @param function openCallback optional callback to run when dialog is shown
  2533. */
  2534. jQuery.fn.PMA_confirm = function (question, url, callbackFn, openCallback) {
  2535. var confirmState = PMA_commonParams.get('confirm');
  2536. if (! confirmState) {
  2537. // user does not want to confirm
  2538. if ($.isFunction(callbackFn)) {
  2539. callbackFn.call(this, url);
  2540. return true;
  2541. }
  2542. }
  2543. if (PMA_messages.strDoYouReally === '') {
  2544. return true;
  2545. }
  2546. /**
  2547. * @var button_options Object that stores the options passed to jQueryUI
  2548. * dialog
  2549. */
  2550. var button_options = [
  2551. {
  2552. text: PMA_messages.strOK,
  2553. 'class': 'submitOK',
  2554. click: function () {
  2555. $(this).dialog('close');
  2556. if ($.isFunction(callbackFn)) {
  2557. callbackFn.call(this, url);
  2558. }
  2559. }
  2560. },
  2561. {
  2562. text: PMA_messages.strCancel,
  2563. 'class': 'submitCancel',
  2564. click: function () {
  2565. $(this).dialog('close');
  2566. }
  2567. }
  2568. ];
  2569. $('<div/>', { 'id': 'confirm_dialog', 'title': PMA_messages.strConfirm })
  2570. .prepend(question)
  2571. .dialog({
  2572. buttons: button_options,
  2573. close: function () {
  2574. $(this).remove();
  2575. },
  2576. open: openCallback,
  2577. modal: true
  2578. });
  2579. };
  2580. /**
  2581. * jQuery function to sort a table's body after a new row has been appended to it.
  2582. *
  2583. * @param string text_selector string to select the sortKey's text
  2584. *
  2585. * @return jQuery Object for chaining purposes
  2586. */
  2587. jQuery.fn.PMA_sort_table = function (text_selector) {
  2588. return this.each(function () {
  2589. /**
  2590. * @var table_body Object referring to the table's <tbody> element
  2591. */
  2592. var table_body = $(this);
  2593. /**
  2594. * @var rows Object referring to the collection of rows in {@link table_body}
  2595. */
  2596. var rows = $(this).find('tr').get();
  2597. // get the text of the field that we will sort by
  2598. $.each(rows, function (index, row) {
  2599. row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
  2600. });
  2601. // get the sorted order
  2602. rows.sort(function (a, b) {
  2603. if (a.sortKey < b.sortKey) {
  2604. return -1;
  2605. }
  2606. if (a.sortKey > b.sortKey) {
  2607. return 1;
  2608. }
  2609. return 0;
  2610. });
  2611. // pull out each row from the table and then append it according to it's order
  2612. $.each(rows, function (index, row) {
  2613. $(table_body).append(row);
  2614. row.sortKey = null;
  2615. });
  2616. });
  2617. };
  2618. /**
  2619. * Unbind all event handlers before tearing down a page
  2620. */
  2621. AJAX.registerTeardown('functions.js', function () {
  2622. $(document).off('submit', '#create_table_form_minimal.ajax');
  2623. $(document).off('submit', 'form.create_table_form.ajax');
  2624. $(document).off('click', 'form.create_table_form.ajax input[name=submit_num_fields]');
  2625. $(document).off('keyup', 'form.create_table_form.ajax input');
  2626. $(document).off('change', 'input[name=partition_count],input[name=subpartition_count],select[name=partition_by]');
  2627. });
  2628. /**
  2629. * jQuery coding for 'Create Table'. Used on db_operations.php,
  2630. * db_structure.php and db_tracking.php (i.e., wherever
  2631. * PhpMyAdmin\Display\CreateTable is used)
  2632. *
  2633. * Attach Ajax Event handlers for Create Table
  2634. */
  2635. AJAX.registerOnload('functions.js', function () {
  2636. /**
  2637. * Attach event handler for submission of create table form (save)
  2638. */
  2639. $(document).on('submit', 'form.create_table_form.ajax', function (event) {
  2640. event.preventDefault();
  2641. /**
  2642. * @var the_form object referring to the create table form
  2643. */
  2644. var $form = $(this);
  2645. /*
  2646. * First validate the form; if there is a problem, avoid submitting it
  2647. *
  2648. * checkTableEditForm() needs a pure element and not a jQuery object,
  2649. * this is why we pass $form[0] as a parameter (the jQuery object
  2650. * is actually an array of DOM elements)
  2651. */
  2652. if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
  2653. PMA_prepareForAjaxRequest($form);
  2654. if (PMA_checkReservedWordColumns($form)) {
  2655. PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
  2656. // User wants to submit the form
  2657. $.post($form.attr('action'), $form.serialize() + PMA_commonParams.get('arg_separator') + 'do_save_data=1', function (data) {
  2658. if (typeof data !== 'undefined' && data.success === true) {
  2659. $('#properties_message')
  2660. .removeClass('error')
  2661. .html('');
  2662. PMA_ajaxShowMessage(data.message);
  2663. // Only if the create table dialog (distinct panel) exists
  2664. var $createTableDialog = $('#create_table_dialog');
  2665. if ($createTableDialog.length > 0) {
  2666. $createTableDialog.dialog('close').remove();
  2667. }
  2668. $('#tableslistcontainer').before(data.formatted_sql);
  2669. /**
  2670. * @var tables_table Object referring to the <tbody> element that holds the list of tables
  2671. */
  2672. var tables_table = $('#tablesForm').find('tbody').not('#tbl_summary_row');
  2673. // this is the first table created in this db
  2674. if (tables_table.length === 0) {
  2675. PMA_commonActions.refreshMain(
  2676. PMA_commonParams.get('opendb_url')
  2677. );
  2678. } else {
  2679. /**
  2680. * @var curr_last_row Object referring to the last <tr> element in {@link tables_table}
  2681. */
  2682. var curr_last_row = $(tables_table).find('tr:last');
  2683. /**
  2684. * @var curr_last_row_index_string String containing the index of {@link curr_last_row}
  2685. */
  2686. var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
  2687. /**
  2688. * @var curr_last_row_index Index of {@link curr_last_row}
  2689. */
  2690. var curr_last_row_index = parseFloat(curr_last_row_index_string);
  2691. /**
  2692. * @var new_last_row_index Index of the new row to be appended to {@link tables_table}
  2693. */
  2694. var new_last_row_index = curr_last_row_index + 1;
  2695. /**
  2696. * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
  2697. */
  2698. var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
  2699. data.new_table_string = data.new_table_string.replace(/checkbox_tbl_/, new_last_row_id);
  2700. // append to table
  2701. $(data.new_table_string)
  2702. .appendTo(tables_table);
  2703. // Sort the table
  2704. $(tables_table).PMA_sort_table('th');
  2705. // Adjust summary row
  2706. PMA_adjustTotals();
  2707. }
  2708. // Refresh navigation as a new table has been added
  2709. PMA_reloadNavigation();
  2710. // Redirect to table structure page on creation of new table
  2711. var argsep = PMA_commonParams.get('arg_separator');
  2712. var params_12 = 'ajax_request=true' + argsep + 'ajax_page_request=true';
  2713. if (! (history && history.pushState)) {
  2714. params_12 += PMA_MicroHistory.menus.getRequestParam();
  2715. }
  2716. tblStruct_url = 'tbl_structure.php?server=' + data._params.server +
  2717. argsep + 'db=' + data._params.db + argsep + 'token=' + data._params.token +
  2718. argsep + 'goto=db_structure.php' + argsep + 'table=' + data._params.table + '';
  2719. $.get(tblStruct_url, params_12, AJAX.responseHandler);
  2720. } else {
  2721. PMA_ajaxShowMessage(
  2722. '<div class="error">' + data.error + '</div>',
  2723. false
  2724. );
  2725. }
  2726. }); // end $.post()
  2727. }
  2728. } // end if (checkTableEditForm() )
  2729. }); // end create table form (save)
  2730. /**
  2731. * Submits the intermediate changes in the table creation form
  2732. * to refresh the UI accordingly
  2733. */
  2734. function submitChangesInCreateTableForm (actionParam) {
  2735. /**
  2736. * @var the_form object referring to the create table form
  2737. */
  2738. var $form = $('form.create_table_form.ajax');
  2739. var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
  2740. PMA_prepareForAjaxRequest($form);
  2741. // User wants to add more fields to the table
  2742. $.post($form.attr('action'), $form.serialize() + '&' + actionParam, function (data) {
  2743. if (typeof data !== 'undefined' && data.success) {
  2744. var $pageContent = $('#page_content');
  2745. $pageContent.html(data.message);
  2746. PMA_highlightSQL($pageContent);
  2747. PMA_verifyColumnsProperties();
  2748. PMA_hideShowConnection($('.create_table_form select[name=tbl_storage_engine]'));
  2749. PMA_ajaxRemoveMessage($msgbox);
  2750. } else {
  2751. PMA_ajaxShowMessage(data.error);
  2752. }
  2753. }); // end $.post()
  2754. }
  2755. /**
  2756. * Attach event handler for create table form (add fields)
  2757. */
  2758. $(document).on('click', 'form.create_table_form.ajax input[name=submit_num_fields]', function (event) {
  2759. event.preventDefault();
  2760. submitChangesInCreateTableForm('submit_num_fields=1');
  2761. }); // end create table form (add fields)
  2762. $(document).on('keydown', 'form.create_table_form.ajax input[name=added_fields]', function (event) {
  2763. if (event.keyCode === 13) {
  2764. event.preventDefault();
  2765. event.stopImmediatePropagation();
  2766. $(this)
  2767. .closest('form')
  2768. .find('input[name=submit_num_fields]')
  2769. .click();
  2770. }
  2771. });
  2772. /**
  2773. * Attach event handler to manage changes in number of partitions and subpartitions
  2774. */
  2775. $(document).on('change', 'input[name=partition_count],input[name=subpartition_count],select[name=partition_by]', function (event) {
  2776. $this = $(this);
  2777. $form = $this.parents('form');
  2778. if ($form.is('.create_table_form.ajax')) {
  2779. submitChangesInCreateTableForm('submit_partition_change=1');
  2780. } else {
  2781. $form.submit();
  2782. }
  2783. });
  2784. $(document).on('change', 'input[value=AUTO_INCREMENT]', function () {
  2785. if (this.checked) {
  2786. var col = /\d/.exec($(this).attr('name'));
  2787. col = col[0];
  2788. var $selectFieldKey = $('select[name="field_key[' + col + ']"]');
  2789. if ($selectFieldKey.val() === 'none_' + col) {
  2790. $selectFieldKey.val('primary_' + col).change();
  2791. }
  2792. }
  2793. });
  2794. $('body')
  2795. .off('click', 'input.preview_sql')
  2796. .on('click', 'input.preview_sql', function () {
  2797. var $form = $(this).closest('form');
  2798. PMA_previewSQL($form);
  2799. });
  2800. });
  2801. /**
  2802. * Validates the password field in a form
  2803. *
  2804. * @see PMA_messages.strPasswordEmpty
  2805. * @see PMA_messages.strPasswordNotSame
  2806. * @param object $the_form The form to be validated
  2807. * @return bool
  2808. */
  2809. function PMA_checkPassword ($the_form) {
  2810. // Did the user select 'no password'?
  2811. if ($the_form.find('#nopass_1').is(':checked')) {
  2812. return true;
  2813. } else {
  2814. var $pred = $the_form.find('#select_pred_password');
  2815. if ($pred.length && ($pred.val() === 'none' || $pred.val() === 'keep')) {
  2816. return true;
  2817. }
  2818. }
  2819. var $password = $the_form.find('input[name=pma_pw]');
  2820. var $password_repeat = $the_form.find('input[name=pma_pw2]');
  2821. var alert_msg = false;
  2822. if ($password.val() === '') {
  2823. alert_msg = PMA_messages.strPasswordEmpty;
  2824. } else if ($password.val() !== $password_repeat.val()) {
  2825. alert_msg = PMA_messages.strPasswordNotSame;
  2826. }
  2827. if (alert_msg) {
  2828. alert(alert_msg);
  2829. $password.val('');
  2830. $password_repeat.val('');
  2831. $password.focus();
  2832. return false;
  2833. }
  2834. return true;
  2835. }
  2836. /**
  2837. * Attach Ajax event handlers for 'Change Password' on index.php
  2838. */
  2839. AJAX.registerOnload('functions.js', function () {
  2840. /* Handler for hostname type */
  2841. $(document).on('change', '#select_pred_hostname', function () {
  2842. var hostname = $('#pma_hostname');
  2843. if (this.value === 'any') {
  2844. hostname.val('%');
  2845. } else if (this.value === 'localhost') {
  2846. hostname.val('localhost');
  2847. } else if (this.value === 'thishost' && $(this).data('thishost')) {
  2848. hostname.val($(this).data('thishost'));
  2849. } else if (this.value === 'hosttable') {
  2850. hostname.val('').prop('required', false);
  2851. } else if (this.value === 'userdefined') {
  2852. hostname.focus().select().prop('required', true);
  2853. }
  2854. });
  2855. /* Handler for editing hostname */
  2856. $(document).on('change', '#pma_hostname', function () {
  2857. $('#select_pred_hostname').val('userdefined');
  2858. $('#pma_hostname').prop('required', true);
  2859. });
  2860. /* Handler for username type */
  2861. $(document).on('change', '#select_pred_username', function () {
  2862. if (this.value === 'any') {
  2863. $('#pma_username').val('').prop('required', false);
  2864. $('#user_exists_warning').css('display', 'none');
  2865. } else if (this.value === 'userdefined') {
  2866. $('#pma_username').focus().select().prop('required', true);
  2867. }
  2868. });
  2869. /* Handler for editing username */
  2870. $(document).on('change', '#pma_username', function () {
  2871. $('#select_pred_username').val('userdefined');
  2872. $('#pma_username').prop('required', true);
  2873. });
  2874. /* Handler for password type */
  2875. $(document).on('change', '#select_pred_password', function () {
  2876. if (this.value === 'none') {
  2877. $('#text_pma_pw2').prop('required', false).val('');
  2878. $('#text_pma_pw').prop('required', false).val('');
  2879. } else if (this.value === 'userdefined') {
  2880. $('#text_pma_pw2').prop('required', true);
  2881. $('#text_pma_pw').prop('required', true).focus().select();
  2882. } else {
  2883. $('#text_pma_pw2').prop('required', false);
  2884. $('#text_pma_pw').prop('required', false);
  2885. }
  2886. });
  2887. /* Handler for editing password */
  2888. $(document).on('change', '#text_pma_pw,#text_pma_pw2', function () {
  2889. $('#select_pred_password').val('userdefined');
  2890. $('#text_pma_pw2').prop('required', true);
  2891. $('#text_pma_pw').prop('required', true);
  2892. });
  2893. /**
  2894. * Unbind all event handlers before tearing down a page
  2895. */
  2896. $(document).off('click', '#change_password_anchor.ajax');
  2897. /**
  2898. * Attach Ajax event handler on the change password anchor
  2899. */
  2900. $(document).on('click', '#change_password_anchor.ajax', function (event) {
  2901. event.preventDefault();
  2902. var $msgbox = PMA_ajaxShowMessage();
  2903. /**
  2904. * @var button_options Object containing options to be passed to jQueryUI's dialog
  2905. */
  2906. var button_options = {};
  2907. button_options[PMA_messages.strGo] = function () {
  2908. event.preventDefault();
  2909. /**
  2910. * @var $the_form Object referring to the change password form
  2911. */
  2912. var $the_form = $('#change_password_form');
  2913. if (! PMA_checkPassword($the_form)) {
  2914. return false;
  2915. }
  2916. /**
  2917. * @var this_value String containing the value of the submit button.
  2918. * Need to append this for the change password form on Server Privileges
  2919. * page to work
  2920. */
  2921. var this_value = $(this).val();
  2922. var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
  2923. $the_form.append('<input type="hidden" name="ajax_request" value="true" />');
  2924. $.post($the_form.attr('action'), $the_form.serialize() + PMA_commonParams.get('arg_separator') + 'change_pw=' + this_value, function (data) {
  2925. if (typeof data === 'undefined' || data.success !== true) {
  2926. PMA_ajaxShowMessage(data.error, false);
  2927. return;
  2928. }
  2929. var $pageContent = $('#page_content');
  2930. $pageContent.prepend(data.message);
  2931. PMA_highlightSQL($pageContent);
  2932. $('#change_password_dialog').hide().remove();
  2933. $('#edit_user_dialog').dialog('close').remove();
  2934. PMA_ajaxRemoveMessage($msgbox);
  2935. }); // end $.post()
  2936. };
  2937. button_options[PMA_messages.strCancel] = function () {
  2938. $(this).dialog('close');
  2939. };
  2940. $.get($(this).attr('href'), { 'ajax_request': true }, function (data) {
  2941. if (typeof data === 'undefined' || !data.success) {
  2942. PMA_ajaxShowMessage(data.error, false);
  2943. return;
  2944. }
  2945. if (data._scripts) {
  2946. AJAX.scriptHandler.load(data._scripts);
  2947. }
  2948. $('<div id="change_password_dialog"></div>')
  2949. .dialog({
  2950. title: PMA_messages.strChangePassword,
  2951. width: 600,
  2952. close: function (ev, ui) {
  2953. $(this).remove();
  2954. },
  2955. buttons: button_options,
  2956. modal: true
  2957. })
  2958. .append(data.message);
  2959. // for this dialog, we remove the fieldset wrapping due to double headings
  2960. $('fieldset#fieldset_change_password')
  2961. .find('legend').remove().end()
  2962. .find('table.noclick').unwrap().addClass('some-margin')
  2963. .find('input#text_pma_pw').focus();
  2964. $('#fieldset_change_password_footer').hide();
  2965. PMA_ajaxRemoveMessage($msgbox);
  2966. $('#change_password_form').on('submit', function (e) {
  2967. e.preventDefault();
  2968. $(this)
  2969. .closest('.ui-dialog')
  2970. .find('.ui-dialog-buttonpane .ui-button')
  2971. .first()
  2972. .click();
  2973. });
  2974. }); // end $.get()
  2975. }); // end handler for change password anchor
  2976. }); // end $() for Change Password
  2977. /**
  2978. * Unbind all event handlers before tearing down a page
  2979. */
  2980. AJAX.registerTeardown('functions.js', function () {
  2981. $(document).off('change', 'select.column_type');
  2982. $(document).off('change', 'select.default_type');
  2983. $(document).off('change', 'select.virtuality');
  2984. $(document).off('change', 'input.allow_null');
  2985. $(document).off('change', '.create_table_form select[name=tbl_storage_engine]');
  2986. });
  2987. /**
  2988. * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
  2989. * the page loads and when the selected data type changes
  2990. */
  2991. AJAX.registerOnload('functions.js', function () {
  2992. // is called here for normal page loads and also when opening
  2993. // the Create table dialog
  2994. PMA_verifyColumnsProperties();
  2995. //
  2996. // needs on() to work also in the Create Table dialog
  2997. $(document).on('change', 'select.column_type', function () {
  2998. PMA_showNoticeForEnum($(this));
  2999. });
  3000. $(document).on('change', 'select.default_type', function () {
  3001. PMA_hideShowDefaultValue($(this));
  3002. });
  3003. $(document).on('change', 'select.virtuality', function () {
  3004. PMA_hideShowExpression($(this));
  3005. });
  3006. $(document).on('change', 'input.allow_null', function () {
  3007. PMA_validateDefaultValue($(this));
  3008. });
  3009. $(document).on('change', '.create_table_form select[name=tbl_storage_engine]', function () {
  3010. PMA_hideShowConnection($(this));
  3011. });
  3012. });
  3013. /**
  3014. * If the chosen storage engine is FEDERATED show connection field. Hide otherwise
  3015. *
  3016. * @param $engine_selector storage engine selector
  3017. */
  3018. function PMA_hideShowConnection ($engine_selector) {
  3019. var $connection = $('.create_table_form input[name=connection]');
  3020. var index = $connection.parent('td').index() + 1;
  3021. var $labelTh = $connection.parents('tr').prev('tr').children('th:nth-child(' + index + ')');
  3022. if ($engine_selector.val() !== 'FEDERATED') {
  3023. $connection
  3024. .prop('disabled', true)
  3025. .parent('td').hide();
  3026. $labelTh.hide();
  3027. } else {
  3028. $connection
  3029. .prop('disabled', false)
  3030. .parent('td').show();
  3031. $labelTh.show();
  3032. }
  3033. }
  3034. /**
  3035. * If the column does not allow NULL values, makes sure that default is not NULL
  3036. */
  3037. function PMA_validateDefaultValue ($null_checkbox) {
  3038. if (! $null_checkbox.prop('checked')) {
  3039. var $default = $null_checkbox.closest('tr').find('.default_type');
  3040. if ($default.val() === 'NULL') {
  3041. $default.val('NONE');
  3042. }
  3043. }
  3044. }
  3045. /**
  3046. * function to populate the input fields on picking a column from central list
  3047. *
  3048. * @param string input_id input id of the name field for the column to be populated
  3049. * @param integer offset of the selected column in central list of columns
  3050. */
  3051. function autoPopulate (input_id, offset) {
  3052. var db = PMA_commonParams.get('db');
  3053. var table = PMA_commonParams.get('table');
  3054. input_id = input_id.substring(0, input_id.length - 1);
  3055. $('#' + input_id + '1').val(central_column_list[db + '_' + table][offset].col_name);
  3056. var col_type = central_column_list[db + '_' + table][offset].col_type.toUpperCase();
  3057. $('#' + input_id + '2').val(col_type);
  3058. var $input3 = $('#' + input_id + '3');
  3059. $input3.val(central_column_list[db + '_' + table][offset].col_length);
  3060. if (col_type === 'ENUM' || col_type === 'SET') {
  3061. $input3.next().show();
  3062. } else {
  3063. $input3.next().hide();
  3064. }
  3065. var col_default = central_column_list[db + '_' + table][offset].col_default.toUpperCase();
  3066. var $input4 = $('#' + input_id + '4');
  3067. if (col_default !== '' && col_default !== 'NULL' && col_default !== 'CURRENT_TIMESTAMP' && col_default !== 'CURRENT_TIMESTAMP()') {
  3068. $input4.val('USER_DEFINED');
  3069. $input4.next().next().show();
  3070. $input4.next().next().val(central_column_list[db + '_' + table][offset].col_default);
  3071. } else {
  3072. $input4.val(central_column_list[db + '_' + table][offset].col_default);
  3073. $input4.next().next().hide();
  3074. }
  3075. $('#' + input_id + '5').val(central_column_list[db + '_' + table][offset].col_collation);
  3076. var $input6 = $('#' + input_id + '6');
  3077. $input6.val(central_column_list[db + '_' + table][offset].col_attribute);
  3078. if (central_column_list[db + '_' + table][offset].col_extra === 'on update CURRENT_TIMESTAMP') {
  3079. $input6.val(central_column_list[db + '_' + table][offset].col_extra);
  3080. }
  3081. if (central_column_list[db + '_' + table][offset].col_extra.toUpperCase() === 'AUTO_INCREMENT') {
  3082. $('#' + input_id + '9').prop('checked',true).change();
  3083. } else {
  3084. $('#' + input_id + '9').prop('checked',false);
  3085. }
  3086. if (central_column_list[db + '_' + table][offset].col_isNull !== '0') {
  3087. $('#' + input_id + '7').prop('checked',true);
  3088. } else {
  3089. $('#' + input_id + '7').prop('checked',false);
  3090. }
  3091. }
  3092. /**
  3093. * Unbind all event handlers before tearing down a page
  3094. */
  3095. AJAX.registerTeardown('functions.js', function () {
  3096. $(document).off('click', 'a.open_enum_editor');
  3097. $(document).off('click', 'input.add_value');
  3098. $(document).off('click', '#enum_editor td.drop');
  3099. $(document).off('click', 'a.central_columns_dialog');
  3100. });
  3101. /**
  3102. * @var $enum_editor_dialog An object that points to the jQuery
  3103. * dialog of the ENUM/SET editor
  3104. */
  3105. var $enum_editor_dialog = null;
  3106. /**
  3107. * Opens the ENUM/SET editor and controls its functions
  3108. */
  3109. AJAX.registerOnload('functions.js', function () {
  3110. $(document).on('click', 'a.open_enum_editor', function () {
  3111. // Get the name of the column that is being edited
  3112. var colname = $(this).closest('tr').find('input:first').val();
  3113. var title;
  3114. var i;
  3115. // And use it to make up a title for the page
  3116. if (colname.length < 1) {
  3117. title = PMA_messages.enum_newColumnVals;
  3118. } else {
  3119. title = PMA_messages.enum_columnVals.replace(
  3120. /%s/,
  3121. '"' + escapeHtml(decodeURIComponent(colname)) + '"'
  3122. );
  3123. }
  3124. // Get the values as a string
  3125. var inputstring = $(this)
  3126. .closest('td')
  3127. .find('input')
  3128. .val();
  3129. // Escape html entities
  3130. inputstring = $('<div/>')
  3131. .text(inputstring)
  3132. .html();
  3133. // Parse the values, escaping quotes and
  3134. // slashes on the fly, into an array
  3135. var values = [];
  3136. var in_string = false;
  3137. var curr;
  3138. var next;
  3139. var buffer = '';
  3140. for (i = 0; i < inputstring.length; i++) {
  3141. curr = inputstring.charAt(i);
  3142. next = i === inputstring.length ? '' : inputstring.charAt(i + 1);
  3143. if (! in_string && curr === '\'') {
  3144. in_string = true;
  3145. } else if (in_string && curr === '\\' && next === '\\') {
  3146. buffer += '&#92;';
  3147. i++;
  3148. } else if (in_string && next === '\'' && (curr === '\'' || curr === '\\')) {
  3149. buffer += '&#39;';
  3150. i++;
  3151. } else if (in_string && curr === '\'') {
  3152. in_string = false;
  3153. values.push(buffer);
  3154. buffer = '';
  3155. } else if (in_string) {
  3156. buffer += curr;
  3157. }
  3158. }
  3159. if (buffer.length > 0) {
  3160. // The leftovers in the buffer are the last value (if any)
  3161. values.push(buffer);
  3162. }
  3163. var fields = '';
  3164. // If there are no values, maybe the user is about to make a
  3165. // new list so we add a few for him/her to get started with.
  3166. if (values.length === 0) {
  3167. values.push('', '', '', '');
  3168. }
  3169. // Add the parsed values to the editor
  3170. var drop_icon = PMA_getImage('b_drop');
  3171. for (i = 0; i < values.length; i++) {
  3172. fields += '<tr><td>' +
  3173. '<input type=\'text\' value=\'' + values[i] + '\'/>' +
  3174. '</td><td class=\'drop\'>' +
  3175. drop_icon +
  3176. '</td></tr>';
  3177. }
  3178. /**
  3179. * @var dialog HTML code for the ENUM/SET dialog
  3180. */
  3181. var dialog = '<div id=\'enum_editor\'>' +
  3182. '<fieldset>' +
  3183. '<legend>' + title + '</legend>' +
  3184. '<p>' + PMA_getImage('s_notice') +
  3185. PMA_messages.enum_hint + '</p>' +
  3186. '<table class=\'values\'>' + fields + '</table>' +
  3187. '</fieldset><fieldset class=\'tblFooters\'>' +
  3188. '<table class=\'add\'><tr><td>' +
  3189. '<div class=\'slider\'></div>' +
  3190. '</td><td>' +
  3191. '<form><div><input type=\'submit\' class=\'add_value\' value=\'' +
  3192. PMA_sprintf(PMA_messages.enum_addValue, 1) +
  3193. '\'/></div></form>' +
  3194. '</td></tr></table>' +
  3195. '<input type=\'hidden\' value=\'' + // So we know which column's data is being edited
  3196. $(this).closest('td').find('input').attr('id') +
  3197. '\' />' +
  3198. '</fieldset>' +
  3199. '</div>';
  3200. /**
  3201. * @var Defines functions to be called when the buttons in
  3202. * the buttonOptions jQuery dialog bar are pressed
  3203. */
  3204. var buttonOptions = {};
  3205. buttonOptions[PMA_messages.strGo] = function () {
  3206. // When the submit button is clicked,
  3207. // put the data back into the original form
  3208. var value_array = [];
  3209. $(this).find('.values input').each(function (index, elm) {
  3210. var val = elm.value.replace(/\\/g, '\\\\').replace(/'/g, '\'\'');
  3211. value_array.push('\'' + val + '\'');
  3212. });
  3213. // get the Length/Values text field where this value belongs
  3214. var values_id = $(this).find('input[type=\'hidden\']').val();
  3215. $('input#' + values_id).val(value_array.join(','));
  3216. $(this).dialog('close');
  3217. };
  3218. buttonOptions[PMA_messages.strClose] = function () {
  3219. $(this).dialog('close');
  3220. };
  3221. // Show the dialog
  3222. var width = parseInt(
  3223. (parseInt($('html').css('font-size'), 10) / 13) * 340,
  3224. 10
  3225. );
  3226. if (! width) {
  3227. width = 340;
  3228. }
  3229. $enum_editor_dialog = $(dialog).dialog({
  3230. minWidth: width,
  3231. maxHeight: 450,
  3232. modal: true,
  3233. title: PMA_messages.enum_editor,
  3234. buttons: buttonOptions,
  3235. open: function () {
  3236. // Focus the "Go" button after opening the dialog
  3237. $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button:first').focus();
  3238. },
  3239. close: function () {
  3240. $(this).remove();
  3241. }
  3242. });
  3243. // slider for choosing how many fields to add
  3244. $enum_editor_dialog.find('.slider').slider({
  3245. animate: true,
  3246. range: 'min',
  3247. value: 1,
  3248. min: 1,
  3249. max: 9,
  3250. slide: function (event, ui) {
  3251. $(this).closest('table').find('input[type=submit]').val(
  3252. PMA_sprintf(PMA_messages.enum_addValue, ui.value)
  3253. );
  3254. }
  3255. });
  3256. // Focus the slider, otherwise it looks nearly transparent
  3257. $('a.ui-slider-handle').addClass('ui-state-focus');
  3258. return false;
  3259. });
  3260. $(document).on('click', 'a.central_columns_dialog', function (e) {
  3261. var href = 'db_central_columns.php';
  3262. var db = PMA_commonParams.get('db');
  3263. var table = PMA_commonParams.get('table');
  3264. var maxRows = $(this).data('maxrows');
  3265. var pick = $(this).data('pick');
  3266. if (pick !== false) {
  3267. pick = true;
  3268. }
  3269. var params = {
  3270. 'ajax_request' : true,
  3271. 'server' : PMA_commonParams.get('server'),
  3272. 'db' : PMA_commonParams.get('db'),
  3273. 'cur_table' : PMA_commonParams.get('table'),
  3274. 'getColumnList':true
  3275. };
  3276. var colid = $(this).closest('td').find('input').attr('id');
  3277. var fields = '';
  3278. if (! (db + '_' + table in central_column_list)) {
  3279. central_column_list.push(db + '_' + table);
  3280. $.ajax({
  3281. type: 'POST',
  3282. url: href,
  3283. data: params,
  3284. success: function (data) {
  3285. central_column_list[db + '_' + table] = JSON.parse(data.message);
  3286. },
  3287. async:false
  3288. });
  3289. }
  3290. var i = 0;
  3291. var list_size = central_column_list[db + '_' + table].length;
  3292. var min = (list_size <= maxRows) ? list_size : maxRows;
  3293. for (i = 0; i < min; i++) {
  3294. fields += '<tr><td><div><span class="font_weight_bold">' +
  3295. escapeHtml(central_column_list[db + '_' + table][i].col_name) +
  3296. '</span><br><span class="color_gray">' + central_column_list[db + '_' + table][i].col_type;
  3297. if (central_column_list[db + '_' + table][i].col_attribute !== '') {
  3298. fields += '(' + escapeHtml(central_column_list[db + '_' + table][i].col_attribute) + ') ';
  3299. }
  3300. if (central_column_list[db + '_' + table][i].col_length !== '') {
  3301. fields += '(' + escapeHtml(central_column_list[db + '_' + table][i].col_length) + ') ';
  3302. }
  3303. fields += escapeHtml(central_column_list[db + '_' + table][i].col_extra) + '</span>' +
  3304. '</div></td>';
  3305. if (pick) {
  3306. fields += '<td><input class="pick all100" type="submit" value="' +
  3307. PMA_messages.pickColumn + '" onclick="autoPopulate(\'' + colid + '\',' + i + ')"/></td>';
  3308. }
  3309. fields += '</tr>';
  3310. }
  3311. var result_pointer = i;
  3312. var search_in = '<input type="text" class="filter_rows" placeholder="' + PMA_messages.searchList + '">';
  3313. if (fields === '') {
  3314. fields = PMA_sprintf(PMA_messages.strEmptyCentralList, '\'' + escapeHtml(db) + '\'');
  3315. search_in = '';
  3316. }
  3317. var seeMore = '';
  3318. if (list_size > maxRows) {
  3319. seeMore = '<fieldset class=\'tblFooters center\' style=\'font-weight:bold\'>' +
  3320. '<a href=\'#\' id=\'seeMore\'>' + PMA_messages.seeMore + '</a></fieldset>';
  3321. }
  3322. var central_columns_dialog = '<div style=\'max-height:400px\'>' +
  3323. '<fieldset>' +
  3324. search_in +
  3325. '<table id=\'col_list\' style=\'width:100%\' class=\'values\'>' + fields + '</table>' +
  3326. '</fieldset>' +
  3327. seeMore +
  3328. '</div>';
  3329. var width = parseInt(
  3330. (parseInt($('html').css('font-size'), 10) / 13) * 500,
  3331. 10
  3332. );
  3333. if (! width) {
  3334. width = 500;
  3335. }
  3336. var buttonOptions = {};
  3337. var $central_columns_dialog = $(central_columns_dialog).dialog({
  3338. minWidth: width,
  3339. maxHeight: 450,
  3340. modal: true,
  3341. title: PMA_messages.pickColumnTitle,
  3342. buttons: buttonOptions,
  3343. open: function () {
  3344. $('#col_list').on('click', '.pick', function () {
  3345. $central_columns_dialog.remove();
  3346. });
  3347. $('.filter_rows').on('keyup', function () {
  3348. $.uiTableFilter($('#col_list'), $(this).val());
  3349. });
  3350. $('#seeMore').click(function () {
  3351. fields = '';
  3352. min = (list_size <= maxRows + result_pointer) ? list_size : maxRows + result_pointer;
  3353. for (i = result_pointer; i < min; i++) {
  3354. fields += '<tr><td><div><span class="font_weight_bold">' +
  3355. central_column_list[db + '_' + table][i].col_name +
  3356. '</span><br><span class="color_gray">' +
  3357. central_column_list[db + '_' + table][i].col_type;
  3358. if (central_column_list[db + '_' + table][i].col_attribute !== '') {
  3359. fields += '(' + central_column_list[db + '_' + table][i].col_attribute + ') ';
  3360. }
  3361. if (central_column_list[db + '_' + table][i].col_length !== '') {
  3362. fields += '(' + central_column_list[db + '_' + table][i].col_length + ') ';
  3363. }
  3364. fields += central_column_list[db + '_' + table][i].col_extra + '</span>' +
  3365. '</div></td>';
  3366. if (pick) {
  3367. fields += '<td><input class="pick all100" type="submit" value="' +
  3368. PMA_messages.pickColumn + '" onclick="autoPopulate(\'' + colid + '\',' + i + ')"/></td>';
  3369. }
  3370. fields += '</tr>';
  3371. }
  3372. $('#col_list').append(fields);
  3373. result_pointer = i;
  3374. if (result_pointer === list_size) {
  3375. $('.tblFooters').hide();
  3376. }
  3377. return false;
  3378. });
  3379. $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button:first').focus();
  3380. },
  3381. close: function () {
  3382. $('#col_list').off('click', '.pick');
  3383. $('.filter_rows').off('keyup');
  3384. $(this).remove();
  3385. }
  3386. });
  3387. return false;
  3388. });
  3389. // $(document).on('click', 'a.show_central_list',function(e) {
  3390. // });
  3391. // When "add a new value" is clicked, append an empty text field
  3392. $(document).on('click', 'input.add_value', function (e) {
  3393. e.preventDefault();
  3394. var num_new_rows = $enum_editor_dialog.find('div.slider').slider('value');
  3395. while (num_new_rows--) {
  3396. $enum_editor_dialog.find('.values')
  3397. .append(
  3398. '<tr class=\'hide\'><td>' +
  3399. '<input type=\'text\' />' +
  3400. '</td><td class=\'drop\'>' +
  3401. PMA_getImage('b_drop') +
  3402. '</td></tr>'
  3403. )
  3404. .find('tr:last')
  3405. .show('fast');
  3406. }
  3407. });
  3408. // Removes the specified row from the enum editor
  3409. $(document).on('click', '#enum_editor td.drop', function () {
  3410. $(this).closest('tr').hide('fast', function () {
  3411. $(this).remove();
  3412. });
  3413. });
  3414. });
  3415. /**
  3416. * Ensures indexes names are valid according to their type and, for a primary
  3417. * key, lock index name to 'PRIMARY'
  3418. * @param string form_id Variable which parses the form name as
  3419. * the input
  3420. * @return boolean false if there is no index form, true else
  3421. */
  3422. function checkIndexName (form_id) {
  3423. if ($('#' + form_id).length === 0) {
  3424. return false;
  3425. }
  3426. // Gets the elements pointers
  3427. var $the_idx_name = $('#input_index_name');
  3428. var $the_idx_choice = $('#select_index_choice');
  3429. // Index is a primary key
  3430. if ($the_idx_choice.find('option:selected').val() === 'PRIMARY') {
  3431. $the_idx_name.val('PRIMARY');
  3432. $the_idx_name.prop('disabled', true);
  3433. } else {
  3434. if ($the_idx_name.val() === 'PRIMARY') {
  3435. $the_idx_name.val('');
  3436. }
  3437. $the_idx_name.prop('disabled', false);
  3438. }
  3439. return true;
  3440. } // end of the 'checkIndexName()' function
  3441. AJAX.registerTeardown('functions.js', function () {
  3442. $(document).off('click', '#index_frm input[type=submit]');
  3443. });
  3444. AJAX.registerOnload('functions.js', function () {
  3445. /**
  3446. * Handler for adding more columns to an index in the editor
  3447. */
  3448. $(document).on('click', '#index_frm input[type=submit]', function (event) {
  3449. event.preventDefault();
  3450. var rows_to_add = $(this)
  3451. .closest('fieldset')
  3452. .find('.slider')
  3453. .slider('value');
  3454. var tempEmptyVal = function () {
  3455. $(this).val('');
  3456. };
  3457. var tempSetFocus = function () {
  3458. if ($(this).find('option:selected').val() === '') {
  3459. return true;
  3460. }
  3461. $(this).closest('tr').find('input').focus();
  3462. };
  3463. while (rows_to_add--) {
  3464. var $indexColumns = $('#index_columns');
  3465. var $newrow = $indexColumns
  3466. .find('tbody > tr:first')
  3467. .clone()
  3468. .appendTo(
  3469. $indexColumns.find('tbody')
  3470. );
  3471. $newrow.find(':input').each(tempEmptyVal);
  3472. // focus index size input on column picked
  3473. $newrow.find('select').change(tempSetFocus);
  3474. }
  3475. });
  3476. });
  3477. function indexEditorDialog (url, title, callback_success, callback_failure) {
  3478. /* Remove the hidden dialogs if there are*/
  3479. var $editIndexDialog = $('#edit_index_dialog');
  3480. if ($editIndexDialog.length !== 0) {
  3481. $editIndexDialog.remove();
  3482. }
  3483. var $div = $('<div id="edit_index_dialog"></div>');
  3484. /**
  3485. * @var button_options Object that stores the options
  3486. * passed to jQueryUI dialog
  3487. */
  3488. var button_options = {};
  3489. button_options[PMA_messages.strGo] = function () {
  3490. /**
  3491. * @var the_form object referring to the export form
  3492. */
  3493. var $form = $('#index_frm');
  3494. var $msgbox = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
  3495. PMA_prepareForAjaxRequest($form);
  3496. // User wants to submit the form
  3497. $.post($form.attr('action'), $form.serialize() + PMA_commonParams.get('arg_separator') + 'do_save_data=1', function (data) {
  3498. var $sqlqueryresults = $('.sqlqueryresults');
  3499. if ($sqlqueryresults.length !== 0) {
  3500. $sqlqueryresults.remove();
  3501. }
  3502. if (typeof data !== 'undefined' && data.success === true) {
  3503. PMA_ajaxShowMessage(data.message);
  3504. var $resultQuery = $('.result_query');
  3505. if ($resultQuery.length) {
  3506. $resultQuery.remove();
  3507. }
  3508. if (data.sql_query) {
  3509. $('<div class="result_query"></div>')
  3510. .html(data.sql_query)
  3511. .prependTo('#page_content');
  3512. PMA_highlightSQL($('#page_content'));
  3513. }
  3514. $('.result_query .notice').remove();
  3515. $resultQuery.prepend(data.message);
  3516. /* Reload the field form*/
  3517. $('#table_index').remove();
  3518. $('<div id=\'temp_div\'><div>')
  3519. .append(data.index_table)
  3520. .find('#table_index')
  3521. .insertAfter('#index_header');
  3522. var $editIndexDialog = $('#edit_index_dialog');
  3523. if ($editIndexDialog.length > 0) {
  3524. $editIndexDialog.dialog('close');
  3525. }
  3526. $('div.no_indexes_defined').hide();
  3527. if (callback_success) {
  3528. callback_success();
  3529. }
  3530. PMA_reloadNavigation();
  3531. } else {
  3532. var $temp_div = $('<div id=\'temp_div\'><div>').append(data.error);
  3533. var $error;
  3534. if ($temp_div.find('.error code').length !== 0) {
  3535. $error = $temp_div.find('.error code').addClass('error');
  3536. } else {
  3537. $error = $temp_div;
  3538. }
  3539. if (callback_failure) {
  3540. callback_failure();
  3541. }
  3542. PMA_ajaxShowMessage($error, false);
  3543. }
  3544. }); // end $.post()
  3545. };
  3546. button_options[PMA_messages.strPreviewSQL] = function () {
  3547. // Function for Previewing SQL
  3548. var $form = $('#index_frm');
  3549. PMA_previewSQL($form);
  3550. };
  3551. button_options[PMA_messages.strCancel] = function () {
  3552. $(this).dialog('close');
  3553. };
  3554. var $msgbox = PMA_ajaxShowMessage();
  3555. $.post('tbl_indexes.php', url, function (data) {
  3556. if (typeof data !== 'undefined' && data.success === false) {
  3557. // in the case of an error, show the error message returned.
  3558. PMA_ajaxShowMessage(data.error, false);
  3559. } else {
  3560. PMA_ajaxRemoveMessage($msgbox);
  3561. // Show dialog if the request was successful
  3562. $div
  3563. .append(data.message)
  3564. .dialog({
  3565. title: title,
  3566. width: 'auto',
  3567. open: PMA_verifyColumnsProperties,
  3568. modal: true,
  3569. buttons: button_options,
  3570. close: function () {
  3571. $(this).remove();
  3572. }
  3573. });
  3574. $div.find('.tblFooters').remove();
  3575. showIndexEditDialog($div);
  3576. }
  3577. }); // end $.get()
  3578. }
  3579. function showIndexEditDialog ($outer) {
  3580. checkIndexType();
  3581. checkIndexName('index_frm');
  3582. var $indexColumns = $('#index_columns');
  3583. $indexColumns.find('td').each(function () {
  3584. $(this).css('width', $(this).width() + 'px');
  3585. });
  3586. $indexColumns.find('tbody').sortable({
  3587. axis: 'y',
  3588. containment: $indexColumns.find('tbody'),
  3589. tolerance: 'pointer'
  3590. });
  3591. PMA_showHints($outer);
  3592. PMA_init_slider();
  3593. // Add a slider for selecting how many columns to add to the index
  3594. $outer.find('.slider').slider({
  3595. animate: true,
  3596. value: 1,
  3597. min: 1,
  3598. max: 16,
  3599. slide: function (event, ui) {
  3600. $(this).closest('fieldset').find('input[type=submit]').val(
  3601. PMA_sprintf(PMA_messages.strAddToIndex, ui.value)
  3602. );
  3603. }
  3604. });
  3605. $('div.add_fields').removeClass('hide');
  3606. // focus index size input on column picked
  3607. $outer.find('table#index_columns select').change(function () {
  3608. if ($(this).find('option:selected').val() === '') {
  3609. return true;
  3610. }
  3611. $(this).closest('tr').find('input').focus();
  3612. });
  3613. // Focus the slider, otherwise it looks nearly transparent
  3614. $('a.ui-slider-handle').addClass('ui-state-focus');
  3615. // set focus on index name input, if empty
  3616. var input = $outer.find('input#input_index_name');
  3617. if (! input.val()) {
  3618. input.focus();
  3619. }
  3620. }
  3621. /**
  3622. * Function to display tooltips that were
  3623. * generated on the PHP side by PhpMyAdmin\Util::showHint()
  3624. *
  3625. * @param object $div a div jquery object which specifies the
  3626. * domain for searching for tooltips. If we
  3627. * omit this parameter the function searches
  3628. * in the whole body
  3629. **/
  3630. function PMA_showHints ($div) {
  3631. if ($div === undefined || ! $div instanceof jQuery || $div.length === 0) {
  3632. $div = $('body');
  3633. }
  3634. $div.find('.pma_hint').each(function () {
  3635. PMA_tooltip(
  3636. $(this).children('img'),
  3637. 'img',
  3638. $(this).children('span').html()
  3639. );
  3640. });
  3641. }
  3642. AJAX.registerOnload('functions.js', function () {
  3643. PMA_showHints();
  3644. });
  3645. function PMA_mainMenuResizerCallback () {
  3646. // 5 px margin for jumping menu in Chrome
  3647. return $(document.body).width() - 5;
  3648. }
  3649. // This must be fired only once after the initial page load
  3650. $(function () {
  3651. // Initialise the menu resize plugin
  3652. $('#topmenu').menuResizer(PMA_mainMenuResizerCallback);
  3653. // register resize event
  3654. $(window).on('resize', function () {
  3655. $('#topmenu').menuResizer('resize');
  3656. });
  3657. });
  3658. /**
  3659. * Get the row number from the classlist (for example, row_1)
  3660. */
  3661. function PMA_getRowNumber (classlist) {
  3662. return parseInt(classlist.split(/\s+row_/)[1], 10);
  3663. }
  3664. /**
  3665. * Changes status of slider
  3666. */
  3667. function PMA_set_status_label ($element) {
  3668. var text;
  3669. if ($element.css('display') === 'none') {
  3670. text = '+ ';
  3671. } else {
  3672. text = '- ';
  3673. }
  3674. $element.closest('.slide-wrapper').prev().find('span').text(text);
  3675. }
  3676. /**
  3677. * var toggleButton This is a function that creates a toggle
  3678. * sliding button given a jQuery reference
  3679. * to the correct DOM element
  3680. */
  3681. var toggleButton = function ($obj) {
  3682. // In rtl mode the toggle switch is flipped horizontally
  3683. // so we need to take that into account
  3684. var right;
  3685. if ($('span.text_direction', $obj).text() === 'ltr') {
  3686. right = 'right';
  3687. } else {
  3688. right = 'left';
  3689. }
  3690. /**
  3691. * var h Height of the button, used to scale the
  3692. * background image and position the layers
  3693. */
  3694. var h = $obj.height();
  3695. $('img', $obj).height(h);
  3696. $('table', $obj).css('bottom', h - 1);
  3697. /**
  3698. * var on Width of the "ON" part of the toggle switch
  3699. * var off Width of the "OFF" part of the toggle switch
  3700. */
  3701. var on = $('td.toggleOn', $obj).width();
  3702. var off = $('td.toggleOff', $obj).width();
  3703. // Make the "ON" and "OFF" parts of the switch the same size
  3704. // + 2 pixels to avoid overflowed
  3705. $('td.toggleOn > div', $obj).width(Math.max(on, off) + 2);
  3706. $('td.toggleOff > div', $obj).width(Math.max(on, off) + 2);
  3707. /**
  3708. * var w Width of the central part of the switch
  3709. */
  3710. var w = parseInt(($('img', $obj).height() / 16) * 22, 10);
  3711. // Resize the central part of the switch on the top
  3712. // layer to match the background
  3713. $('table td:nth-child(2) > div', $obj).width(w);
  3714. /**
  3715. * var imgw Width of the background image
  3716. * var tblw Width of the foreground layer
  3717. * var offset By how many pixels to move the background
  3718. * image, so that it matches the top layer
  3719. */
  3720. var imgw = $('img', $obj).width();
  3721. var tblw = $('table', $obj).width();
  3722. var offset = parseInt(((imgw - tblw) / 2), 10);
  3723. // Move the background to match the layout of the top layer
  3724. $obj.find('img').css(right, offset);
  3725. /**
  3726. * var offw Outer width of the "ON" part of the toggle switch
  3727. * var btnw Outer width of the central part of the switch
  3728. */
  3729. var offw = $('td.toggleOff', $obj).outerWidth();
  3730. var btnw = $('table td:nth-child(2)', $obj).outerWidth();
  3731. // Resize the main div so that exactly one side of
  3732. // the switch plus the central part fit into it.
  3733. $obj.width(offw + btnw + 2);
  3734. /**
  3735. * var move How many pixels to move the
  3736. * switch by when toggling
  3737. */
  3738. var move = $('td.toggleOff', $obj).outerWidth();
  3739. // If the switch is initialized to the
  3740. // OFF state we need to move it now.
  3741. if ($('div.container', $obj).hasClass('off')) {
  3742. if (right === 'right') {
  3743. $('div.container', $obj).animate({ 'left': '-=' + move + 'px' }, 0);
  3744. } else {
  3745. $('div.container', $obj).animate({ 'left': '+=' + move + 'px' }, 0);
  3746. }
  3747. }
  3748. // Attach an 'onclick' event to the switch
  3749. $('div.container', $obj).click(function () {
  3750. if ($(this).hasClass('isActive')) {
  3751. return false;
  3752. } else {
  3753. $(this).addClass('isActive');
  3754. }
  3755. var $msg = PMA_ajaxShowMessage();
  3756. var $container = $(this);
  3757. var callback = $('span.callback', this).text();
  3758. var operator;
  3759. var url;
  3760. var removeClass;
  3761. var addClass;
  3762. // Perform the actual toggle
  3763. if ($(this).hasClass('on')) {
  3764. if (right === 'right') {
  3765. operator = '-=';
  3766. } else {
  3767. operator = '+=';
  3768. }
  3769. url = $(this).find('td.toggleOff > span').text();
  3770. removeClass = 'on';
  3771. addClass = 'off';
  3772. } else {
  3773. if (right === 'right') {
  3774. operator = '+=';
  3775. } else {
  3776. operator = '-=';
  3777. }
  3778. url = $(this).find('td.toggleOn > span').text();
  3779. removeClass = 'off';
  3780. addClass = 'on';
  3781. }
  3782. var parts = url.split('?');
  3783. $.post(parts[0], parts[1] + '&ajax_request=true', function (data) {
  3784. if (typeof data !== 'undefined' && data.success === true) {
  3785. PMA_ajaxRemoveMessage($msg);
  3786. $container
  3787. .removeClass(removeClass)
  3788. .addClass(addClass)
  3789. .animate({ 'left': operator + move + 'px' }, function () {
  3790. $container.removeClass('isActive');
  3791. });
  3792. eval(callback);
  3793. } else {
  3794. PMA_ajaxShowMessage(data.error, false);
  3795. $container.removeClass('isActive');
  3796. }
  3797. });
  3798. });
  3799. };
  3800. /**
  3801. * Unbind all event handlers before tearing down a page
  3802. */
  3803. AJAX.registerTeardown('functions.js', function () {
  3804. $('div.container').off('click');
  3805. });
  3806. /**
  3807. * Initialise all toggle buttons
  3808. */
  3809. AJAX.registerOnload('functions.js', function () {
  3810. $('div.toggleAjax').each(function () {
  3811. var $button = $(this).show();
  3812. $button.find('img').each(function () {
  3813. if (this.complete) {
  3814. toggleButton($button);
  3815. } else {
  3816. $(this).load(function () {
  3817. toggleButton($button);
  3818. });
  3819. }
  3820. });
  3821. });
  3822. });
  3823. /**
  3824. * Unbind all event handlers before tearing down a page
  3825. */
  3826. AJAX.registerTeardown('functions.js', function () {
  3827. $(document).off('change', 'select.pageselector');
  3828. $('#update_recent_tables').off('ready');
  3829. $('#sync_favorite_tables').off('ready');
  3830. });
  3831. AJAX.registerOnload('functions.js', function () {
  3832. /**
  3833. * Autosubmit page selector
  3834. */
  3835. $(document).on('change', 'select.pageselector', function (event) {
  3836. event.stopPropagation();
  3837. // Check where to load the new content
  3838. if ($(this).closest('#pma_navigation').length === 0) {
  3839. // For the main page we don't need to do anything,
  3840. $(this).closest('form').submit();
  3841. } else {
  3842. // but for the navigation we need to manually replace the content
  3843. PMA_navigationTreePagination($(this));
  3844. }
  3845. });
  3846. /**
  3847. * Load version information asynchronously.
  3848. */
  3849. if ($('li.jsversioncheck').length > 0) {
  3850. $.ajax({
  3851. dataType: 'json',
  3852. url: 'version_check.php',
  3853. method: 'POST',
  3854. data: {
  3855. 'server': PMA_commonParams.get('server')
  3856. },
  3857. success: PMA_current_version
  3858. });
  3859. }
  3860. if ($('#is_git_revision').length > 0) {
  3861. setTimeout(PMA_display_git_revision, 10);
  3862. }
  3863. /**
  3864. * Slider effect.
  3865. */
  3866. PMA_init_slider();
  3867. var $updateRecentTables = $('#update_recent_tables');
  3868. if ($updateRecentTables.length) {
  3869. $.get(
  3870. $updateRecentTables.attr('href'),
  3871. { no_debug: true },
  3872. function (data) {
  3873. if (typeof data !== 'undefined' && data.success === true) {
  3874. $('#pma_recent_list').html(data.list);
  3875. }
  3876. }
  3877. );
  3878. }
  3879. // Sync favorite tables from localStorage to pmadb.
  3880. if ($('#sync_favorite_tables').length) {
  3881. $.ajax({
  3882. url: $('#sync_favorite_tables').attr('href'),
  3883. cache: false,
  3884. type: 'POST',
  3885. data: {
  3886. favorite_tables: (isStorageSupported('localStorage') && typeof window.localStorage.favorite_tables !== 'undefined')
  3887. ? window.localStorage.favorite_tables
  3888. : '',
  3889. server: PMA_commonParams.get('server'),
  3890. no_debug: true
  3891. },
  3892. success: function (data) {
  3893. // Update localStorage.
  3894. if (isStorageSupported('localStorage')) {
  3895. window.localStorage.favorite_tables = data.favorite_tables;
  3896. }
  3897. $('#pma_favorite_list').html(data.list);
  3898. }
  3899. });
  3900. }
  3901. }); // end of $()
  3902. /**
  3903. * Submits the form placed in place of a link due to the excessive url length
  3904. *
  3905. * @param $link anchor
  3906. * @returns {Boolean}
  3907. */
  3908. function submitFormLink ($link) {
  3909. if ($link.attr('href').indexOf('=') !== -1) {
  3910. var data = $link.attr('href').substr($link.attr('href').indexOf('#') + 1).split('=', 2);
  3911. $link.parents('form').append('<input type="hidden" name="' + data[0] + '" value="' + data[1] + '"/>');
  3912. }
  3913. $link.parents('form').submit();
  3914. }
  3915. /**
  3916. * Initializes slider effect.
  3917. */
  3918. function PMA_init_slider () {
  3919. $('div.pma_auto_slider').each(function () {
  3920. var $this = $(this);
  3921. if ($this.data('slider_init_done')) {
  3922. return;
  3923. }
  3924. var $wrapper = $('<div>', { 'class': 'slide-wrapper' });
  3925. $wrapper.toggle($this.is(':visible'));
  3926. $('<a>', { href: '#' + this.id, 'class': 'ajax' })
  3927. .text($this.attr('title'))
  3928. .prepend($('<span>'))
  3929. .insertBefore($this)
  3930. .click(function () {
  3931. var $wrapper = $this.closest('.slide-wrapper');
  3932. var visible = $this.is(':visible');
  3933. if (!visible) {
  3934. $wrapper.show();
  3935. }
  3936. $this[visible ? 'hide' : 'show']('blind', function () {
  3937. $wrapper.toggle(!visible);
  3938. $wrapper.parent().toggleClass('print_ignore', visible);
  3939. PMA_set_status_label($this);
  3940. });
  3941. return false;
  3942. });
  3943. $this.wrap($wrapper);
  3944. $this.removeAttr('title');
  3945. PMA_set_status_label($this);
  3946. $this.data('slider_init_done', 1);
  3947. });
  3948. }
  3949. /**
  3950. * Initializes slider effect.
  3951. */
  3952. AJAX.registerOnload('functions.js', function () {
  3953. PMA_init_slider();
  3954. });
  3955. /**
  3956. * Restores sliders to the state they were in before initialisation.
  3957. */
  3958. AJAX.registerTeardown('functions.js', function () {
  3959. $('div.pma_auto_slider').each(function () {
  3960. var $this = $(this);
  3961. $this.removeData();
  3962. $this.parent().replaceWith($this);
  3963. $this.parent().children('a').remove();
  3964. });
  3965. });
  3966. /**
  3967. * Creates a message inside an object with a sliding effect
  3968. *
  3969. * @param msg A string containing the text to display
  3970. * @param $obj a jQuery object containing the reference
  3971. * to the element where to put the message
  3972. * This is optional, if no element is
  3973. * provided, one will be created below the
  3974. * navigation links at the top of the page
  3975. *
  3976. * @return bool True on success, false on failure
  3977. */
  3978. function PMA_slidingMessage (msg, $obj) {
  3979. if (msg === undefined || msg.length === 0) {
  3980. // Don't show an empty message
  3981. return false;
  3982. }
  3983. if ($obj === undefined || ! $obj instanceof jQuery || $obj.length === 0) {
  3984. // If the second argument was not supplied,
  3985. // we might have to create a new DOM node.
  3986. if ($('#PMA_slidingMessage').length === 0) {
  3987. $('#page_content').prepend(
  3988. '<span id="PMA_slidingMessage" ' +
  3989. 'class="pma_sliding_message"></span>'
  3990. );
  3991. }
  3992. $obj = $('#PMA_slidingMessage');
  3993. }
  3994. if ($obj.has('div').length > 0) {
  3995. // If there already is a message inside the
  3996. // target object, we must get rid of it
  3997. $obj
  3998. .find('div')
  3999. .first()
  4000. .fadeOut(function () {
  4001. $obj
  4002. .children()
  4003. .remove();
  4004. $obj
  4005. .append('<div>' + msg + '</div>');
  4006. // highlight any sql before taking height;
  4007. PMA_highlightSQL($obj);
  4008. $obj.find('div')
  4009. .first()
  4010. .hide();
  4011. $obj
  4012. .animate({
  4013. height: $obj.find('div').first().height()
  4014. })
  4015. .find('div')
  4016. .first()
  4017. .fadeIn();
  4018. });
  4019. } else {
  4020. // Object does not already have a message
  4021. // inside it, so we simply slide it down
  4022. $obj.width('100%')
  4023. .html('<div>' + msg + '</div>');
  4024. // highlight any sql before taking height;
  4025. PMA_highlightSQL($obj);
  4026. var h = $obj
  4027. .find('div')
  4028. .first()
  4029. .hide()
  4030. .height();
  4031. $obj
  4032. .find('div')
  4033. .first()
  4034. .css('height', 0)
  4035. .show()
  4036. .animate({
  4037. height: h
  4038. }, function () {
  4039. // Set the height of the parent
  4040. // to the height of the child
  4041. $obj
  4042. .height(
  4043. $obj
  4044. .find('div')
  4045. .first()
  4046. .height()
  4047. );
  4048. });
  4049. }
  4050. return true;
  4051. } // end PMA_slidingMessage()
  4052. /**
  4053. * Attach CodeMirror2 editor to SQL edit area.
  4054. */
  4055. AJAX.registerOnload('functions.js', function () {
  4056. var $elm = $('#sqlquery');
  4057. if ($elm.length > 0) {
  4058. if (typeof CodeMirror !== 'undefined') {
  4059. codemirror_editor = PMA_getSQLEditor($elm);
  4060. codemirror_editor.focus();
  4061. codemirror_editor.on('blur', updateQueryParameters);
  4062. } else {
  4063. // without codemirror
  4064. $elm.focus().on('blur', updateQueryParameters);
  4065. }
  4066. }
  4067. PMA_highlightSQL($('body'));
  4068. });
  4069. AJAX.registerTeardown('functions.js', function () {
  4070. if (codemirror_editor) {
  4071. $('#sqlquery').text(codemirror_editor.getValue());
  4072. codemirror_editor.toTextArea();
  4073. codemirror_editor = false;
  4074. }
  4075. });
  4076. AJAX.registerOnload('functions.js', function () {
  4077. // initializes all lock-page elements lock-id and
  4078. // val-hash data property
  4079. $('#page_content form.lock-page textarea, ' +
  4080. '#page_content form.lock-page input[type="text"], ' +
  4081. '#page_content form.lock-page input[type="number"], ' +
  4082. '#page_content form.lock-page select').each(function (i) {
  4083. $(this).data('lock-id', i);
  4084. // val-hash is the hash of default value of the field
  4085. // so that it can be compared with new value hash
  4086. // to check whether field was modified or not.
  4087. $(this).data('val-hash', AJAX.hash($(this).val()));
  4088. });
  4089. // initializes lock-page elements (input types checkbox and radio buttons)
  4090. // lock-id and val-hash data property
  4091. $('#page_content form.lock-page input[type="checkbox"], ' +
  4092. '#page_content form.lock-page input[type="radio"]').each(function (i) {
  4093. $(this).data('lock-id', i);
  4094. $(this).data('val-hash', AJAX.hash($(this).is(':checked')));
  4095. });
  4096. });
  4097. /**
  4098. * jQuery plugin to correctly filter input fields by value, needed
  4099. * because some nasty values may break selector syntax
  4100. */
  4101. (function ($) {
  4102. $.fn.filterByValue = function (value) {
  4103. return this.filter(function () {
  4104. return $(this).val() === value;
  4105. });
  4106. };
  4107. }(jQuery));
  4108. /**
  4109. * Return value of a cell in a table.
  4110. */
  4111. function PMA_getCellValue (td) {
  4112. var $td = $(td);
  4113. if ($td.is('.null')) {
  4114. return '';
  4115. } else if ((! $td.is('.to_be_saved')
  4116. || $td.is('.set'))
  4117. && $td.data('original_data')
  4118. ) {
  4119. return $td.data('original_data');
  4120. } else {
  4121. return $td.text();
  4122. }
  4123. }
  4124. $(window).on('popstate', function (event, data) {
  4125. $('#printcss').attr('media','print');
  4126. return true;
  4127. });
  4128. /**
  4129. * Unbind all event handlers before tearing down a page
  4130. */
  4131. AJAX.registerTeardown('functions.js', function () {
  4132. $(document).off('click', 'a.themeselect');
  4133. $(document).off('change', '.autosubmit');
  4134. $('a.take_theme').off('click');
  4135. });
  4136. AJAX.registerOnload('functions.js', function () {
  4137. /**
  4138. * Theme selector.
  4139. */
  4140. $(document).on('click', 'a.themeselect', function (e) {
  4141. window.open(
  4142. e.target,
  4143. 'themes',
  4144. 'left=10,top=20,width=510,height=350,scrollbars=yes,status=yes,resizable=yes'
  4145. );
  4146. return false;
  4147. });
  4148. /**
  4149. * Automatic form submission on change.
  4150. */
  4151. $(document).on('change', '.autosubmit', function (e) {
  4152. $(this).closest('form').submit();
  4153. });
  4154. /**
  4155. * Theme changer.
  4156. */
  4157. $('a.take_theme').click(function (e) {
  4158. var what = this.name;
  4159. if (window.opener && window.opener.document.forms.setTheme.elements.set_theme) {
  4160. window.opener.document.forms.setTheme.elements.set_theme.value = what;
  4161. window.opener.document.forms.setTheme.submit();
  4162. window.close();
  4163. return false;
  4164. }
  4165. return true;
  4166. });
  4167. });
  4168. /**
  4169. * Produce print preview
  4170. */
  4171. function printPreview () {
  4172. $('#printcss').attr('media','all');
  4173. createPrintAndBackButtons();
  4174. }
  4175. /**
  4176. * Create print and back buttons in preview page
  4177. */
  4178. function createPrintAndBackButtons () {
  4179. var back_button = $('<input/>',{
  4180. type: 'button',
  4181. value: PMA_messages.back,
  4182. id: 'back_button_print_view'
  4183. });
  4184. back_button.click(removePrintAndBackButton);
  4185. back_button.appendTo('#page_content');
  4186. var print_button = $('<input/>',{
  4187. type: 'button',
  4188. value: PMA_messages.print,
  4189. id: 'print_button_print_view'
  4190. });
  4191. print_button.click(printPage);
  4192. print_button.appendTo('#page_content');
  4193. }
  4194. /**
  4195. * Remove print and back buttons and revert to normal view
  4196. */
  4197. function removePrintAndBackButton () {
  4198. $('#printcss').attr('media','print');
  4199. $('#back_button_print_view').remove();
  4200. $('#print_button_print_view').remove();
  4201. }
  4202. /**
  4203. * Print page
  4204. */
  4205. function printPage () {
  4206. if (typeof(window.print) !== 'undefined') {
  4207. window.print();
  4208. }
  4209. }
  4210. /**
  4211. * Unbind all event handlers before tearing down a page
  4212. */
  4213. AJAX.registerTeardown('functions.js', function () {
  4214. $('input#print').off('click');
  4215. $(document).off('click', 'a.create_view.ajax');
  4216. $(document).off('keydown', '#createViewDialog input, #createViewDialog select');
  4217. $(document).off('change', '#fkc_checkbox');
  4218. });
  4219. AJAX.registerOnload('functions.js', function () {
  4220. $('input#print').click(printPage);
  4221. $('.logout').click(function () {
  4222. var form = $(
  4223. '<form method="POST" action="' + $(this).attr('href') + '" class="disableAjax">' +
  4224. '<input type="hidden" name="token" value="' + escapeHtml(PMA_commonParams.get('token')) + '"/>' +
  4225. '</form>'
  4226. );
  4227. $('body').append(form);
  4228. form.submit();
  4229. return false;
  4230. });
  4231. /**
  4232. * Ajaxification for the "Create View" action
  4233. */
  4234. $(document).on('click', 'a.create_view.ajax', function (e) {
  4235. e.preventDefault();
  4236. PMA_createViewDialog($(this));
  4237. });
  4238. /**
  4239. * Attach Ajax event handlers for input fields in the editor
  4240. * and used to submit the Ajax request when the ENTER key is pressed.
  4241. */
  4242. if ($('#createViewDialog').length !== 0) {
  4243. $(document).on('keydown', '#createViewDialog input, #createViewDialog select', function (e) {
  4244. if (e.which === 13) { // 13 is the ENTER key
  4245. e.preventDefault();
  4246. // with preventing default, selection by <select> tag
  4247. // was also prevented in IE
  4248. $(this).blur();
  4249. $(this).closest('.ui-dialog').find('.ui-button:first').click();
  4250. }
  4251. }); // end $(document).on()
  4252. }
  4253. if ($('textarea[name="view[as]"]').length !== 0) {
  4254. codemirror_editor = PMA_getSQLEditor($('textarea[name="view[as]"]'));
  4255. }
  4256. });
  4257. function PMA_createViewDialog ($this) {
  4258. var $msg = PMA_ajaxShowMessage();
  4259. var syntaxHighlighter = null;
  4260. var sep = PMA_commonParams.get('arg_separator');
  4261. var params = getJSConfirmCommonParam(this, $this.getPostData());
  4262. params += sep + 'ajax_dialog=1';
  4263. $.post($this.attr('href'), params, function (data) {
  4264. if (typeof data !== 'undefined' && data.success === true) {
  4265. PMA_ajaxRemoveMessage($msg);
  4266. var buttonOptions = {};
  4267. buttonOptions[PMA_messages.strGo] = function () {
  4268. if (typeof CodeMirror !== 'undefined') {
  4269. codemirror_editor.save();
  4270. }
  4271. $msg = PMA_ajaxShowMessage();
  4272. $.post('view_create.php', $('#createViewDialog').find('form').serialize(), function (data) {
  4273. PMA_ajaxRemoveMessage($msg);
  4274. if (typeof data !== 'undefined' && data.success === true) {
  4275. $('#createViewDialog').dialog('close');
  4276. $('.result_query').html(data.message);
  4277. PMA_reloadNavigation();
  4278. } else {
  4279. PMA_ajaxShowMessage(data.error, false);
  4280. }
  4281. });
  4282. };
  4283. buttonOptions[PMA_messages.strClose] = function () {
  4284. $(this).dialog('close');
  4285. };
  4286. var $dialog = $('<div/>').attr('id', 'createViewDialog').append(data.message).dialog({
  4287. width: 600,
  4288. minWidth: 400,
  4289. modal: true,
  4290. buttons: buttonOptions,
  4291. title: PMA_messages.strCreateView,
  4292. close: function () {
  4293. $(this).remove();
  4294. }
  4295. });
  4296. // Attach syntax highlighted editor
  4297. codemirror_editor = PMA_getSQLEditor($dialog.find('textarea'));
  4298. $('input:visible[type=text]', $dialog).first().focus();
  4299. } else {
  4300. PMA_ajaxShowMessage(data.error);
  4301. }
  4302. });
  4303. }
  4304. /**
  4305. * Makes the breadcrumbs and the menu bar float at the top of the viewport
  4306. */
  4307. $(function () {
  4308. if ($('#floating_menubar').length && $('#PMA_disable_floating_menubar').length === 0) {
  4309. var left = $('html').attr('dir') === 'ltr' ? 'left' : 'right';
  4310. $('#floating_menubar')
  4311. .css('margin-' + left, $('#pma_navigation').width() + $('#pma_navigation_resizer').width())
  4312. .css(left, 0)
  4313. .css({
  4314. 'position': 'fixed',
  4315. 'top': 0,
  4316. 'width': '100%',
  4317. 'z-index': 99
  4318. })
  4319. .append($('#serverinfo'))
  4320. .append($('#topmenucontainer'));
  4321. // Allow the DOM to render, then adjust the padding on the body
  4322. setTimeout(function () {
  4323. $('body').css(
  4324. 'padding-top',
  4325. $('#floating_menubar').outerHeight(true)
  4326. );
  4327. $('#topmenu').menuResizer('resize');
  4328. }, 4);
  4329. }
  4330. });
  4331. /**
  4332. * Scrolls the page to the top if clicking the serverinfo bar
  4333. */
  4334. $(function () {
  4335. $(document).on('click', '#serverinfo, #goto_pagetop', function (event) {
  4336. event.preventDefault();
  4337. $('html, body').animate({ scrollTop: 0 }, 'fast');
  4338. });
  4339. });
  4340. var checkboxes_sel = 'input.checkall:checkbox:enabled';
  4341. /**
  4342. * Watches checkboxes in a form to set the checkall box accordingly
  4343. */
  4344. var checkboxes_changed = function () {
  4345. var $form = $(this.form);
  4346. // total number of checkboxes in current form
  4347. var total_boxes = $form.find(checkboxes_sel).length;
  4348. // number of checkboxes checked in current form
  4349. var checked_boxes = $form.find(checkboxes_sel + ':checked').length;
  4350. var $checkall = $form.find('input.checkall_box');
  4351. if (total_boxes === checked_boxes) {
  4352. $checkall.prop({ checked: true, indeterminate: false });
  4353. } else if (checked_boxes > 0) {
  4354. $checkall.prop({ checked: true, indeterminate: true });
  4355. } else {
  4356. $checkall.prop({ checked: false, indeterminate: false });
  4357. }
  4358. };
  4359. $(document).on('change', checkboxes_sel, checkboxes_changed);
  4360. $(document).on('change', 'input.checkall_box', function () {
  4361. var is_checked = $(this).is(':checked');
  4362. $(this.form).find(checkboxes_sel).not('.row-hidden').prop('checked', is_checked)
  4363. .parents('tr').toggleClass('marked', is_checked);
  4364. });
  4365. $(document).on('click', '.checkall-filter', function () {
  4366. var $this = $(this);
  4367. var selector = $this.data('checkall-selector');
  4368. $('input.checkall_box').prop('checked', false);
  4369. $this.parents('form').find(checkboxes_sel).filter(selector).prop('checked', true).trigger('change')
  4370. .parents('tr').toggleClass('marked', true);
  4371. return false;
  4372. });
  4373. /**
  4374. * Watches checkboxes in a sub form to set the sub checkall box accordingly
  4375. */
  4376. var sub_checkboxes_changed = function () {
  4377. var $form = $(this).parent().parent();
  4378. // total number of checkboxes in current sub form
  4379. var total_boxes = $form.find(checkboxes_sel).length;
  4380. // number of checkboxes checked in current sub form
  4381. var checked_boxes = $form.find(checkboxes_sel + ':checked').length;
  4382. var $checkall = $form.find('input.sub_checkall_box');
  4383. if (total_boxes === checked_boxes) {
  4384. $checkall.prop({ checked: true, indeterminate: false });
  4385. } else if (checked_boxes > 0) {
  4386. $checkall.prop({ checked: true, indeterminate: true });
  4387. } else {
  4388. $checkall.prop({ checked: false, indeterminate: false });
  4389. }
  4390. };
  4391. $(document).on('change', checkboxes_sel + ', input.checkall_box:checkbox:enabled', sub_checkboxes_changed);
  4392. $(document).on('change', 'input.sub_checkall_box', function () {
  4393. var is_checked = $(this).is(':checked');
  4394. var $form = $(this).parent().parent();
  4395. $form.find(checkboxes_sel).prop('checked', is_checked)
  4396. .parents('tr').toggleClass('marked', is_checked);
  4397. });
  4398. /**
  4399. * Rows filtering
  4400. *
  4401. * - rows to filter are identified by data-filter-row attribute
  4402. * which contains uppercase string to filter
  4403. * - it is simple substring case insensitive search
  4404. * - optionally number of matching rows is written to element with
  4405. * id filter-rows-count
  4406. */
  4407. $(document).on('keyup', '#filterText', function () {
  4408. var filterInput = $(this).val().toUpperCase();
  4409. var count = 0;
  4410. $('[data-filter-row]').each(function () {
  4411. var $row = $(this);
  4412. /* Can not use data() here as it does magic conversion to int for numeric values */
  4413. if ($row.attr('data-filter-row').indexOf(filterInput) > -1) {
  4414. count += 1;
  4415. $row.show();
  4416. $row.find('input.checkall').removeClass('row-hidden');
  4417. } else {
  4418. $row.hide();
  4419. $row.find('input.checkall').addClass('row-hidden').prop('checked', false);
  4420. $row.removeClass('marked');
  4421. }
  4422. });
  4423. setTimeout(function () {
  4424. $(checkboxes_sel).trigger('change');
  4425. }, 300);
  4426. $('#filter-rows-count').html(count);
  4427. });
  4428. AJAX.registerOnload('functions.js', function () {
  4429. /* Trigger filtering of the list based on incoming database name */
  4430. var $filter = $('#filterText');
  4431. if ($filter.val()) {
  4432. $filter.trigger('keyup').select();
  4433. }
  4434. });
  4435. /**
  4436. * Formats a byte number to human-readable form
  4437. *
  4438. * @param bytes the bytes to format
  4439. * @param optional subdecimals the number of digits after the point
  4440. * @param optional pointchar the char to use as decimal point
  4441. */
  4442. function formatBytes (bytes, subdecimals, pointchar) {
  4443. if (!subdecimals) {
  4444. subdecimals = 0;
  4445. }
  4446. if (!pointchar) {
  4447. pointchar = '.';
  4448. }
  4449. var units = ['B', 'KiB', 'MiB', 'GiB'];
  4450. for (var i = 0; bytes > 1024 && i < units.length; i++) {
  4451. bytes /= 1024;
  4452. }
  4453. var factor = Math.pow(10, subdecimals);
  4454. bytes = Math.round(bytes * factor) / factor;
  4455. bytes = bytes.toString().split('.').join(pointchar);
  4456. return bytes + ' ' + units[i];
  4457. }
  4458. AJAX.registerOnload('functions.js', function () {
  4459. /**
  4460. * Reveal the login form to users with JS enabled
  4461. * and focus the appropriate input field
  4462. */
  4463. var $loginform = $('#loginform');
  4464. if ($loginform.length) {
  4465. $loginform.find('.js-show').show();
  4466. if ($('#input_username').val()) {
  4467. $('#input_password').trigger('focus');
  4468. } else {
  4469. $('#input_username').trigger('focus');
  4470. }
  4471. }
  4472. var $https_warning = $('#js-https-mismatch');
  4473. if ($https_warning.length) {
  4474. if ((window.location.protocol === 'https:') !== PMA_commonParams.get('is_https')) {
  4475. $https_warning.show();
  4476. }
  4477. }
  4478. });
  4479. /**
  4480. * Formats timestamp for display
  4481. */
  4482. function PMA_formatDateTime (date, seconds) {
  4483. var result = $.datepicker.formatDate('yy-mm-dd', date);
  4484. var timefmt = 'HH:mm';
  4485. if (seconds) {
  4486. timefmt = 'HH:mm:ss';
  4487. }
  4488. return result + ' ' + $.datepicker.formatTime(
  4489. timefmt, {
  4490. hour: date.getHours(),
  4491. minute: date.getMinutes(),
  4492. second: date.getSeconds()
  4493. }
  4494. );
  4495. }
  4496. /**
  4497. * Check than forms have less fields than max allowed by PHP.
  4498. */
  4499. function checkNumberOfFields () {
  4500. if (typeof maxInputVars === 'undefined') {
  4501. return false;
  4502. }
  4503. if (false === maxInputVars) {
  4504. return false;
  4505. }
  4506. $('form').each(function () {
  4507. var nbInputs = $(this).find(':input').length;
  4508. if (nbInputs > maxInputVars) {
  4509. var warning = PMA_sprintf(PMA_messages.strTooManyInputs, maxInputVars);
  4510. PMA_ajaxShowMessage(warning);
  4511. return false;
  4512. }
  4513. return true;
  4514. });
  4515. return true;
  4516. }
  4517. /**
  4518. * Ignore the displayed php errors.
  4519. * Simply removes the displayed errors.
  4520. *
  4521. * @param clearPrevErrors whether to clear errors stored
  4522. * in $_SESSION['prev_errors'] at server
  4523. *
  4524. */
  4525. function PMA_ignorePhpErrors (clearPrevErrors) {
  4526. if (typeof(clearPrevErrors) === 'undefined' ||
  4527. clearPrevErrors === null
  4528. ) {
  4529. str = false;
  4530. }
  4531. // send AJAX request to error_report.php with send_error_report=0, exception_type=php & token.
  4532. // It clears the prev_errors stored in session.
  4533. if (clearPrevErrors) {
  4534. var $pmaReportErrorsForm = $('#pma_report_errors_form');
  4535. $pmaReportErrorsForm.find('input[name="send_error_report"]').val(0); // change send_error_report to '0'
  4536. $pmaReportErrorsForm.submit();
  4537. }
  4538. // remove displayed errors
  4539. var $pmaErrors = $('#pma_errors');
  4540. $pmaErrors.fadeOut('slow');
  4541. $pmaErrors.remove();
  4542. }
  4543. /**
  4544. * Toggle the Datetimepicker UI if the date value entered
  4545. * by the user in the 'text box' is not going to be accepted
  4546. * by the Datetimepicker plugin (but is accepted by MySQL)
  4547. */
  4548. function toggleDatepickerIfInvalid ($td, $input_field) {
  4549. // Regex allowed by the Datetimepicker UI
  4550. var dtexpDate = new RegExp(['^([0-9]{4})',
  4551. '-(((01|03|05|07|08|10|12)-((0[1-9])|([1-2][0-9])|(3[0-1])))|((02|04|06|09|11)',
  4552. '-((0[1-9])|([1-2][0-9])|30)))$'].join(''));
  4553. var dtexpTime = new RegExp(['^(([0-1][0-9])|(2[0-3]))',
  4554. ':((0[0-9])|([1-5][0-9]))',
  4555. ':((0[0-9])|([1-5][0-9]))(\.[0-9]{1,6}){0,1}$'].join(''));
  4556. // If key-ed in Time or Date values are unsupported by the UI, close it
  4557. if ($td.attr('data-type') === 'date' && ! dtexpDate.test($input_field.val())) {
  4558. $input_field.datepicker('hide');
  4559. } else if ($td.attr('data-type') === 'time' && ! dtexpTime.test($input_field.val())) {
  4560. $input_field.datepicker('hide');
  4561. } else {
  4562. $input_field.datepicker('show');
  4563. }
  4564. }
  4565. /*
  4566. * Function to submit the login form after validation is done.
  4567. */
  4568. function recaptchaCallback () {
  4569. $('#login_form').submit();
  4570. }
  4571. /**
  4572. * Unbind all event handlers before tearing down a page
  4573. */
  4574. AJAX.registerTeardown('functions.js', function () {
  4575. $(document).off('keydown', 'form input, form textarea, form select');
  4576. });
  4577. AJAX.registerOnload('functions.js', function () {
  4578. /**
  4579. * Handle 'Ctrl/Alt + Enter' form submits
  4580. */
  4581. $('form input, form textarea, form select').on('keydown', function (e) {
  4582. if ((e.ctrlKey && e.which === 13) || (e.altKey && e.which === 13)) {
  4583. $form = $(this).closest('form');
  4584. if (! $form.find('input[type="submit"]') ||
  4585. ! $form.find('input[type="submit"]').click()
  4586. ) {
  4587. $form.submit();
  4588. }
  4589. }
  4590. });
  4591. });
  4592. /**
  4593. * Unbind all event handlers before tearing down a page
  4594. */
  4595. AJAX.registerTeardown('functions.js', function () {
  4596. $(document).off('change', 'input[type=radio][name="pw_hash"]');
  4597. $(document).off('mouseover', '.sortlink');
  4598. $(document).off('mouseout', '.sortlink');
  4599. });
  4600. AJAX.registerOnload('functions.js', function () {
  4601. /*
  4602. * Display warning regarding SSL when sha256_password
  4603. * method is selected
  4604. * Used in user_password.php (Change Password link on index.php)
  4605. */
  4606. $(document).on('change', 'select#select_authentication_plugin_cp', function () {
  4607. if (this.value === 'sha256_password') {
  4608. $('#ssl_reqd_warning_cp').show();
  4609. } else {
  4610. $('#ssl_reqd_warning_cp').hide();
  4611. }
  4612. });
  4613. Cookies.defaults.path = PMA_commonParams.get('rootPath');
  4614. // Bind event handlers for toggling sort icons
  4615. $(document).on('mouseover', '.sortlink', function () {
  4616. $(this).find('.soimg').toggle();
  4617. });
  4618. $(document).on('mouseout', '.sortlink', function () {
  4619. $(this).find('.soimg').toggle();
  4620. });
  4621. });
  4622. /**
  4623. * Returns an HTML IMG tag for a particular image from a theme,
  4624. * which may be an actual file or an icon from a sprite
  4625. *
  4626. * @param string image The name of the file to get
  4627. * @param string alternate Used to set 'alt' and 'title' attributes of the image
  4628. * @param object attributes An associative array of other attributes
  4629. *
  4630. * @return Object The requested image, this object has two methods:
  4631. * .toString() - Returns the IMG tag for the requested image
  4632. * .attr(name) - Returns a particular attribute of the IMG
  4633. * tag given it's name
  4634. * .attr(name, value) - Sets a particular attribute of the IMG
  4635. * tag to the given value
  4636. */
  4637. function PMA_getImage (image, alternate, attributes) {
  4638. // custom image object, it will eventually be returned by this functions
  4639. var retval = {
  4640. data: {
  4641. // this is private
  4642. alt: '',
  4643. title: '',
  4644. src: 'themes/dot.gif',
  4645. },
  4646. attr: function (name, value) {
  4647. if (value == undefined) {
  4648. if (this.data[name] == undefined) {
  4649. return '';
  4650. } else {
  4651. return this.data[name];
  4652. }
  4653. } else {
  4654. this.data[name] = value;
  4655. }
  4656. },
  4657. toString: function () {
  4658. var retval = '<' + 'img';
  4659. for (var i in this.data) {
  4660. retval += ' ' + i + '="' + this.data[i] + '"';
  4661. }
  4662. retval += ' /' + '>';
  4663. return retval;
  4664. }
  4665. };
  4666. // initialise missing parameters
  4667. if (attributes == undefined) {
  4668. attributes = {};
  4669. }
  4670. if (alternate == undefined) {
  4671. alternate = '';
  4672. }
  4673. // set alt
  4674. if (attributes.alt != undefined) {
  4675. retval.attr('alt', escapeHtml(attributes.alt));
  4676. } else {
  4677. retval.attr('alt', escapeHtml(alternate));
  4678. }
  4679. // set title
  4680. if (attributes.title != undefined) {
  4681. retval.attr('title', escapeHtml(attributes.title));
  4682. } else {
  4683. retval.attr('title', escapeHtml(alternate));
  4684. }
  4685. // set css classes
  4686. retval.attr('class', 'icon ic_' + image);
  4687. // set all other attrubutes
  4688. for (var i in attributes) {
  4689. if (i == 'src') {
  4690. // do not allow to override the 'src' attribute
  4691. continue;
  4692. }
  4693. retval.attr(i, attributes[i]);
  4694. }
  4695. return retval;
  4696. }
  4697. /**
  4698. * Sets a configuration value.
  4699. *
  4700. * A configuration value may be set in both browser's local storage and
  4701. * remotely in server's configuration table.
  4702. *
  4703. * If the `only_local` argument is `true`, the value is store is stored only in
  4704. * browser's local storage and may be lost if the user resets his browser's
  4705. * settings.
  4706. *
  4707. * NOTE: Depending on server's configuration, the configuration table may be or
  4708. * not persistent.
  4709. *
  4710. * @param {string} key Configuration key.
  4711. * @param {object} value Configuration value.
  4712. * @param {boolean} only_local Configuration type.
  4713. */
  4714. function configSet (key, value, only_local) {
  4715. only_local = (typeof only_local !== 'undefined') ? only_local : false;
  4716. var serialized = JSON.stringify(value);
  4717. localStorage.setItem(key, serialized);
  4718. $.ajax({
  4719. url: 'ajax.php',
  4720. type: 'POST',
  4721. dataType: 'json',
  4722. data: {
  4723. key: key,
  4724. type: 'config-set',
  4725. server: PMA_commonParams.get('server'),
  4726. value: serialized,
  4727. },
  4728. success: function (data) {
  4729. // Updating value in local storage.
  4730. if (! data.success) {
  4731. PMA_ajaxShowMessage(data.message);
  4732. }
  4733. // Eventually, call callback.
  4734. }
  4735. });
  4736. }
  4737. /**
  4738. * Gets a configuration value. A configuration value will be searched in
  4739. * browser's local storage first and if not found, a call to the server will be
  4740. * made.
  4741. *
  4742. * If value should not be cached and the up-to-date configuration value from
  4743. * right from the server is required, the third parameter should be `false`.
  4744. *
  4745. * @param {string} key Configuration key.
  4746. * @param {boolean} cached Configuration type.
  4747. *
  4748. * @return {object} Configuration value.
  4749. */
  4750. function configGet (key, cached) {
  4751. cached = (typeof cached !== 'undefined') ? cached : true;
  4752. var value = localStorage.getItem(key);
  4753. if (cached && value !== undefined && value !== null) {
  4754. return JSON.parse(value);
  4755. }
  4756. // Result not found in local storage or ignored.
  4757. // Hitting the server.
  4758. $.ajax({
  4759. // TODO: This is ugly, but usually when a configuration is needed,
  4760. // processing cannot continue until that value is found.
  4761. // Another solution is to provide a callback as a parameter.
  4762. async: false,
  4763. url: 'ajax.php',
  4764. type: 'POST',
  4765. dataType: 'json',
  4766. data: {
  4767. type: 'config-get',
  4768. server: PMA_commonParams.get('server'),
  4769. key: key
  4770. },
  4771. success: function (data) {
  4772. // Updating value in local storage.
  4773. if (data.success) {
  4774. localStorage.setItem(key, JSON.stringify(data.value));
  4775. } else {
  4776. PMA_ajaxShowMessage(data.message);
  4777. }
  4778. // Eventually, call callback.
  4779. }
  4780. });
  4781. return JSON.parse(localStorage.getItem(key));
  4782. }
  4783. /**
  4784. * Return POST data as stored by Util::linkOrButton
  4785. */
  4786. jQuery.fn.getPostData = function () {
  4787. var dataPost = this.attr('data-post');
  4788. // Strip possible leading ?
  4789. if (dataPost !== undefined && dataPost.substring(0,1) == '?') {
  4790. dataPost = dataPost.substr(1);
  4791. }
  4792. return dataPost;
  4793. };