functions.js 171 KB

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