functions.js 169 KB

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