functions.js 146 KB

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