functions.js 126 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896
  1. /* vim: set expandtab sw=4 ts=4 sts=4: */
  2. /**
  3. * general function, usually for data manipulation pages
  4. *
  5. */
  6. /**
  7. * @var $table_clone reference to the action links on the tbl_structure page
  8. */
  9. var $table_clone = false;
  10. /**
  11. * @var sql_box_locked lock for the sqlbox textarea in the querybox/querywindow
  12. */
  13. var sql_box_locked = false;
  14. /**
  15. * @var array holds elements which content should only selected once
  16. */
  17. var only_once_elements = [];
  18. /**
  19. * @var int ajax_message_count Number of AJAX messages shown since page load
  20. */
  21. var ajax_message_count = 0;
  22. /**
  23. * @var codemirror_editor object containing CodeMirror editor of the query editor in SQL tab
  24. */
  25. var codemirror_editor = false;
  26. /**
  27. * @var codemirror_editor object containing CodeMirror editor of the inline query editor
  28. */
  29. var codemirror_inline_editor = false;
  30. /**
  31. * @var chart_activeTimeouts object active timeouts that refresh the charts. When disabling a realtime chart, this can be used to stop the continuous ajax requests
  32. */
  33. var chart_activeTimeouts = {};
  34. /**
  35. * Make sure that ajax requests will not be cached
  36. * by appending a random variable to their parameters
  37. */
  38. $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
  39. var nocache = new Date().getTime() + "" + Math.floor(Math.random() * 1000000);
  40. if (typeof options.data == "string") {
  41. options.data += "&_nocache=" + nocache;
  42. } else if (typeof options.data == "object") {
  43. options.data = $.extend(originalOptions.data, {'_nocache':nocache});
  44. }
  45. });
  46. /**
  47. * Add a hidden field to the form to indicate that this will be an
  48. * Ajax request (only if this hidden field does not exist)
  49. *
  50. * @param object the form
  51. */
  52. function PMA_prepareForAjaxRequest($form)
  53. {
  54. if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
  55. $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
  56. }
  57. }
  58. /**
  59. * Generate a new password and copy it to the password input areas
  60. *
  61. * @param object the form that holds the password fields
  62. *
  63. * @return boolean always true
  64. */
  65. function suggestPassword(passwd_form)
  66. {
  67. // restrict the password to just letters and numbers to avoid problems:
  68. // "editors and viewers regard the password as multiple words and
  69. // things like double click no longer work"
  70. var pwchars = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  71. var passwordlength = 16; // do we want that to be dynamic? no, keep it simple :)
  72. var passwd = passwd_form.generated_pw;
  73. var randomWords = new Int32Array(passwordlength);
  74. passwd.value = '';
  75. // First we're going to try to use a built-in CSPRNG
  76. if (window.crypto && window.crypto.getRandomValues) {
  77. window.crypto.getRandomValues(randomWords);
  78. }
  79. // Because of course IE calls it msCrypto instead of being standard
  80. else if (window.msCrypto && window.msCrypto.getRandomValues) {
  81. window.msCrypto.getRandomValues(randomWords);
  82. } else {
  83. // Fallback to Math.random
  84. for (var i = 0; i < passwordlength; i++) {
  85. randomWords[i] = Math.floor(Math.random() * pwchars.length);
  86. }
  87. }
  88. for (var i = 0; i < passwordlength; i++) {
  89. passwd.value += pwchars.charAt(Math.abs(randomWords[i]) % pwchars.length);
  90. }
  91. passwd_form.text_pma_pw.value = passwd.value;
  92. passwd_form.text_pma_pw2.value = passwd.value;
  93. return true;
  94. }
  95. /**
  96. * Version string to integer conversion.
  97. */
  98. function parseVersionString (str)
  99. {
  100. if (typeof(str) != 'string') { return false; }
  101. var add = 0;
  102. // Parse possible alpha/beta/rc/
  103. var state = str.split('-');
  104. if (state.length >= 2) {
  105. if (state[1].substr(0, 2) == 'rc') {
  106. add = - 20 - parseInt(state[1].substr(2));
  107. } else if (state[1].substr(0, 4) == 'beta') {
  108. add = - 40 - parseInt(state[1].substr(4));
  109. } else if (state[1].substr(0, 5) == 'alpha') {
  110. add = - 60 - parseInt(state[1].substr(5));
  111. } else if (state[1].substr(0, 3) == 'dev') {
  112. /* We don't handle dev, it's git snapshot */
  113. add = 0;
  114. }
  115. }
  116. // Parse version
  117. var x = str.split('.');
  118. // Use 0 for non existing parts
  119. var maj = parseInt(x[0]) || 0;
  120. var min = parseInt(x[1]) || 0;
  121. var pat = parseInt(x[2]) || 0;
  122. var hotfix = parseInt(x[3]) || 0;
  123. return maj * 100000000 + min * 1000000 + pat * 10000 + hotfix * 100 + add;
  124. }
  125. /**
  126. * Indicates current available version on main page.
  127. */
  128. function PMA_current_version(data)
  129. {
  130. if (data && data.version && data.date) {
  131. var current = parseVersionString(pmaversion);
  132. var latest = parseVersionString(data['version']);
  133. var version_information_message = PMA_messages['strLatestAvailable'] + ' ' + escapeHtml(data['version']);
  134. if (latest > current) {
  135. var message = $.sprintf(
  136. PMA_messages['strNewerVersion'],
  137. escapeHtml(data['version']),
  138. escapeHtml(data['date'])
  139. );
  140. if (Math.floor(latest / 10000) === Math.floor(current / 10000)) {
  141. /* Security update */
  142. var klass = 'error';
  143. } else {
  144. var klass = 'notice';
  145. }
  146. $('#maincontainer').after('<div class="' + klass + '">' + message + '</div>');
  147. }
  148. if (latest === current) {
  149. version_information_message = ' (' + PMA_messages['strUpToDate'] + ')';
  150. }
  151. $('#li_pma_version').append(version_information_message);
  152. }
  153. }
  154. /**
  155. * Loads Git revision data from ajax for index.php
  156. */
  157. function PMA_display_git_revision()
  158. {
  159. $('#is_git_revision').remove();
  160. $.get(
  161. "index.php",
  162. {
  163. "server": PMA_commonParams.get('server'),
  164. "token": PMA_commonParams.get('token'),
  165. "git_revision": true,
  166. "ajax_request": true
  167. },
  168. function (data) {
  169. if (data.success == true) {
  170. $(data.message).insertAfter('#li_pma_version');
  171. }
  172. }
  173. );
  174. }
  175. /**
  176. * for libraries/display_change_password.lib.php
  177. * libraries/user_password.php
  178. *
  179. */
  180. function displayPasswordGenerateButton()
  181. {
  182. $('#tr_element_before_generate_password').parent().append('<tr class="vmiddle"><td>' + PMA_messages['strGeneratePassword'] + '</td><td><input type="button" class="button" id="button_generate_password" value="' + PMA_messages['strGenerate'] + '" onclick="suggestPassword(this.form)" /><input type="text" name="generated_pw" id="generated_pw" /></td></tr>');
  183. $('#div_element_before_generate_password').parent().append('<div class="item"><label for="button_generate_password">' + PMA_messages['strGeneratePassword'] + ':</label><span class="options"><input type="button" class="button" id="button_generate_password" value="' + PMA_messages['strGenerate'] + '" onclick="suggestPassword(this.form)" /></span><input type="text" name="generated_pw" id="generated_pw" /></div>');
  184. }
  185. /*
  186. * Adds a date/time picker to an element
  187. *
  188. * @param object $this_element a jQuery object pointing to the element
  189. */
  190. function PMA_addDatepicker($this_element, options)
  191. {
  192. var showTimeOption = false;
  193. if ($this_element.is('.datetimefield')) {
  194. showTimeOption = true;
  195. }
  196. var defaultOptions = {
  197. showOn: 'button',
  198. buttonImage: themeCalendarImage, // defined in js/messages.php
  199. buttonImageOnly: true,
  200. stepMinutes: 1,
  201. stepHours: 1,
  202. showSecond: true,
  203. showTimepicker: showTimeOption,
  204. showButtonPanel: false,
  205. dateFormat: 'yy-mm-dd', // yy means year with four digits
  206. timeFormat: 'HH:mm:ss',
  207. altFieldTimeOnly: false,
  208. showAnim: '',
  209. beforeShow: function(input, inst) {
  210. // Remember that we came from the datepicker; this is used
  211. // in tbl_change.js by verificationsAfterFieldChange()
  212. $this_element.data('comes_from', 'datepicker');
  213. // Fix wrong timepicker z-index, doesn't work without timeout
  214. setTimeout(function() {
  215. $('#ui-timepicker-div').css('z-index',$('#ui-datepicker-div').css('z-index'));
  216. }, 0);
  217. },
  218. onClose: function(dateText, dp_inst) {
  219. // The value is no more from the date picker
  220. $this_element.data('comes_from', '');
  221. }
  222. };
  223. if ( showTimeOption || (typeof(options) != 'undefined' && options.showTimepicker) ) {
  224. $this_element.datetimepicker($.extend(defaultOptions, options));
  225. } else {
  226. $this_element.datepicker($.extend(defaultOptions, options));
  227. }
  228. }
  229. /**
  230. * selects the content of a given object, f.e. a textarea
  231. *
  232. * @param object element element of which the content will be selected
  233. * @param var lock variable which holds the lock for this element
  234. * or true, if no lock exists
  235. * @param boolean only_once if true this is only done once
  236. * f.e. only on first focus
  237. */
  238. function selectContent( element, lock, only_once )
  239. {
  240. if ( only_once && only_once_elements[element.name] ) {
  241. return;
  242. }
  243. only_once_elements[element.name] = true;
  244. if ( lock ) {
  245. return;
  246. }
  247. element.select();
  248. }
  249. /**
  250. * Displays a confirmation box before submitting a "DROP/DELETE/ALTER" query.
  251. * This function is called while clicking links
  252. *
  253. * @param object the link
  254. * @param object the sql query to submit
  255. *
  256. * @return boolean whether to run the query or not
  257. */
  258. function confirmLink(theLink, theSqlQuery)
  259. {
  260. // Confirmation is not required in the configuration file
  261. // or browser is Opera (crappy js implementation)
  262. if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
  263. return true;
  264. }
  265. var is_confirmed = confirm($.sprintf(PMA_messages['strDoYouReally'], theSqlQuery));
  266. if (is_confirmed) {
  267. if ( $(theLink).hasClass('formLinkSubmit') ) {
  268. var name = 'is_js_confirmed';
  269. if ($(theLink).attr('href').indexOf('usesubform') != -1) {
  270. name = 'subform[' + $(theLink).attr('href').substr('#').match(/usesubform\[(\d+)\]/i)[1] + '][is_js_confirmed]';
  271. }
  272. $(theLink).parents('form').append('<input type="hidden" name="' + name + '" value="1" />');
  273. } else if ( typeof(theLink.href) != 'undefined' ) {
  274. theLink.href += '&is_js_confirmed=1';
  275. } else if ( typeof(theLink.form) != 'undefined' ) {
  276. theLink.form.action += '?is_js_confirmed=1';
  277. }
  278. }
  279. return is_confirmed;
  280. } // end of the 'confirmLink()' function
  281. /**
  282. * Displays an error message if a "DROP DATABASE" statement is submitted
  283. * while it isn't allowed, else confirms a "DROP/DELETE/ALTER" query before
  284. * sumitting it if required.
  285. * This function is called by the 'checkSqlQuery()' js function.
  286. *
  287. * @param object the form
  288. * @param object the sql query textarea
  289. *
  290. * @return boolean whether to run the query or not
  291. *
  292. * @see checkSqlQuery()
  293. */
  294. function confirmQuery(theForm1, sqlQuery1)
  295. {
  296. // Confirmation is not required in the configuration file
  297. if (PMA_messages['strDoYouReally'] == '') {
  298. return true;
  299. }
  300. // "DROP DATABASE" statement isn't allowed
  301. if (PMA_messages['strNoDropDatabases'] != '') {
  302. var drop_re = new RegExp('(^|;)\\s*DROP\\s+(IF EXISTS\\s+)?DATABASE\\s', 'i');
  303. if (drop_re.test(sqlQuery1.value)) {
  304. alert(PMA_messages['strNoDropDatabases']);
  305. theForm1.reset();
  306. sqlQuery1.focus();
  307. return false;
  308. } // end if
  309. } // end if
  310. // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement
  311. //
  312. // TODO: find a way (if possible) to use the parser-analyser
  313. // for this kind of verification
  314. // For now, I just added a ^ to check for the statement at
  315. // beginning of expression
  316. var do_confirm_re_0 = new RegExp('^\\s*DROP\\s+(IF EXISTS\\s+)?(TABLE|DATABASE|PROCEDURE)\\s', 'i');
  317. var do_confirm_re_1 = new RegExp('^\\s*ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i');
  318. var do_confirm_re_2 = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
  319. var do_confirm_re_3 = new RegExp('^\\s*TRUNCATE\\s', 'i');
  320. if (do_confirm_re_0.test(sqlQuery1.value)
  321. || do_confirm_re_1.test(sqlQuery1.value)
  322. || do_confirm_re_2.test(sqlQuery1.value)
  323. || do_confirm_re_3.test(sqlQuery1.value)) {
  324. var message = (sqlQuery1.value.length > 100)
  325. ? sqlQuery1.value.substr(0, 100) + '\n ...'
  326. : sqlQuery1.value;
  327. var is_confirmed = confirm($.sprintf(PMA_messages['strDoYouReally'], message));
  328. // statement is confirmed -> update the
  329. // "is_js_confirmed" form field so the confirm test won't be
  330. // run on the server side and allows to submit the form
  331. if (is_confirmed) {
  332. theForm1.elements['is_js_confirmed'].value = 1;
  333. return true;
  334. }
  335. // statement is rejected -> do not submit the form
  336. else {
  337. window.focus();
  338. sqlQuery1.focus();
  339. return false;
  340. } // end if (handle confirm box result)
  341. } // end if (display confirm box)
  342. return true;
  343. } // end of the 'confirmQuery()' function
  344. /**
  345. * Displays an error message if the user submitted the sql query form with no
  346. * sql query, else checks for "DROP/DELETE/ALTER" statements
  347. *
  348. * @param object the form
  349. *
  350. * @return boolean always false
  351. *
  352. * @see confirmQuery()
  353. */
  354. function checkSqlQuery(theForm)
  355. {
  356. // First check if codemirror is active.
  357. if (codemirror_editor) {
  358. theForm.elements['sql_query'].value = codemirror_editor.getValue();
  359. }
  360. var sqlQuery = theForm.elements['sql_query'];
  361. var isEmpty = 1;
  362. var space_re = new RegExp('\\s+');
  363. if (typeof(theForm.elements['sql_file']) != 'undefined' &&
  364. theForm.elements['sql_file'].value.replace(space_re, '') != '') {
  365. return true;
  366. }
  367. if (typeof(theForm.elements['sql_localfile']) != 'undefined' &&
  368. theForm.elements['sql_localfile'].value.replace(space_re, '') != '') {
  369. return true;
  370. }
  371. if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined' &&
  372. (theForm.elements['id_bookmark'].value != null || theForm.elements['id_bookmark'].value != '') &&
  373. theForm.elements['id_bookmark'].selectedIndex != 0
  374. ) {
  375. return true;
  376. }
  377. // Checks for "DROP/DELETE/ALTER" statements
  378. if (sqlQuery.value.replace(space_re, '') != '') {
  379. if (confirmQuery(theForm, sqlQuery)) {
  380. return true;
  381. } else {
  382. return false;
  383. }
  384. }
  385. theForm.reset();
  386. isEmpty = 1;
  387. if (isEmpty) {
  388. sqlQuery.select();
  389. alert(PMA_messages['strFormEmpty']);
  390. sqlQuery.focus();
  391. return false;
  392. }
  393. return true;
  394. } // end of the 'checkSqlQuery()' function
  395. /**
  396. * Check if a form's element is empty.
  397. * An element containing only spaces is also considered empty
  398. *
  399. * @param object the form
  400. * @param string the name of the form field to put the focus on
  401. *
  402. * @return boolean whether the form field is empty or not
  403. */
  404. function emptyCheckTheField(theForm, theFieldName)
  405. {
  406. var theField = theForm.elements[theFieldName];
  407. var space_re = new RegExp('\\s+');
  408. return (theField.value.replace(space_re, '') == '') ? 1 : 0;
  409. } // end of the 'emptyCheckTheField()' function
  410. /**
  411. * Check whether a form field is empty or not
  412. *
  413. * @param object the form
  414. * @param string the name of the form field to put the focus on
  415. *
  416. * @return boolean whether the form field is empty or not
  417. */
  418. function emptyFormElements(theForm, theFieldName)
  419. {
  420. var theField = theForm.elements[theFieldName];
  421. var isEmpty = emptyCheckTheField(theForm, theFieldName);
  422. return isEmpty;
  423. } // end of the 'emptyFormElements()' function
  424. /**
  425. * Ensures a value submitted in a form is numeric and is in a range
  426. *
  427. * @param object the form
  428. * @param string the name of the form field to check
  429. * @param integer the minimum authorized value
  430. * @param integer the maximum authorized value
  431. *
  432. * @return boolean whether a valid number has been submitted or not
  433. */
  434. function checkFormElementInRange(theForm, theFieldName, message, min, max)
  435. {
  436. var theField = theForm.elements[theFieldName];
  437. var val = parseInt(theField.value);
  438. if (typeof(min) == 'undefined') {
  439. min = 0;
  440. }
  441. if (typeof(max) == 'undefined') {
  442. max = Number.MAX_VALUE;
  443. }
  444. // It's not a number
  445. if (isNaN(val)) {
  446. theField.select();
  447. alert(PMA_messages['strNotNumber']);
  448. theField.focus();
  449. return false;
  450. }
  451. // It's a number but it is not between min and max
  452. else if (val < min || val > max) {
  453. theField.select();
  454. alert($.sprintf(message, val));
  455. theField.focus();
  456. return false;
  457. }
  458. // It's a valid number
  459. else {
  460. theField.value = val;
  461. }
  462. return true;
  463. } // end of the 'checkFormElementInRange()' function
  464. function checkTableEditForm(theForm, fieldsCnt)
  465. {
  466. // TODO: avoid sending a message if user just wants to add a line
  467. // on the form but has not completed at least one field name
  468. var atLeastOneField = 0;
  469. var i, elm, elm2, elm3, val, id;
  470. for (i=0; i<fieldsCnt; i++)
  471. {
  472. id = "#field_" + i + "_2";
  473. elm = $(id);
  474. val = elm.val();
  475. if (val == 'VARCHAR' || val == 'CHAR' || val == 'BIT' || val == 'VARBINARY' || val == 'BINARY') {
  476. elm2 = $("#field_" + i + "_3");
  477. val = parseInt(elm2.val());
  478. elm3 = $("#field_" + i + "_1");
  479. if (isNaN(val) && elm3.val() != "") {
  480. elm2.select();
  481. alert(PMA_messages['strNotNumber']);
  482. elm2.focus();
  483. return false;
  484. }
  485. }
  486. if (atLeastOneField == 0) {
  487. id = "field_" + i + "_1";
  488. if (!emptyCheckTheField(theForm, id)) {
  489. atLeastOneField = 1;
  490. }
  491. }
  492. }
  493. if (atLeastOneField == 0) {
  494. var theField = theForm.elements["field_0_1"];
  495. alert(PMA_messages['strFormEmpty']);
  496. theField.focus();
  497. return false;
  498. }
  499. // at least this section is under jQuery
  500. if ($("input.textfield[name='table']").val() == "") {
  501. alert(PMA_messages['strFormEmpty']);
  502. $("input.textfield[name='table']").focus();
  503. return false;
  504. }
  505. return true;
  506. } // enf of the 'checkTableEditForm()' function
  507. /**
  508. * Unbind all event handlers before tearing down a page
  509. */
  510. AJAX.registerTeardown('functions.js', function() {
  511. $('input:checkbox.checkall').die('click');
  512. });
  513. AJAX.registerOnload('functions.js', function() {
  514. /**
  515. * Row marking in horizontal mode (use "live" so that it works also for
  516. * next pages reached via AJAX); a tr may have the class noclick to remove
  517. * this behavior.
  518. */
  519. $('input:checkbox.checkall').live('click', function(e) {
  520. var $tr = $(this).closest('tr');
  521. // make the table unselectable (to prevent default highlighting when shift+click)
  522. //$tr.parents('table').noSelect();
  523. if (!e.shiftKey || last_clicked_row == -1) {
  524. // usual click
  525. // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
  526. var $checkbox = $tr.find(':checkbox');
  527. if ($checkbox.length) {
  528. // checkbox in a row, add or remove class depending on checkbox state
  529. var checked = $checkbox.prop('checked');
  530. if (!$(e.target).is(':checkbox, label')) {
  531. checked = !checked;
  532. $checkbox.prop('checked', checked).trigger('change');
  533. }
  534. if (checked) {
  535. $tr.addClass('marked');
  536. } else {
  537. $tr.removeClass('marked');
  538. }
  539. last_click_checked = checked;
  540. } else {
  541. // normal data table, just toggle class
  542. $tr.toggleClass('marked');
  543. last_click_checked = false;
  544. }
  545. // remember the last clicked row
  546. last_clicked_row = last_click_checked ? $('tr.odd:not(.noclick), tr.even:not(.noclick)').index($tr) : -1;
  547. last_shift_clicked_row = -1;
  548. } else {
  549. // handle the shift click
  550. PMA_clearSelection();
  551. var start, end;
  552. // clear last shift click result
  553. if (last_shift_clicked_row >= 0) {
  554. if (last_shift_clicked_row >= last_clicked_row) {
  555. start = last_clicked_row;
  556. end = last_shift_clicked_row;
  557. } else {
  558. start = last_shift_clicked_row;
  559. end = last_clicked_row;
  560. }
  561. $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
  562. .slice(start, end + 1)
  563. .removeClass('marked')
  564. .find(':checkbox')
  565. .prop('checked', false)
  566. .trigger('change');
  567. }
  568. // handle new shift click
  569. var curr_row = $('tr.odd:not(.noclick), tr.even:not(.noclick)').index($tr);
  570. if (curr_row >= last_clicked_row) {
  571. start = last_clicked_row;
  572. end = curr_row;
  573. } else {
  574. start = curr_row;
  575. end = last_clicked_row;
  576. }
  577. $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
  578. .slice(start, end + 1)
  579. .addClass('marked')
  580. .find(':checkbox')
  581. .prop('checked', true)
  582. .trigger('change');
  583. // remember the last shift clicked row
  584. last_shift_clicked_row = curr_row;
  585. }
  586. });
  587. addDateTimePicker();
  588. /**
  589. * Add attribute to text boxes for iOS devices (based on bugID: 3508912)
  590. */
  591. if (navigator.userAgent.match(/(iphone|ipod|ipad)/i)) {
  592. $('input[type=text]').attr('autocapitalize','off').attr('autocorrect','off');
  593. }
  594. });
  595. /**
  596. * True if last click is to check a row.
  597. */
  598. var last_click_checked = false;
  599. /**
  600. * Zero-based index of last clicked row.
  601. * Used to handle the shift + click event in the code above.
  602. */
  603. var last_clicked_row = -1;
  604. /**
  605. * Zero-based index of last shift clicked row.
  606. */
  607. var last_shift_clicked_row = -1;
  608. /**
  609. * Row highlighting in horizontal mode (use "live"
  610. * so that it works also for pages reached via AJAX)
  611. */
  612. /*AJAX.registerOnload('functions.js', function() {
  613. $('tr.odd, tr.even').live('hover',function(event) {
  614. var $tr = $(this);
  615. $tr.toggleClass('hover',event.type=='mouseover');
  616. $tr.children().toggleClass('hover',event.type=='mouseover');
  617. });
  618. })*/
  619. /**
  620. * This array is used to remember mark status of rows in browse mode
  621. */
  622. var marked_row = [];
  623. /**
  624. * marks all rows and selects its first checkbox inside the given element
  625. * the given element is usaly a table or a div containing the table or tables
  626. *
  627. * @param container DOM element
  628. */
  629. function markAllRows(container_id)
  630. {
  631. $("#" + container_id).find("input:checkbox:enabled").prop('checked', true)
  632. .trigger("change")
  633. .parents("tr").addClass("marked");
  634. return true;
  635. }
  636. /**
  637. * marks all rows and selects its first checkbox inside the given element
  638. * the given element is usaly a table or a div containing the table or tables
  639. *
  640. * @param container DOM element
  641. */
  642. function unMarkAllRows(container_id)
  643. {
  644. $("#" + container_id).find("input:checkbox:enabled").prop('checked', false)
  645. .trigger("change")
  646. .parents("tr").removeClass("marked");
  647. return true;
  648. }
  649. /**
  650. * Checks/unchecks all checkbox in given conainer (f.e. a form, fieldset or div)
  651. *
  652. * @param string container_id the container id
  653. * @param boolean state new value for checkbox (true or false)
  654. * @return boolean always true
  655. */
  656. function setCheckboxes(container_id, state)
  657. {
  658. $("#" + container_id).find("input:checkbox").prop('checked', state);
  659. return true;
  660. } // end of the 'setCheckboxes()' function
  661. /**
  662. * Checks/unchecks all options of a <select> element
  663. *
  664. * @param string the form name
  665. * @param string the element name
  666. * @param boolean whether to check or to uncheck options
  667. *
  668. * @return boolean always true
  669. */
  670. function setSelectOptions(the_form, the_select, do_check)
  671. {
  672. $("form[name='"+ the_form +"'] select[name='"+the_select+"']").find("option").prop('selected', do_check);
  673. return true;
  674. } // end of the 'setSelectOptions()' function
  675. /**
  676. * Sets current value for query box.
  677. */
  678. function setQuery(query)
  679. {
  680. if (codemirror_editor) {
  681. codemirror_editor.setValue(query);
  682. codemirror_editor.focus();
  683. } else {
  684. document.sqlform.sql_query.value = query;
  685. document.sqlform.sql_query.focus();
  686. }
  687. }
  688. /**
  689. * Create quick sql statements.
  690. *
  691. */
  692. function insertQuery(queryType)
  693. {
  694. if (queryType == "clear") {
  695. setQuery('');
  696. return;
  697. }
  698. var query = "";
  699. var myListBox = document.sqlform.dummy;
  700. var table = document.sqlform.table.value;
  701. if (myListBox.options.length > 0) {
  702. sql_box_locked = true;
  703. var chaineAj = "";
  704. var valDis = "";
  705. var editDis = "";
  706. var NbSelect = 0;
  707. for (var i=0; i < myListBox.options.length; i++) {
  708. NbSelect++;
  709. if (NbSelect > 1) {
  710. chaineAj += ", ";
  711. valDis += ",";
  712. editDis += ",";
  713. }
  714. chaineAj += myListBox.options[i].value;
  715. valDis += "[value-" + NbSelect + "]";
  716. editDis += myListBox.options[i].value + "=[value-" + NbSelect + "]";
  717. }
  718. if (queryType == "selectall") {
  719. query = "SELECT * FROM `" + table + "` WHERE 1";
  720. } else if (queryType == "select") {
  721. query = "SELECT " + chaineAj + " FROM `" + table + "` WHERE 1";
  722. } else if (queryType == "insert") {
  723. query = "INSERT INTO `" + table + "`(" + chaineAj + ") VALUES (" + valDis + ")";
  724. } else if (queryType == "update") {
  725. query = "UPDATE `" + table + "` SET " + editDis + " WHERE 1";
  726. } else if (queryType == "delete") {
  727. query = "DELETE FROM `" + table + "` WHERE 1";
  728. }
  729. setQuery(query);
  730. sql_box_locked = false;
  731. }
  732. }
  733. /**
  734. * Inserts multiple fields.
  735. *
  736. */
  737. function insertValueQuery()
  738. {
  739. var myQuery = document.sqlform.sql_query;
  740. var myListBox = document.sqlform.dummy;
  741. if (myListBox.options.length > 0) {
  742. sql_box_locked = true;
  743. var chaineAj = "";
  744. var NbSelect = 0;
  745. for (var i=0; i<myListBox.options.length; i++) {
  746. if (myListBox.options[i].selected) {
  747. NbSelect++;
  748. if (NbSelect > 1) {
  749. chaineAj += ", ";
  750. }
  751. chaineAj += myListBox.options[i].value;
  752. }
  753. }
  754. /* CodeMirror support */
  755. if (codemirror_editor) {
  756. codemirror_editor.replaceSelection(chaineAj);
  757. //IE support
  758. } else if (document.selection) {
  759. myQuery.focus();
  760. var sel = document.selection.createRange();
  761. sel.text = chaineAj;
  762. document.sqlform.insert.focus();
  763. }
  764. //MOZILLA/NETSCAPE support
  765. else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart == "0") {
  766. var startPos = document.sqlform.sql_query.selectionStart;
  767. var endPos = document.sqlform.sql_query.selectionEnd;
  768. var chaineSql = document.sqlform.sql_query.value;
  769. myQuery.value = chaineSql.substring(0, startPos) + chaineAj + chaineSql.substring(endPos, chaineSql.length);
  770. } else {
  771. myQuery.value += chaineAj;
  772. }
  773. sql_box_locked = false;
  774. }
  775. }
  776. /**
  777. * Add a date/time picker to each element that needs it
  778. * (only when jquery-ui-timepicker-addon.js is loaded)
  779. */
  780. function addDateTimePicker() {
  781. if ($.timepicker != undefined) {
  782. $('input.datefield, input.datetimefield').each(function() {
  783. PMA_addDatepicker($(this));
  784. });
  785. }
  786. }
  787. /**
  788. * Refresh/resize the WYSIWYG scratchboard
  789. */
  790. function refreshLayout()
  791. {
  792. var $elm = $('#pdflayout');
  793. var orientation = $('#orientation_opt').val();
  794. if ($('#paper_opt').length==1) {
  795. var paper = $('#paper_opt').val();
  796. }else{
  797. var paper = 'A4';
  798. }
  799. if (orientation == 'P') {
  800. var posa = 'x';
  801. var posb = 'y';
  802. } else {
  803. var posa = 'y';
  804. var posb = 'x';
  805. }
  806. $elm.css('width', pdfPaperSize(paper, posa) + 'px');
  807. $elm.css('height', pdfPaperSize(paper, posb) + 'px');
  808. }
  809. /**
  810. * Initializes positions of elements.
  811. */
  812. function TableDragInit() {
  813. $('.pdflayout_table').each(function () {
  814. var $this = $(this);
  815. var number = $this.data('number');
  816. var x = $('#c_table_' + number + '_x').val();
  817. var y = $('#c_table_' + number + '_y').val();
  818. $this.css('left', x + 'px');
  819. $this.css('top', y + 'px');
  820. /* Make elements draggable */
  821. $this.draggable({
  822. containment: "parent",
  823. drag: function (evt, ui) {
  824. var number = $this.data('number');
  825. $('#c_table_' + number + '_x').val(parseInt(ui.position.left));
  826. $('#c_table_' + number + '_y').val(parseInt(ui.position.top));
  827. }
  828. });
  829. });
  830. }
  831. /**
  832. * Resets drag and drop positions.
  833. */
  834. function resetDrag() {
  835. $('.pdflayout_table').each(function () {
  836. var $this = $(this);
  837. var x = $this.data('x');
  838. var y = $this.data('y');
  839. $this.css('left', x + 'px');
  840. $this.css('top', y + 'px');
  841. });
  842. }
  843. /**
  844. * User schema handlers.
  845. */
  846. $(function () {
  847. /* Move in scratchboard on manual change */
  848. $('.position-change').live('change', function () {
  849. var $this = $(this);
  850. var $elm = $('#table_' + $this.data('number'));
  851. $elm.css($this.data('axis'), $this.val() + 'px');
  852. });
  853. /* Refresh on paper size/orientation change */
  854. $('.paper-change').live('change', function () {
  855. var $elm = $('#pdflayout');
  856. if ($elm.css('visibility') == 'visible') {
  857. refreshLayout();
  858. TableDragInit();
  859. }
  860. });
  861. /* Show/hide the WYSIWYG scratchboard */
  862. $('#toggle-dragdrop').live('click', function () {
  863. var $elm = $('#pdflayout');
  864. if ($elm.css('visibility') == 'hidden') {
  865. refreshLayout();
  866. TableDragInit();
  867. $elm.css('visibility', 'visible');
  868. $elm.css('display', 'block');
  869. $('#showwysiwyg').val('1');
  870. } else {
  871. $elm.css('visibility', 'hidden');
  872. $elm.css('display', 'none');
  873. $('#showwysiwyg').val('0');
  874. }
  875. });
  876. /* Reset scratchboard */
  877. $('#reset-dragdrop').live('click', function () {
  878. resetDrag();
  879. });
  880. });
  881. /**
  882. * Returns paper sizes for a given format
  883. */
  884. function pdfPaperSize(format, axis)
  885. {
  886. switch (format.toUpperCase()) {
  887. case '4A0':
  888. if (axis == 'x') {
  889. return 4767.87;
  890. } else {
  891. return 6740.79;
  892. }
  893. break;
  894. case '2A0':
  895. if (axis == 'x') {
  896. return 3370.39;
  897. } else {
  898. return 4767.87;
  899. }
  900. break;
  901. case 'A0':
  902. if (axis == 'x') {
  903. return 2383.94;
  904. } else {
  905. return 3370.39;
  906. }
  907. break;
  908. case 'A1':
  909. if (axis == 'x') {
  910. return 1683.78;
  911. } else {
  912. return 2383.94;
  913. }
  914. break;
  915. case 'A2':
  916. if (axis == 'x') {
  917. return 1190.55;
  918. } else {
  919. return 1683.78;
  920. }
  921. break;
  922. case 'A3':
  923. if (axis == 'x') {
  924. return 841.89;
  925. } else {
  926. return 1190.55;
  927. }
  928. break;
  929. case 'A4':
  930. if (axis == 'x') {
  931. return 595.28;
  932. } else {
  933. return 841.89;
  934. }
  935. break;
  936. case 'A5':
  937. if (axis == 'x') {
  938. return 419.53;
  939. } else {
  940. return 595.28;
  941. }
  942. break;
  943. case 'A6':
  944. if (axis == 'x') {
  945. return 297.64;
  946. } else {
  947. return 419.53;
  948. }
  949. break;
  950. case 'A7':
  951. if (axis == 'x') {
  952. return 209.76;
  953. } else {
  954. return 297.64;
  955. }
  956. break;
  957. case 'A8':
  958. if (axis == 'x') {
  959. return 147.40;
  960. } else {
  961. return 209.76;
  962. }
  963. break;
  964. case 'A9':
  965. if (axis == 'x') {
  966. return 104.88;
  967. } else {
  968. return 147.40;
  969. }
  970. break;
  971. case 'A10':
  972. if (axis == 'x') {
  973. return 73.70;
  974. } else {
  975. return 104.88;
  976. }
  977. break;
  978. case 'B0':
  979. if (axis == 'x') {
  980. return 2834.65;
  981. } else {
  982. return 4008.19;
  983. }
  984. break;
  985. case 'B1':
  986. if (axis == 'x') {
  987. return 2004.09;
  988. } else {
  989. return 2834.65;
  990. }
  991. break;
  992. case 'B2':
  993. if (axis == 'x') {
  994. return 1417.32;
  995. } else {
  996. return 2004.09;
  997. }
  998. break;
  999. case 'B3':
  1000. if (axis == 'x') {
  1001. return 1000.63;
  1002. } else {
  1003. return 1417.32;
  1004. }
  1005. break;
  1006. case 'B4':
  1007. if (axis == 'x') {
  1008. return 708.66;
  1009. } else {
  1010. return 1000.63;
  1011. }
  1012. break;
  1013. case 'B5':
  1014. if (axis == 'x') {
  1015. return 498.90;
  1016. } else {
  1017. return 708.66;
  1018. }
  1019. break;
  1020. case 'B6':
  1021. if (axis == 'x') {
  1022. return 354.33;
  1023. } else {
  1024. return 498.90;
  1025. }
  1026. break;
  1027. case 'B7':
  1028. if (axis == 'x') {
  1029. return 249.45;
  1030. } else {
  1031. return 354.33;
  1032. }
  1033. break;
  1034. case 'B8':
  1035. if (axis == 'x') {
  1036. return 175.75;
  1037. } else {
  1038. return 249.45;
  1039. }
  1040. break;
  1041. case 'B9':
  1042. if (axis == 'x') {
  1043. return 124.72;
  1044. } else {
  1045. return 175.75;
  1046. }
  1047. break;
  1048. case 'B10':
  1049. if (axis == 'x') {
  1050. return 87.87;
  1051. } else {
  1052. return 124.72;
  1053. }
  1054. break;
  1055. case 'C0':
  1056. if (axis == 'x') {
  1057. return 2599.37;
  1058. } else {
  1059. return 3676.54;
  1060. }
  1061. break;
  1062. case 'C1':
  1063. if (axis == 'x') {
  1064. return 1836.85;
  1065. } else {
  1066. return 2599.37;
  1067. }
  1068. break;
  1069. case 'C2':
  1070. if (axis == 'x') {
  1071. return 1298.27;
  1072. } else {
  1073. return 1836.85;
  1074. }
  1075. break;
  1076. case 'C3':
  1077. if (axis == 'x') {
  1078. return 918.43;
  1079. } else {
  1080. return 1298.27;
  1081. }
  1082. break;
  1083. case 'C4':
  1084. if (axis == 'x') {
  1085. return 649.13;
  1086. } else {
  1087. return 918.43;
  1088. }
  1089. break;
  1090. case 'C5':
  1091. if (axis == 'x') {
  1092. return 459.21;
  1093. } else {
  1094. return 649.13;
  1095. }
  1096. break;
  1097. case 'C6':
  1098. if (axis == 'x') {
  1099. return 323.15;
  1100. } else {
  1101. return 459.21;
  1102. }
  1103. break;
  1104. case 'C7':
  1105. if (axis == 'x') {
  1106. return 229.61;
  1107. } else {
  1108. return 323.15;
  1109. }
  1110. break;
  1111. case 'C8':
  1112. if (axis == 'x') {
  1113. return 161.57;
  1114. } else {
  1115. return 229.61;
  1116. }
  1117. break;
  1118. case 'C9':
  1119. if (axis == 'x') {
  1120. return 113.39;
  1121. } else {
  1122. return 161.57;
  1123. }
  1124. break;
  1125. case 'C10':
  1126. if (axis == 'x') {
  1127. return 79.37;
  1128. } else {
  1129. return 113.39;
  1130. }
  1131. break;
  1132. case 'RA0':
  1133. if (axis == 'x') {
  1134. return 2437.80;
  1135. } else {
  1136. return 3458.27;
  1137. }
  1138. break;
  1139. case 'RA1':
  1140. if (axis == 'x') {
  1141. return 1729.13;
  1142. } else {
  1143. return 2437.80;
  1144. }
  1145. break;
  1146. case 'RA2':
  1147. if (axis == 'x') {
  1148. return 1218.90;
  1149. } else {
  1150. return 1729.13;
  1151. }
  1152. break;
  1153. case 'RA3':
  1154. if (axis == 'x') {
  1155. return 864.57;
  1156. } else {
  1157. return 1218.90;
  1158. }
  1159. break;
  1160. case 'RA4':
  1161. if (axis == 'x') {
  1162. return 609.45;
  1163. } else {
  1164. return 864.57;
  1165. }
  1166. break;
  1167. case 'SRA0':
  1168. if (axis == 'x') {
  1169. return 2551.18;
  1170. } else {
  1171. return 3628.35;
  1172. }
  1173. break;
  1174. case 'SRA1':
  1175. if (axis == 'x') {
  1176. return 1814.17;
  1177. } else {
  1178. return 2551.18;
  1179. }
  1180. break;
  1181. case 'SRA2':
  1182. if (axis == 'x') {
  1183. return 1275.59;
  1184. } else {
  1185. return 1814.17;
  1186. }
  1187. break;
  1188. case 'SRA3':
  1189. if (axis == 'x') {
  1190. return 907.09;
  1191. } else {
  1192. return 1275.59;
  1193. }
  1194. break;
  1195. case 'SRA4':
  1196. if (axis == 'x') {
  1197. return 637.80;
  1198. } else {
  1199. return 907.09;
  1200. }
  1201. break;
  1202. case 'LETTER':
  1203. if (axis == 'x') {
  1204. return 612.00;
  1205. } else {
  1206. return 792.00;
  1207. }
  1208. break;
  1209. case 'LEGAL':
  1210. if (axis == 'x') {
  1211. return 612.00;
  1212. } else {
  1213. return 1008.00;
  1214. }
  1215. break;
  1216. case 'EXECUTIVE':
  1217. if (axis == 'x') {
  1218. return 521.86;
  1219. } else {
  1220. return 756.00;
  1221. }
  1222. break;
  1223. case 'FOLIO':
  1224. if (axis == 'x') {
  1225. return 612.00;
  1226. } else {
  1227. return 936.00;
  1228. }
  1229. break;
  1230. } // end switch
  1231. return 0;
  1232. }
  1233. /**
  1234. * Unbind all event handlers before tearing down a page
  1235. */
  1236. AJAX.registerTeardown('functions.js', function() {
  1237. $("a.inline_edit_sql").die('click');
  1238. $("input#sql_query_edit_save").die('click');
  1239. $("input#sql_query_edit_discard").die('click');
  1240. $('input.sqlbutton').unbind('click');
  1241. $("#export_type").unbind('change');
  1242. $('#sqlquery').unbind('keydown');
  1243. $('#sql_query_edit').unbind('keydown');
  1244. if (codemirror_inline_editor) {
  1245. // Copy the sql query to the text area to preserve it.
  1246. $('#sql_query_edit').text(codemirror_inline_editor.getValue());
  1247. $(codemirror_inline_editor.getWrapperElement()).unbind('keydown');
  1248. codemirror_inline_editor.toTextArea();
  1249. codemirror_inline_editor = false;
  1250. }
  1251. if (codemirror_editor) {
  1252. $(codemirror_editor.getWrapperElement()).unbind('keydown');
  1253. }
  1254. });
  1255. /**
  1256. * Jquery Coding for inline editing SQL_QUERY
  1257. */
  1258. AJAX.registerOnload('functions.js', function() {
  1259. // If we are coming back to the page by clicking forward button
  1260. // of the browser, bind the code mirror to inline query editor.
  1261. bindCodeMirrorToInlineEditor();
  1262. $("a.inline_edit_sql").live('click', function() {
  1263. if ($('#sql_query_edit').length) {
  1264. // An inline query editor is already open,
  1265. // we don't want another copy of it
  1266. return false;
  1267. }
  1268. var $form = $(this).prev('form');
  1269. var sql_query = $form.find("input[name='sql_query']").val();
  1270. var $inner_sql = $(this).parent().prev().find('.inner_sql');
  1271. var old_text = $inner_sql.html();
  1272. var new_content = "<textarea name=\"sql_query_edit\" id=\"sql_query_edit\">" + escapeHtml(sql_query) + "</textarea>\n";
  1273. new_content += "<input type=\"submit\" id=\"sql_query_edit_save\" class=\"button btnSave\" value=\"" + PMA_messages['strGo'] + "\"/>\n";
  1274. new_content += "<input type=\"button\" id=\"sql_query_edit_discard\" class=\"button btnDiscard\" value=\"" + PMA_messages['strCancel'] + "\"/>\n";
  1275. var $editor_area = $('div#inline_editor');
  1276. if ($editor_area.length == 0) {
  1277. $editor_area = $('<div id="inline_editor_outer"></div>');
  1278. $editor_area.insertBefore($inner_sql);
  1279. }
  1280. $editor_area.html(new_content);
  1281. $inner_sql.hide();
  1282. bindCodeMirrorToInlineEditor();
  1283. return false;
  1284. });
  1285. $("input#sql_query_edit_save").live('click', function() {
  1286. if (codemirror_inline_editor) {
  1287. var sql_query = codemirror_inline_editor.getValue();
  1288. } else {
  1289. var sql_query = $(this).prev().val();
  1290. }
  1291. var $form = $("a.inline_edit_sql").prev('form');
  1292. var $fake_form = $('<form>', {action: 'import.php', method: 'post'})
  1293. .append($form.find("input[name=server], input[name=db], input[name=table], input[name=token]").clone())
  1294. .append($('<input/>', {type: 'hidden', name: 'show_query', value: 1}))
  1295. .append($('<input/>', {type: 'hidden', name: 'is_js_confirmed', value: 0}))
  1296. .append($('<input/>', {type: 'hidden', name: 'sql_query', value: sql_query}));
  1297. if (! checkSqlQuery($fake_form[0])) {
  1298. return false;
  1299. }
  1300. $fake_form.appendTo($('body')).submit();
  1301. });
  1302. $("input#sql_query_edit_discard").live('click', function() {
  1303. $('div#inline_editor_outer')
  1304. .empty()
  1305. .siblings('.inner_sql').show();
  1306. });
  1307. $('input.sqlbutton').click(function(evt) {
  1308. insertQuery(evt.target.id);
  1309. return false;
  1310. });
  1311. $("#export_type").change(function() {
  1312. if ($("#export_type").val()=='svg') {
  1313. $("#show_grid_opt").prop("disabled",true);
  1314. $("#orientation_opt").prop("disabled",true);
  1315. $("#with_doc").prop("disabled",true);
  1316. $("#show_table_dim_opt").removeProp("disabled");
  1317. $("#all_tables_same_width").removeProp("disabled");
  1318. $("#paper_opt").removeProp("disabled");
  1319. $("#show_color_opt").removeProp("disabled");
  1320. //$(this).css("background-color","yellow");
  1321. } else if ($("#export_type").val()=='dia') {
  1322. $("#show_grid_opt").prop("disabled",true);
  1323. $("#with_doc").prop("disabled",true);
  1324. $("#show_table_dim_opt").prop("disabled",true);
  1325. $("#all_tables_same_width").prop("disabled",true);
  1326. $("#paper_opt").removeProp("disabled");
  1327. $("#show_color_opt").removeProp("disabled");
  1328. $("#orientation_opt").removeProp("disabled");
  1329. } else if ($("#export_type").val()=='eps') {
  1330. $("#show_grid_opt").prop("disabled",true);
  1331. $("#orientation_opt").removeProp("disabled");
  1332. $("#with_doc").prop("disabled",true);
  1333. $("#show_table_dim_opt").prop("disabled",true);
  1334. $("#all_tables_same_width").prop("disabled",true);
  1335. $("#paper_opt").prop("disabled",true);
  1336. $("#show_color_opt").prop("disabled",true);
  1337. } else if ($("#export_type").val()=='pdf') {
  1338. $("#show_grid_opt").removeProp("disabled");
  1339. $("#orientation_opt").removeProp("disabled");
  1340. $("#with_doc").removeProp("disabled");
  1341. $("#show_table_dim_opt").removeProp("disabled");
  1342. $("#all_tables_same_width").removeProp("disabled");
  1343. $("#paper_opt").removeProp("disabled");
  1344. $("#show_color_opt").removeProp("disabled");
  1345. } else {
  1346. // nothing
  1347. }
  1348. });
  1349. if ($('#input_username')) {
  1350. if ($('#input_username').val() == '') {
  1351. $('#input_username').focus();
  1352. } else {
  1353. $('#input_password').focus();
  1354. }
  1355. }
  1356. });
  1357. /**
  1358. * Binds the CodeMirror to the text area used to inline edit a query.
  1359. */
  1360. function bindCodeMirrorToInlineEditor() {
  1361. var $inline_editor = $('#sql_query_edit');
  1362. if ($inline_editor.length > 0) {
  1363. if (typeof CodeMirror !== 'undefined') {
  1364. var height = $('#sql_query_edit').css('height');
  1365. codemirror_inline_editor = CodeMirror.fromTextArea($inline_editor[0], {
  1366. lineNumbers: true,
  1367. matchBrackets: true,
  1368. indentUnit: 4,
  1369. mode: "text/x-mysql",
  1370. lineWrapping: true
  1371. });
  1372. codemirror_inline_editor.getScrollerElement().style.height = height;
  1373. codemirror_inline_editor.refresh();
  1374. codemirror_inline_editor.focus();
  1375. $(codemirror_inline_editor.getWrapperElement()).bind(
  1376. 'keydown',
  1377. catchKeypressesFromSqlTextboxes
  1378. );
  1379. } else {
  1380. $inline_editor.focus().bind(
  1381. 'keydown',
  1382. catchKeypressesFromSqlTextboxes
  1383. );
  1384. }
  1385. }
  1386. }
  1387. function catchKeypressesFromSqlTextboxes(event) {
  1388. // ctrl-enter is 10 in chrome and ie, but 13 in ff
  1389. if (event.ctrlKey && (event.keyCode == 13 || event.keyCode == 10)) {
  1390. if ($('#sql_query_edit').length > 0) {
  1391. $("#sql_query_edit_save").trigger('click');
  1392. } else if ($('#sqlquery').length > 0) {
  1393. $("#button_submit_query").trigger('click');
  1394. }
  1395. }
  1396. }
  1397. /**
  1398. * Show a message on the top of the page for an Ajax request
  1399. *
  1400. * Sample usage:
  1401. *
  1402. * 1) var $msg = PMA_ajaxShowMessage();
  1403. * This will show a message that reads "Loading...". Such a message will not
  1404. * disappear automatically and cannot be dismissed by the user. To remove this
  1405. * message either the PMA_ajaxRemoveMessage($msg) function must be called or
  1406. * another message must be show with PMA_ajaxShowMessage() function.
  1407. *
  1408. * 2) var $msg = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
  1409. * This is a special case. The behaviour is same as above,
  1410. * just with a different message
  1411. *
  1412. * 3) var $msg = PMA_ajaxShowMessage('The operation was successful');
  1413. * This will show a message that will disappear automatically and it can also
  1414. * be dismissed by the user.
  1415. *
  1416. * 4) var $msg = PMA_ajaxShowMessage('Some error', false);
  1417. * This will show a message that will not disappear automatically, but it
  1418. * can be dismissed by the user after he has finished reading it.
  1419. *
  1420. * @param string message string containing the message to be shown.
  1421. * optional, defaults to 'Loading...'
  1422. * @param mixed timeout number of milliseconds for the message to be visible
  1423. * optional, defaults to 5000. If set to 'false', the
  1424. * notification will never disappear
  1425. * @return jQuery object jQuery Element that holds the message div
  1426. * this object can be passed to PMA_ajaxRemoveMessage()
  1427. * to remove the notification
  1428. */
  1429. function PMA_ajaxShowMessage(message, timeout)
  1430. {
  1431. /**
  1432. * @var self_closing Whether the notification will automatically disappear
  1433. */
  1434. var self_closing = true;
  1435. /**
  1436. * @var dismissable Whether the user will be able to remove
  1437. * the notification by clicking on it
  1438. */
  1439. var dismissable = true;
  1440. // Handle the case when a empty data.message is passed.
  1441. // We don't want the empty message
  1442. if (message == '') {
  1443. return true;
  1444. } else if (! message) {
  1445. // If the message is undefined, show the default
  1446. message = PMA_messages['strLoading'];
  1447. dismissable = false;
  1448. self_closing = false;
  1449. } else if (message == PMA_messages['strProcessingRequest']) {
  1450. // This is another case where the message should not disappear
  1451. dismissable = false;
  1452. self_closing = false;
  1453. }
  1454. // Figure out whether (or after how long) to remove the notification
  1455. if (timeout == undefined) {
  1456. timeout = 5000;
  1457. } else if (timeout === false) {
  1458. self_closing = false;
  1459. }
  1460. // Create a parent element for the AJAX messages, if necessary
  1461. if ($('#loading_parent').length == 0) {
  1462. $('<div id="loading_parent"></div>')
  1463. .prependTo("body");
  1464. }
  1465. // Update message count to create distinct message elements every time
  1466. ajax_message_count++;
  1467. // Remove all old messages, if any
  1468. $("span.ajax_notification[id^=ajax_message_num]").remove();
  1469. /**
  1470. * @var $retval a jQuery object containing the reference
  1471. * to the created AJAX message
  1472. */
  1473. var $retval = $(
  1474. '<span class="ajax_notification" id="ajax_message_num_'
  1475. + ajax_message_count +
  1476. '"></span>'
  1477. )
  1478. .hide()
  1479. .appendTo("#loading_parent")
  1480. .html(message)
  1481. .show();
  1482. // If the notification is self-closing we should create a callback to remove it
  1483. if (self_closing) {
  1484. $retval
  1485. .delay(timeout)
  1486. .fadeOut('medium', function() {
  1487. if ($(this).is('.dismissable')) {
  1488. $(this).tooltip('destroy');
  1489. }
  1490. // Remove the notification
  1491. $(this).remove();
  1492. });
  1493. }
  1494. // If the notification is dismissable we need to add the relevant class to it
  1495. // and add a tooltip so that the users know that it can be removed
  1496. if (dismissable) {
  1497. $retval.addClass('dismissable').css('cursor', 'pointer');
  1498. /**
  1499. * Add a tooltip to the notification to let the user know that (s)he
  1500. * can dismiss the ajax notification by clicking on it.
  1501. */
  1502. PMA_tooltip(
  1503. $retval,
  1504. 'span',
  1505. PMA_messages['strDismiss']
  1506. );
  1507. }
  1508. return $retval;
  1509. }
  1510. /**
  1511. * Removes the message shown for an Ajax operation when it's completed
  1512. *
  1513. * @param jQuery object jQuery Element that holds the notification
  1514. *
  1515. * @return nothing
  1516. */
  1517. function PMA_ajaxRemoveMessage($this_msgbox)
  1518. {
  1519. if ($this_msgbox != undefined && $this_msgbox instanceof jQuery) {
  1520. $this_msgbox
  1521. .stop(true, true)
  1522. .fadeOut('medium');
  1523. if ($this_msgbox.is('.dismissable')) {
  1524. if ($.isFunction($this_msgbox.tooltip)) {
  1525. $this_msgbox.tooltip('destroy');
  1526. }
  1527. } else {
  1528. $this_msgbox.remove();
  1529. }
  1530. }
  1531. }
  1532. // This event only need to be fired once after the initial page load
  1533. $(function() {
  1534. /**
  1535. * Allows the user to dismiss a notification
  1536. * created with PMA_ajaxShowMessage()
  1537. */
  1538. $('span.ajax_notification.dismissable').live('click', function () {
  1539. PMA_ajaxRemoveMessage($(this));
  1540. });
  1541. /**
  1542. * The below two functions hide the "Dismiss notification" tooltip when a user
  1543. * is hovering a link or button that is inside an ajax message
  1544. */
  1545. $('span.ajax_notification a, span.ajax_notification button, span.ajax_notification input')
  1546. .live('mouseover', function () {
  1547. $(this).parents('span.ajax_notification').tooltip('disable');
  1548. })
  1549. .live('mouseout', function () {
  1550. $(this).parents('span.ajax_notification').tooltip('enable');
  1551. });
  1552. });
  1553. /**
  1554. * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
  1555. */
  1556. function PMA_showNoticeForEnum(selectElement)
  1557. {
  1558. var enum_notice_id = selectElement.attr("id").split("_")[1];
  1559. enum_notice_id += "_" + (parseInt(selectElement.attr("id").split("_")[2]) + 1);
  1560. var selectedType = selectElement.val();
  1561. if (selectedType == "ENUM" || selectedType == "SET") {
  1562. $("p#enum_notice_" + enum_notice_id).show();
  1563. } else {
  1564. $("p#enum_notice_" + enum_notice_id).hide();
  1565. }
  1566. }
  1567. /*
  1568. * Creates a Profiling Chart with jqplot. Used in sql.js
  1569. * and in server_status_monitor.js
  1570. */
  1571. function PMA_createProfilingChartJqplot(target, data)
  1572. {
  1573. return $.jqplot(target, [data],
  1574. {
  1575. seriesDefaults: {
  1576. renderer: $.jqplot.PieRenderer,
  1577. rendererOptions: {
  1578. showDataLabels: true
  1579. }
  1580. },
  1581. legend: {
  1582. show: true,
  1583. location: 'e'
  1584. },
  1585. // from http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines#Color_Palette
  1586. seriesColors: [
  1587. '#fce94f',
  1588. '#fcaf3e',
  1589. '#e9b96e',
  1590. '#8ae234',
  1591. '#729fcf',
  1592. '#ad7fa8',
  1593. '#ef2929',
  1594. '#eeeeec',
  1595. '#888a85',
  1596. '#c4a000',
  1597. '#ce5c00',
  1598. '#8f5902',
  1599. '#4e9a06',
  1600. '#204a87',
  1601. '#5c3566',
  1602. '#a40000',
  1603. '#babdb6',
  1604. '#2e3436'
  1605. ]
  1606. }
  1607. );
  1608. }
  1609. /**
  1610. * Formats a profiling duration nicely (in us and ms time). Used in server_status.js
  1611. *
  1612. * @param integer Number to be formatted, should be in the range of microsecond to second
  1613. * @param integer Accuracy, how many numbers right to the comma should be
  1614. * @return string The formatted number
  1615. */
  1616. function PMA_prettyProfilingNum(num, acc)
  1617. {
  1618. if (!acc) {
  1619. acc = 2;
  1620. }
  1621. acc = Math.pow(10, acc);
  1622. if (num * 1000 < 0.1) {
  1623. num = Math.round(acc * (num * 1000 * 1000)) / acc + 'µ';
  1624. } else if (num < 0.1) {
  1625. num = Math.round(acc * (num * 1000)) / acc + 'm';
  1626. } else {
  1627. num = Math.round(acc * num) / acc;
  1628. }
  1629. return num + 's';
  1630. }
  1631. /**
  1632. * Formats a SQL Query nicely with newlines and indentation. Depends on Codemirror and MySQL Mode!
  1633. *
  1634. * @param string Query to be formatted
  1635. * @return string The formatted query
  1636. */
  1637. function PMA_SQLPrettyPrint(string)
  1638. {
  1639. if (typeof CodeMirror == 'undefined') {
  1640. return string;
  1641. }
  1642. var mode = CodeMirror.getMode({},"text/x-mysql");
  1643. var stream = new CodeMirror.StringStream(string);
  1644. var state = mode.startState();
  1645. var token, tokens = [];
  1646. var output = '';
  1647. var tabs = function(cnt) {
  1648. var ret = '';
  1649. for (var i=0; i<4*cnt; i++) {
  1650. ret += " ";
  1651. }
  1652. return ret;
  1653. };
  1654. // "root-level" statements
  1655. var statements = {
  1656. 'select': ['select', 'from','on','where','having','limit','order by','group by'],
  1657. 'update': ['update', 'set','where'],
  1658. 'insert into': ['insert into', 'values']
  1659. };
  1660. // don't put spaces before these tokens
  1661. var spaceExceptionsBefore = { ';':true, ',': true, '.': true, '(': true };
  1662. // don't put spaces after these tokens
  1663. var spaceExceptionsAfter = { '.': true };
  1664. // Populate tokens array
  1665. var str='';
  1666. while (! stream.eol()) {
  1667. stream.start = stream.pos;
  1668. token = mode.token(stream, state);
  1669. if (token != null) {
  1670. tokens.push([token, stream.current().toLowerCase()]);
  1671. }
  1672. }
  1673. var currentStatement = tokens[0][1];
  1674. if (! statements[currentStatement]) {
  1675. return string;
  1676. }
  1677. // Holds all currently opened code blocks (statement, function or generic)
  1678. var blockStack = [];
  1679. // Holds the type of block from last iteration (the current is in blockStack[0])
  1680. var previousBlock;
  1681. // If a new code block is found, newBlock contains its type for one iteration and vice versa for endBlock
  1682. var newBlock, endBlock;
  1683. // How much to indent in the current line
  1684. var indentLevel = 0;
  1685. // Holds the "root-level" statements
  1686. var statementPart, lastStatementPart = statements[currentStatement][0];
  1687. blockStack.unshift('statement');
  1688. // Iterate through every token and format accordingly
  1689. for (var i = 0; i < tokens.length; i++) {
  1690. previousBlock = blockStack[0];
  1691. // New block => push to stack
  1692. if (tokens[i][1] == '(') {
  1693. if (i < tokens.length - 1 && tokens[i+1][0] == 'statement-verb') {
  1694. blockStack.unshift(newBlock = 'statement');
  1695. } else if (i > 0 && tokens[i-1][0] == 'builtin') {
  1696. blockStack.unshift(newBlock = 'function');
  1697. } else {
  1698. blockStack.unshift(newBlock = 'generic');
  1699. }
  1700. } else {
  1701. newBlock = null;
  1702. }
  1703. // Block end => pop from stack
  1704. if (tokens[i][1] == ')') {
  1705. endBlock = blockStack[0];
  1706. blockStack.shift();
  1707. } else {
  1708. endBlock = null;
  1709. }
  1710. // A subquery is starting
  1711. if (i > 0 && newBlock == 'statement') {
  1712. indentLevel++;
  1713. output += "\n" + tabs(indentLevel) + tokens[i][1] + ' ' + tokens[i+1][1].toUpperCase() + "\n" + tabs(indentLevel + 1);
  1714. currentStatement = tokens[i+1][1];
  1715. i++;
  1716. continue;
  1717. }
  1718. // A subquery is ending
  1719. if (endBlock == 'statement' && indentLevel > 0) {
  1720. output += "\n" + tabs(indentLevel);
  1721. indentLevel--;
  1722. }
  1723. // One less indentation for statement parts (from, where, order by, etc.) and a newline
  1724. statementPart = statements[currentStatement].indexOf(tokens[i][1]);
  1725. if (statementPart != -1) {
  1726. if (i > 0) {
  1727. output += "\n";
  1728. }
  1729. output += tabs(indentLevel) + tokens[i][1].toUpperCase();
  1730. output += "\n" + tabs(indentLevel + 1);
  1731. lastStatementPart = tokens[i][1];
  1732. }
  1733. // Normal indentatin and spaces for everything else
  1734. else {
  1735. if (! spaceExceptionsBefore[tokens[i][1]]
  1736. && ! (i > 0 && spaceExceptionsAfter[tokens[i-1][1]])
  1737. && output.charAt(output.length -1) != ' ' ) {
  1738. output += " ";
  1739. }
  1740. if (tokens[i][0] == 'keyword') {
  1741. output += tokens[i][1].toUpperCase();
  1742. } else {
  1743. output += tokens[i][1];
  1744. }
  1745. }
  1746. // split columns in select and 'update set' clauses, but only inside statements blocks
  1747. if (( lastStatementPart == 'select' || lastStatementPart == 'where' || lastStatementPart == 'set')
  1748. && tokens[i][1]==',' && blockStack[0] == 'statement') {
  1749. output += "\n" + tabs(indentLevel + 1);
  1750. }
  1751. // split conditions in where clauses, but only inside statements blocks
  1752. if (lastStatementPart == 'where'
  1753. && (tokens[i][1]=='and' || tokens[i][1]=='or' || tokens[i][1]=='xor')) {
  1754. if (blockStack[0] == 'statement') {
  1755. output += "\n" + tabs(indentLevel + 1);
  1756. }
  1757. // Todo: Also split and or blocks in newlines & identation++
  1758. //if (blockStack[0] == 'generic')
  1759. // output += ...
  1760. }
  1761. }
  1762. return output;
  1763. }
  1764. /**
  1765. * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
  1766. * return a jQuery object yet and hence cannot be chained
  1767. *
  1768. * @param string question
  1769. * @param string url URL to be passed to the callbackFn to make
  1770. * an Ajax call to
  1771. * @param function callbackFn callback to execute after user clicks on OK
  1772. */
  1773. jQuery.fn.PMA_confirm = function(question, url, callbackFn) {
  1774. var confirmState = PMA_commonParams.get('confirm');
  1775. // when the Confirm directive is set to false in config.inc.php
  1776. // and not changed in user prefs, confirmState is ""
  1777. // when it's unticked in user prefs, confirmState is 1
  1778. if (confirmState === "" || confirmState === "1") {
  1779. // user does not want to confirm
  1780. if ($.isFunction(callbackFn)) {
  1781. callbackFn.call(this, url);
  1782. return true;
  1783. }
  1784. }
  1785. if (PMA_messages['strDoYouReally'] == '') {
  1786. return true;
  1787. }
  1788. /**
  1789. * @var button_options Object that stores the options passed to jQueryUI
  1790. * dialog
  1791. */
  1792. var button_options = {};
  1793. button_options[PMA_messages['strOK']] = function() {
  1794. $(this).dialog("close");
  1795. if ($.isFunction(callbackFn)) {
  1796. callbackFn.call(this, url);
  1797. }
  1798. };
  1799. button_options[PMA_messages['strCancel']] = function() {
  1800. $(this).dialog("close");
  1801. };
  1802. $('<div/>', {'id':'confirm_dialog'})
  1803. .prepend(question)
  1804. .dialog({
  1805. buttons: button_options,
  1806. close: function () {
  1807. $(this).remove();
  1808. },
  1809. modal: true
  1810. });
  1811. };
  1812. /**
  1813. * jQuery function to sort a table's body after a new row has been appended to it.
  1814. * Also fixes the even/odd classes of the table rows at the end.
  1815. *
  1816. * @param string text_selector string to select the sortKey's text
  1817. *
  1818. * @return jQuery Object for chaining purposes
  1819. */
  1820. jQuery.fn.PMA_sort_table = function(text_selector) {
  1821. return this.each(function() {
  1822. /**
  1823. * @var table_body Object referring to the table's <tbody> element
  1824. */
  1825. var table_body = $(this);
  1826. /**
  1827. * @var rows Object referring to the collection of rows in {@link table_body}
  1828. */
  1829. var rows = $(this).find('tr').get();
  1830. //get the text of the field that we will sort by
  1831. $.each(rows, function(index, row) {
  1832. row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
  1833. });
  1834. //get the sorted order
  1835. rows.sort(function(a, b) {
  1836. if (a.sortKey < b.sortKey) {
  1837. return -1;
  1838. }
  1839. if (a.sortKey > b.sortKey) {
  1840. return 1;
  1841. }
  1842. return 0;
  1843. });
  1844. //pull out each row from the table and then append it according to it's order
  1845. $.each(rows, function(index, row) {
  1846. $(table_body).append(row);
  1847. row.sortKey = null;
  1848. });
  1849. //Re-check the classes of each row
  1850. $(this).find('tr:odd')
  1851. .removeClass('even').addClass('odd')
  1852. .end()
  1853. .find('tr:even')
  1854. .removeClass('odd').addClass('even');
  1855. });
  1856. };
  1857. /**
  1858. * Unbind all event handlers before tearing down a page
  1859. */
  1860. AJAX.registerTeardown('functions.js', function() {
  1861. $("#create_table_form_minimal.ajax").die('submit');
  1862. $("form.create_table_form.ajax").die('submit');
  1863. $("form.create_table_form.ajax input[name=submit_num_fields]").die('click');
  1864. $("form.create_table_form.ajax input").die('keyup');
  1865. });
  1866. /**
  1867. * jQuery coding for 'Create Table'. Used on db_operations.php,
  1868. * db_structure.php and db_tracking.php (i.e., wherever
  1869. * libraries/display_create_table.lib.php is used)
  1870. *
  1871. * Attach Ajax Event handlers for Create Table
  1872. */
  1873. AJAX.registerOnload('functions.js', function() {
  1874. /**
  1875. * Attach event handler for submission of create table form (save)
  1876. */
  1877. $("form.create_table_form.ajax").live('submit', function(event) {
  1878. event.preventDefault();
  1879. /**
  1880. * @var the_form object referring to the create table form
  1881. */
  1882. var $form = $(this);
  1883. /*
  1884. * First validate the form; if there is a problem, avoid submitting it
  1885. *
  1886. * checkTableEditForm() needs a pure element and not a jQuery object,
  1887. * this is why we pass $form[0] as a parameter (the jQuery object
  1888. * is actually an array of DOM elements)
  1889. */
  1890. if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
  1891. PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
  1892. PMA_prepareForAjaxRequest($form);
  1893. //User wants to submit the form
  1894. $.post($form.attr('action'), $form.serialize() + "&do_save_data=1", function(data) {
  1895. if (data.success == true) {
  1896. $('#properties_message')
  1897. .removeClass('error')
  1898. .html('');
  1899. PMA_ajaxShowMessage(data.message);
  1900. // Only if the create table dialog (distinct panel) exists
  1901. if ($("#create_table_dialog").length > 0) {
  1902. $("#create_table_dialog").dialog("close").remove();
  1903. }
  1904. $('#tableslistcontainer').before(data.formatted_sql);
  1905. /**
  1906. * @var tables_table Object referring to the <tbody> element that holds the list of tables
  1907. */
  1908. var tables_table = $("#tablesForm").find("tbody").not("#tbl_summary_row");
  1909. // this is the first table created in this db
  1910. if (tables_table.length == 0) {
  1911. PMA_commonActions.refreshMain(
  1912. PMA_commonParams.get('opendb_url')
  1913. );
  1914. } else {
  1915. /**
  1916. * @var curr_last_row Object referring to the last <tr> element in {@link tables_table}
  1917. */
  1918. var curr_last_row = $(tables_table).find('tr:last');
  1919. /**
  1920. * @var curr_last_row_index_string String containing the index of {@link curr_last_row}
  1921. */
  1922. var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
  1923. /**
  1924. * @var curr_last_row_index Index of {@link curr_last_row}
  1925. */
  1926. var curr_last_row_index = parseFloat(curr_last_row_index_string);
  1927. /**
  1928. * @var new_last_row_index Index of the new row to be appended to {@link tables_table}
  1929. */
  1930. var new_last_row_index = curr_last_row_index + 1;
  1931. /**
  1932. * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
  1933. */
  1934. var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
  1935. data.new_table_string = data.new_table_string.replace(/checkbox_tbl_/, new_last_row_id);
  1936. //append to table
  1937. $(data.new_table_string)
  1938. .appendTo(tables_table);
  1939. //Sort the table
  1940. $(tables_table).PMA_sort_table('th');
  1941. // Adjust summary row
  1942. PMA_adjustTotals();
  1943. }
  1944. //Refresh navigation as a new table has been added
  1945. PMA_reloadNavigation();
  1946. } else {
  1947. PMA_ajaxShowMessage(
  1948. '<div class="error">' + data.error + '</div>',
  1949. false
  1950. );
  1951. }
  1952. }); // end $.post()
  1953. } // end if (checkTableEditForm() )
  1954. }); // end create table form (save)
  1955. /**
  1956. * Attach event handler for create table form (add fields)
  1957. */
  1958. $("form.create_table_form.ajax input[name=submit_num_fields]").live('click', function(event) {
  1959. event.preventDefault();
  1960. /**
  1961. * @var the_form object referring to the create table form
  1962. */
  1963. var $form = $(this).closest('form');
  1964. var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
  1965. PMA_prepareForAjaxRequest($form);
  1966. //User wants to add more fields to the table
  1967. $.post($form.attr('action'), $form.serialize() + "&submit_num_fields=1", function(data) {
  1968. if (data.success) {
  1969. $("#page_content").html(data.message);
  1970. PMA_verifyColumnsProperties();
  1971. PMA_ajaxRemoveMessage($msgbox);
  1972. } else {
  1973. PMA_ajaxShowMessage(data.error);
  1974. }
  1975. }); //end $.post()
  1976. }); // end create table form (add fields)
  1977. $("form.create_table_form.ajax input").live('keydown', function (event) {
  1978. if (event.keyCode == 13) {
  1979. event.preventDefault();
  1980. event.stopImmediatePropagation();
  1981. $(this)
  1982. .closest('form')
  1983. .append('<input type="hidden" name="do_save_data" value="1" />')
  1984. .submit();
  1985. }
  1986. });
  1987. });
  1988. /**
  1989. * Unbind all event handlers before tearing down a page
  1990. */
  1991. AJAX.registerTeardown('functions.js', function() {
  1992. $("#copyTable.ajax").die('submit');
  1993. $("#moveTableForm").die('submit');
  1994. $("#tableOptionsForm").die('submit');
  1995. $("#tbl_maintenance li a.maintain_action.ajax").die('click');
  1996. });
  1997. /**
  1998. * jQuery coding for 'Table operations'. Used on tbl_operations.php
  1999. * Attach Ajax Event handlers for Table operations
  2000. */
  2001. AJAX.registerOnload('functions.js', function() {
  2002. /**
  2003. *Ajax action for submitting the "Copy table"
  2004. **/
  2005. $("#copyTable.ajax").live('submit', function(event) {
  2006. event.preventDefault();
  2007. var $form = $(this);
  2008. PMA_prepareForAjaxRequest($form);
  2009. $.post($form.attr('action'), $form.serialize()+"&submit_copy=Go", function(data) {
  2010. if (data.success == true) {
  2011. if ($form.find("input[name='switch_to_new']").prop('checked')) {
  2012. PMA_commonParams.set(
  2013. 'db',
  2014. data.db
  2015. );
  2016. PMA_commonParams.set(
  2017. 'table',
  2018. $form.find("input[name='new_name']").val()
  2019. );
  2020. PMA_commonActions.refreshMain(false, function () {
  2021. PMA_ajaxShowMessage(data.message);
  2022. });
  2023. } else {
  2024. PMA_ajaxShowMessage(data.message);
  2025. }
  2026. // Refresh navigation when the table is copied
  2027. PMA_reloadNavigation();
  2028. } else {
  2029. PMA_ajaxShowMessage(data.error, false);
  2030. }
  2031. }); // end $.post()
  2032. });//end of copyTable ajax submit
  2033. /**
  2034. *Ajax action for submitting the "Move table"
  2035. */
  2036. $("#moveTableForm").live('submit', function(event) {
  2037. event.preventDefault();
  2038. var $form = $(this);
  2039. var db = $form.find('select[name=target_db]').val();
  2040. var tbl = $form.find('input[name=new_name]').val();
  2041. PMA_prepareForAjaxRequest($form);
  2042. $.post($form.attr('action'), $form.serialize()+"&submit_move=1", function(data) {
  2043. if (data.success == true) {
  2044. PMA_commonParams.set('db', db);
  2045. PMA_commonParams.set('table', tbl);
  2046. PMA_commonActions.refreshMain(false, function () {
  2047. PMA_ajaxShowMessage(data.message);
  2048. });
  2049. // Refresh navigation when the table is copied
  2050. PMA_reloadNavigation();
  2051. } else {
  2052. PMA_ajaxShowMessage(data.error, false);
  2053. }
  2054. }); // end $.post()
  2055. });
  2056. /**
  2057. * Ajax action for submitting the "Table options"
  2058. */
  2059. $("#tableOptionsForm").live('submit', function(event) {
  2060. event.preventDefault();
  2061. event.stopPropagation();
  2062. var $form = $(this);
  2063. var $tblNameField = $form.find('input[name=new_name]');
  2064. if ($tblNameField.val() !== $tblNameField[0].defaultValue) {
  2065. // reload page and navigation if the table has been renamed
  2066. PMA_prepareForAjaxRequest($form);
  2067. var tbl = $tblNameField.val();
  2068. $.post($form.attr('action'), $form.serialize(), function(data) {
  2069. if (data.success == true) {
  2070. PMA_commonParams.set('table', tbl);
  2071. PMA_commonActions.refreshMain(false, function() {
  2072. $('#page_content').html(data.message);
  2073. });
  2074. } else {
  2075. PMA_ajaxShowMessage(data.error, false);
  2076. }
  2077. }); // end $.post()
  2078. } else {
  2079. $form.removeClass('ajax').submit().addClass('ajax');
  2080. }
  2081. });
  2082. /**
  2083. *Ajax events for actions in the "Table maintenance"
  2084. **/
  2085. $("#tbl_maintenance li a.maintain_action.ajax").live('click', function(event) {
  2086. event.preventDefault();
  2087. if ($("#sqlqueryresults").length != 0) {
  2088. $("#sqlqueryresults").remove();
  2089. }
  2090. if ($("#result_query").length != 0) {
  2091. $("#result_query").remove();
  2092. }
  2093. //variables which stores the common attributes
  2094. $.post($(this).attr('href'), { ajax_request: 1 }, function(data) {
  2095. function scrollToTop() {
  2096. $('html, body').animate({ scrollTop: 0 });
  2097. }
  2098. if (data.success == true && data.sql_query != undefined) {
  2099. PMA_ajaxShowMessage(data.message);
  2100. $("<div id='sqlqueryresults' class='ajax'></div>").prependTo("#page_content");
  2101. $("#sqlqueryresults").html(data.sql_query);
  2102. scrollToTop();
  2103. } else if (data.success == true) {
  2104. var $temp_div = $("<div id='temp_div'></div>");
  2105. $temp_div.html(data.message);
  2106. var $success = $temp_div.find("#result_query .success");
  2107. PMA_ajaxShowMessage($success);
  2108. $("<div id='sqlqueryresults' class='ajax'></div>").prependTo("#page_content");
  2109. $("#sqlqueryresults").html(data.message);
  2110. PMA_init_slider();
  2111. $("#sqlqueryresults").children("fieldset,br").remove();
  2112. scrollToTop();
  2113. } else {
  2114. var $temp_div = $("<div id='temp_div'></div>");
  2115. $temp_div.html(data.error);
  2116. var $error = $temp_div.find("code").addClass("error");
  2117. PMA_ajaxShowMessage($error, false);
  2118. }
  2119. }); // end $.post()
  2120. });//end of table maintanance ajax click
  2121. }); //end $(document).ready for 'Table operations'
  2122. /**
  2123. * Unbind all event handlers before tearing down a page
  2124. */
  2125. AJAX.registerTeardown('functions.js', function() {
  2126. $("#drop_db_anchor.ajax").die('click');
  2127. });
  2128. /**
  2129. * Attach Ajax event handlers for Drop Database. Moved here from db_structure.js
  2130. * as it was also required on db_create.php
  2131. */
  2132. AJAX.registerOnload('functions.js', function() {
  2133. $("#drop_db_anchor.ajax").live('click', function(event) {
  2134. event.preventDefault();
  2135. /**
  2136. * @var question String containing the question to be asked for confirmation
  2137. */
  2138. var question = PMA_messages.strDropDatabaseStrongWarning + ' ';
  2139. question += $.sprintf(
  2140. PMA_messages.strDoYouReally,
  2141. 'DROP DATABASE ' + escapeHtml(PMA_commonParams.get('db'))
  2142. );
  2143. $(this).PMA_confirm(question, $(this).attr('href'), function(url) {
  2144. PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
  2145. $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
  2146. if (data.success) {
  2147. //Database deleted successfully, refresh both the frames
  2148. PMA_reloadNavigation();
  2149. PMA_commonParams.set('db', '');
  2150. PMA_commonActions.refreshMain(
  2151. 'server_databases.php',
  2152. function () {
  2153. PMA_ajaxShowMessage(data.message);
  2154. }
  2155. );
  2156. } else {
  2157. PMA_ajaxShowMessage(data.error, false);
  2158. }
  2159. });
  2160. });
  2161. });
  2162. }); // end of $() for Drop Database
  2163. /**
  2164. * Validates the password field in a form
  2165. *
  2166. * @see PMA_messages['strPasswordEmpty']
  2167. * @see PMA_messages['strPasswordNotSame']
  2168. * @param object $the_form The form to be validated
  2169. * @return bool
  2170. */
  2171. function PMA_checkPassword($the_form)
  2172. {
  2173. // Did the user select 'no password'?
  2174. if ($the_form.find('#nopass_1').is(':checked')) {
  2175. return true;
  2176. } else {
  2177. var $pred = $the_form.find('#select_pred_password');
  2178. if ($pred.length && ($pred.val() == 'none' || $pred.val() == 'keep')) {
  2179. return true;
  2180. }
  2181. }
  2182. var $password = $the_form.find('input[name=pma_pw]');
  2183. var $password_repeat = $the_form.find('input[name=pma_pw2]');
  2184. var alert_msg = false;
  2185. if ($password.val() == '') {
  2186. alert_msg = PMA_messages['strPasswordEmpty'];
  2187. } else if ($password.val() != $password_repeat.val()) {
  2188. alert_msg = PMA_messages['strPasswordNotSame'];
  2189. }
  2190. if (alert_msg) {
  2191. alert(alert_msg);
  2192. $password.val('');
  2193. $password_repeat.val('');
  2194. $password.focus();
  2195. return false;
  2196. }
  2197. return true;
  2198. }
  2199. /**
  2200. * Unbind all event handlers before tearing down a page
  2201. */
  2202. AJAX.registerTeardown('functions.js', function() {
  2203. $('#change_password_anchor.ajax').die('click');
  2204. });
  2205. /**
  2206. * Attach Ajax event handlers for 'Change Password' on index.php
  2207. */
  2208. AJAX.registerOnload('functions.js', function() {
  2209. /**
  2210. * Attach Ajax event handler on the change password anchor
  2211. */
  2212. $('#change_password_anchor.ajax').live('click', function(event) {
  2213. event.preventDefault();
  2214. var $msgbox = PMA_ajaxShowMessage();
  2215. /**
  2216. * @var button_options Object containing options to be passed to jQueryUI's dialog
  2217. */
  2218. var button_options = {};
  2219. button_options[PMA_messages['strGo']] = function() {
  2220. event.preventDefault();
  2221. /**
  2222. * @var $the_form Object referring to the change password form
  2223. */
  2224. var $the_form = $("#change_password_form");
  2225. if (! PMA_checkPassword($the_form)) {
  2226. return false;
  2227. }
  2228. /**
  2229. * @var this_value String containing the value of the submit button.
  2230. * Need to append this for the change password form on Server Privileges
  2231. * page to work
  2232. */
  2233. var this_value = $(this).val();
  2234. var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
  2235. $the_form.append('<input type="hidden" name="ajax_request" value="true" />');
  2236. $.post($the_form.attr('action'), $the_form.serialize() + '&change_pw='+ this_value, function(data) {
  2237. if (data.success == true) {
  2238. $("#page_content").prepend(data.message);
  2239. $("#change_password_dialog").hide().remove();
  2240. $("#edit_user_dialog").dialog("close").remove();
  2241. PMA_ajaxRemoveMessage($msgbox);
  2242. }
  2243. else {
  2244. PMA_ajaxShowMessage(data.error, false);
  2245. }
  2246. }); // end $.post()
  2247. };
  2248. button_options[PMA_messages['strCancel']] = function() {
  2249. $(this).dialog('close');
  2250. };
  2251. $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
  2252. if (data.success) {
  2253. $('<div id="change_password_dialog"></div>')
  2254. .dialog({
  2255. title: PMA_messages['strChangePassword'],
  2256. width: 600,
  2257. close: function(ev, ui) {
  2258. $(this).remove();
  2259. },
  2260. buttons : button_options,
  2261. modal: true
  2262. })
  2263. .append(data.message);
  2264. // for this dialog, we remove the fieldset wrapping due to double headings
  2265. $("fieldset#fieldset_change_password")
  2266. .find("legend").remove().end()
  2267. .find("table.noclick").unwrap().addClass("some-margin")
  2268. .find("input#text_pma_pw").focus();
  2269. displayPasswordGenerateButton();
  2270. $('#fieldset_change_password_footer').hide();
  2271. PMA_ajaxRemoveMessage($msgbox);
  2272. $('#change_password_form').bind('submit', function (e) {
  2273. e.preventDefault();
  2274. $(this)
  2275. .closest('.ui-dialog')
  2276. .find('.ui-dialog-buttonpane .ui-button')
  2277. .first()
  2278. .click();
  2279. });
  2280. } else {
  2281. PMA_ajaxShowMessage(data.error, false);
  2282. }
  2283. }); // end $.get()
  2284. }); // end handler for change password anchor
  2285. }); // end $() for Change Password
  2286. /**
  2287. * Unbind all event handlers before tearing down a page
  2288. */
  2289. AJAX.registerTeardown('functions.js', function() {
  2290. $("select.column_type").die('change');
  2291. $("select.default_type").die('change');
  2292. $('input.allow_null').die('change');
  2293. });
  2294. /**
  2295. * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
  2296. * the page loads and when the selected data type changes
  2297. */
  2298. AJAX.registerOnload('functions.js', function() {
  2299. // is called here for normal page loads and also when opening
  2300. // the Create table dialog
  2301. PMA_verifyColumnsProperties();
  2302. //
  2303. // needs live() to work also in the Create Table dialog
  2304. $("select.column_type").live('change', function() {
  2305. PMA_showNoticeForEnum($(this));
  2306. });
  2307. $("select.default_type").live('change', function() {
  2308. PMA_hideShowDefaultValue($(this));
  2309. });
  2310. $('input.allow_null').live('change', function() {
  2311. PMA_validateDefaultValue($(this));
  2312. });
  2313. });
  2314. function PMA_verifyColumnsProperties()
  2315. {
  2316. $("select.column_type").each(function() {
  2317. PMA_showNoticeForEnum($(this));
  2318. });
  2319. $("select.default_type").each(function() {
  2320. PMA_hideShowDefaultValue($(this));
  2321. });
  2322. }
  2323. /**
  2324. * Hides/shows the default value input field, depending on the default type
  2325. * Ticks the NULL checkbox if NULL is chosen as default value.
  2326. */
  2327. function PMA_hideShowDefaultValue($default_type)
  2328. {
  2329. if ($default_type.val() == 'USER_DEFINED') {
  2330. $default_type.siblings('.default_value').show().focus();
  2331. } else {
  2332. $default_type.siblings('.default_value').hide();
  2333. if ($default_type.val() == 'NULL') {
  2334. var $null_checkbox = $default_type.closest('tr').find('.allow_null');
  2335. $null_checkbox.prop('checked', true);
  2336. }
  2337. }
  2338. }
  2339. /**
  2340. * If the column does not allow NULL values, makes sure that default is not NULL
  2341. */
  2342. function PMA_validateDefaultValue($null_checkbox)
  2343. {
  2344. if (! $null_checkbox.prop('checked')) {
  2345. var $default = $null_checkbox.closest('tr').find('.default_type');
  2346. if ($default.val() == 'NULL') {
  2347. $default.val('NONE');
  2348. }
  2349. }
  2350. }
  2351. /**
  2352. * Unbind all event handlers before tearing down a page
  2353. */
  2354. AJAX.registerTeardown('functions.js', function() {
  2355. $("a.open_enum_editor").die('click');
  2356. $("input.add_value").die('click');
  2357. $("#enum_editor td.drop").die('click');
  2358. });
  2359. /**
  2360. * @var $enum_editor_dialog An object that points to the jQuery
  2361. * dialog of the ENUM/SET editor
  2362. */
  2363. var $enum_editor_dialog = null;
  2364. /**
  2365. * Opens the ENUM/SET editor and controls its functions
  2366. */
  2367. AJAX.registerOnload('functions.js', function() {
  2368. $("a.open_enum_editor").live('click', function() {
  2369. // Get the name of the column that is being edited
  2370. var colname = $(this).closest('tr').find('input:first').val();
  2371. // And use it to make up a title for the page
  2372. if (colname.length < 1) {
  2373. var title = PMA_messages['enum_newColumnVals'];
  2374. } else {
  2375. var title = PMA_messages['enum_columnVals'].replace(
  2376. /%s/,
  2377. '"' + escapeHtml(decodeURIComponent(colname)) + '"'
  2378. );
  2379. }
  2380. // Get the values as a string
  2381. var inputstring = $(this)
  2382. .closest('td')
  2383. .find("input")
  2384. .val();
  2385. // Escape html entities
  2386. inputstring = $('<div/>')
  2387. .text(inputstring)
  2388. .html();
  2389. // Parse the values, escaping quotes and
  2390. // slashes on the fly, into an array
  2391. var values = [];
  2392. var in_string = false;
  2393. var curr, next, buffer = '';
  2394. for (var i=0; i<inputstring.length; i++) {
  2395. curr = inputstring.charAt(i);
  2396. next = i == inputstring.length ? '' : inputstring.charAt(i+1);
  2397. if (! in_string && curr == "'") {
  2398. in_string = true;
  2399. } else if (in_string && curr == "\\" && next == "\\") {
  2400. buffer += "&#92;";
  2401. i++;
  2402. } else if (in_string && next == "'" && (curr == "'" || curr == "\\")) {
  2403. buffer += "&#39;";
  2404. i++;
  2405. } else if (in_string && curr == "'") {
  2406. in_string = false;
  2407. values.push(buffer);
  2408. buffer = '';
  2409. } else if (in_string) {
  2410. buffer += curr;
  2411. }
  2412. }
  2413. if (buffer.length > 0) {
  2414. // The leftovers in the buffer are the last value (if any)
  2415. values.push(buffer);
  2416. }
  2417. var fields = '';
  2418. // If there are no values, maybe the user is about to make a
  2419. // new list so we add a few for him/her to get started with.
  2420. if (values.length == 0) {
  2421. values.push('','','','');
  2422. }
  2423. // Add the parsed values to the editor
  2424. var drop_icon = PMA_getImage('b_drop.png');
  2425. for (var i=0; i<values.length; i++) {
  2426. fields += "<tr><td>"
  2427. + "<input type='text' value='" + values[i] + "'/>"
  2428. + "</td><td class='drop'>"
  2429. + drop_icon
  2430. + "</td></tr>";
  2431. }
  2432. /**
  2433. * @var dialog HTML code for the ENUM/SET dialog
  2434. */
  2435. var dialog = "<div id='enum_editor'>"
  2436. + "<fieldset>"
  2437. + "<legend>" + title + "</legend>"
  2438. + "<p>" + PMA_getImage('s_notice.png')
  2439. + PMA_messages['enum_hint'] + "</p>"
  2440. + "<table class='values'>" + fields + "</table>"
  2441. + "</fieldset><fieldset class='tblFooters'>"
  2442. + "<table class='add'><tr><td>"
  2443. + "<div class='slider'></div>"
  2444. + "</td><td>"
  2445. + "<form><div><input type='submit' class='add_value' value='"
  2446. + $.sprintf(PMA_messages['enum_addValue'], 1)
  2447. + "'/></div></form>"
  2448. + "</td></tr></table>"
  2449. + "<input type='hidden' value='" // So we know which column's data is being edited
  2450. + $(this).closest('td').find("input").attr("id")
  2451. + "' />"
  2452. + "</fieldset>"
  2453. + "</div>";
  2454. /**
  2455. * @var Defines functions to be called when the buttons in
  2456. * the buttonOptions jQuery dialog bar are pressed
  2457. */
  2458. var buttonOptions = {};
  2459. buttonOptions[PMA_messages['strGo']] = function () {
  2460. // When the submit button is clicked,
  2461. // put the data back into the original form
  2462. var value_array = [];
  2463. $(this).find(".values input").each(function(index, elm) {
  2464. var val = elm.value.replace(/\\/g, '\\\\').replace(/'/g, "''");
  2465. value_array.push("'" + val + "'");
  2466. });
  2467. // get the Length/Values text field where this value belongs
  2468. var values_id = $(this).find("input[type='hidden']").val();
  2469. $("input#" + values_id).val(value_array.join(","));
  2470. $(this).dialog("close");
  2471. };
  2472. buttonOptions[PMA_messages['strClose']] = function () {
  2473. $(this).dialog("close");
  2474. };
  2475. // Show the dialog
  2476. var width = parseInt(
  2477. (parseInt($('html').css('font-size'), 10)/13)*340,
  2478. 10
  2479. );
  2480. if (! width) {
  2481. width = 340;
  2482. }
  2483. $enum_editor_dialog = $(dialog).dialog({
  2484. minWidth: width,
  2485. modal: true,
  2486. title: PMA_messages['enum_editor'],
  2487. buttons: buttonOptions,
  2488. open: function() {
  2489. // Focus the "Go" button after opening the dialog
  2490. $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button:first').focus();
  2491. },
  2492. close: function() {
  2493. $(this).remove();
  2494. }
  2495. });
  2496. // slider for choosing how many fields to add
  2497. $enum_editor_dialog.find(".slider").slider({
  2498. animate: true,
  2499. range: "min",
  2500. value: 1,
  2501. min: 1,
  2502. max: 9,
  2503. slide: function( event, ui ) {
  2504. $(this).closest('table').find('input[type=submit]').val(
  2505. $.sprintf(PMA_messages['enum_addValue'], ui.value)
  2506. );
  2507. }
  2508. });
  2509. // Focus the slider, otherwise it looks nearly transparent
  2510. $('a.ui-slider-handle').addClass('ui-state-focus');
  2511. return false;
  2512. });
  2513. // When "add a new value" is clicked, append an empty text field
  2514. $("input.add_value").live('click', function(e) {
  2515. e.preventDefault();
  2516. var num_new_rows = $enum_editor_dialog.find("div.slider").slider('value');
  2517. while (num_new_rows--) {
  2518. $enum_editor_dialog.find('.values')
  2519. .append(
  2520. "<tr style='display: none;'><td>"
  2521. + "<input type='text' />"
  2522. + "</td><td class='drop'>"
  2523. + PMA_getImage('b_drop.png')
  2524. + "</td></tr>"
  2525. )
  2526. .find('tr:last')
  2527. .show('fast');
  2528. }
  2529. });
  2530. // Removes the specified row from the enum editor
  2531. $("#enum_editor td.drop").live('click', function() {
  2532. $(this).closest('tr').hide('fast', function () {
  2533. $(this).remove();
  2534. });
  2535. });
  2536. });
  2537. /**
  2538. * Ensures indexes names are valid according to their type and, for a primary
  2539. * key, lock index name to 'PRIMARY'
  2540. * @param string form_id Variable which parses the form name as
  2541. * the input
  2542. * @return boolean false if there is no index form, true else
  2543. */
  2544. function checkIndexName(form_id)
  2545. {
  2546. if ($("#"+form_id).length == 0) {
  2547. return false;
  2548. }
  2549. // Gets the elements pointers
  2550. var $the_idx_name = $("#input_index_name");
  2551. var $the_idx_type = $("#select_index_type");
  2552. // Index is a primary key
  2553. if ($the_idx_type.find("option:selected").val() == 'PRIMARY') {
  2554. $the_idx_name.val('PRIMARY');
  2555. $the_idx_name.prop("disabled", true);
  2556. }
  2557. // Other cases
  2558. else {
  2559. if ($the_idx_name.val() == 'PRIMARY') {
  2560. $the_idx_name.val("");
  2561. }
  2562. $the_idx_name.prop("disabled", false);
  2563. }
  2564. return true;
  2565. } // end of the 'checkIndexName()' function
  2566. AJAX.registerTeardown('functions.js', function() {
  2567. $('#index_frm input[type=submit]').die('click');
  2568. });
  2569. AJAX.registerOnload('functions.js', function() {
  2570. /**
  2571. * Handler for adding more columns to an index in the editor
  2572. */
  2573. $('#index_frm input[type=submit]').live('click', function(event) {
  2574. event.preventDefault();
  2575. var rows_to_add = $(this)
  2576. .closest('fieldset')
  2577. .find('.slider')
  2578. .slider('value');
  2579. while (rows_to_add--) {
  2580. var $newrow = $('#index_columns')
  2581. .find('tbody > tr:first')
  2582. .clone()
  2583. .appendTo(
  2584. $('#index_columns').find('tbody')
  2585. );
  2586. $newrow.find(':input').each(function() {
  2587. $(this).val('');
  2588. });
  2589. // focus index size input on column picked
  2590. $newrow.find('select').change(function() {
  2591. if ($(this).find("option:selected").val() == '') {
  2592. return true;
  2593. }
  2594. $(this).closest("tr").find("input").focus();
  2595. });
  2596. }
  2597. });
  2598. });
  2599. function indexEditorDialog(url, title, callback_success, callback_failure)
  2600. {
  2601. /*Remove the hidden dialogs if there are*/
  2602. if ($('#edit_index_dialog').length != 0) {
  2603. $('#edit_index_dialog').remove();
  2604. }
  2605. var $div = $('<div id="edit_index_dialog"></div>');
  2606. /**
  2607. * @var button_options Object that stores the options
  2608. * passed to jQueryUI dialog
  2609. */
  2610. var button_options = {};
  2611. button_options[PMA_messages['strGo']] = function() {
  2612. /**
  2613. * @var the_form object referring to the export form
  2614. */
  2615. var $form = $("#index_frm");
  2616. var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
  2617. PMA_prepareForAjaxRequest($form);
  2618. //User wants to submit the form
  2619. $.post($form.attr('action'), $form.serialize()+"&do_save_data=1", function(data) {
  2620. if ($("#sqlqueryresults").length != 0) {
  2621. $("#sqlqueryresults").remove();
  2622. }
  2623. if (data.success == true) {
  2624. PMA_ajaxShowMessage(data.message);
  2625. if ($('#result_query').length) {
  2626. $('#result_query').remove();
  2627. }
  2628. if (data.sql_query) {
  2629. $('<div id="result_query"></div>')
  2630. .html(data.sql_query)
  2631. .prependTo('#page_content');
  2632. }
  2633. $("#result_query .notice").remove();
  2634. $("#result_query").prepend(data.message);
  2635. /*Reload the field form*/
  2636. $("#table_index").remove();
  2637. var $temp_div = $("<div id='temp_div'><div>").append(data.index_table);
  2638. $temp_div.find("#table_index").insertAfter("#index_header");
  2639. if ($("#edit_index_dialog").length > 0) {
  2640. $("#edit_index_dialog").dialog("close");
  2641. }
  2642. $('div.no_indexes_defined').hide();
  2643. if (callback_success) {
  2644. callback_success();
  2645. }
  2646. PMA_reloadNavigation();
  2647. } else {
  2648. var $temp_div = $("<div id='temp_div'><div>").append(data.error);
  2649. if ($temp_div.find(".error code").length != 0) {
  2650. var $error = $temp_div.find(".error code").addClass("error");
  2651. } else {
  2652. var $error = $temp_div;
  2653. }
  2654. if (callback_failure) {
  2655. callback_failure();
  2656. }
  2657. PMA_ajaxShowMessage($error, false);
  2658. }
  2659. }); // end $.post()
  2660. };
  2661. button_options[PMA_messages['strCancel']] = function() {
  2662. $(this).dialog('close');
  2663. };
  2664. var $msgbox = PMA_ajaxShowMessage();
  2665. $.get("tbl_indexes.php", url, function(data) {
  2666. if (data.success == false) {
  2667. //in the case of an error, show the error message returned.
  2668. PMA_ajaxShowMessage(data.error, false);
  2669. } else {
  2670. PMA_ajaxRemoveMessage($msgbox);
  2671. // Show dialog if the request was successful
  2672. $div
  2673. .append(data.message)
  2674. .dialog({
  2675. title: title,
  2676. width: 450,
  2677. open: PMA_verifyColumnsProperties,
  2678. modal: true,
  2679. buttons: button_options,
  2680. close: function () {
  2681. $(this).remove();
  2682. }
  2683. });
  2684. checkIndexType();
  2685. checkIndexName("index_frm");
  2686. PMA_showHints($div);
  2687. // Add a slider for selecting how many columns to add to the index
  2688. $div.find('.slider').slider({
  2689. animate: true,
  2690. value: 1,
  2691. min: 1,
  2692. max: 16,
  2693. slide: function( event, ui ) {
  2694. $(this).closest('fieldset').find('input[type=submit]').val(
  2695. $.sprintf(PMA_messages['strAddToIndex'], ui.value)
  2696. );
  2697. }
  2698. });
  2699. // focus index size input on column picked
  2700. $div.find('table#index_columns select').change(function() {
  2701. if ($(this).find("option:selected").val() == '') {
  2702. return true;
  2703. }
  2704. $(this).closest("tr").find("input").focus();
  2705. });
  2706. // Focus the slider, otherwise it looks nearly transparent
  2707. $('a.ui-slider-handle').addClass('ui-state-focus');
  2708. // set focus on index name input, if empty
  2709. var input = $div.find('input#input_index_name');
  2710. input.val() || input.focus();
  2711. }
  2712. }); // end $.get()
  2713. }
  2714. /**
  2715. * Function to display tooltips that were
  2716. * generated on the PHP side by PMA_Util::showHint()
  2717. *
  2718. * @param object $div a div jquery object which specifies the
  2719. * domain for searching for tooltips. If we
  2720. * omit this parameter the function searches
  2721. * in the whole body
  2722. **/
  2723. function PMA_showHints($div)
  2724. {
  2725. if ($div == undefined || ! $div instanceof jQuery || $div.length == 0) {
  2726. $div = $("body");
  2727. }
  2728. $div.find('.pma_hint').each(function () {
  2729. PMA_tooltip(
  2730. $(this).children('img'),
  2731. 'img',
  2732. $(this).children('span').html()
  2733. );
  2734. });
  2735. }
  2736. AJAX.registerOnload('functions.js', function() {
  2737. PMA_showHints();
  2738. });
  2739. function PMA_mainMenuResizerCallback() {
  2740. // 5 px margin for jumping menu in Chrome
  2741. return $(document.body).width() - 5;
  2742. }
  2743. // This must be fired only once after the inital page load
  2744. $(function() {
  2745. // Initialise the menu resize plugin
  2746. $('#topmenu').menuResizer(PMA_mainMenuResizerCallback);
  2747. // register resize event
  2748. $(window).resize(function (){
  2749. $('#topmenu').menuResizer('resize');
  2750. });
  2751. });
  2752. /**
  2753. * Get the row number from the classlist (for example, row_1)
  2754. */
  2755. function PMA_getRowNumber(classlist)
  2756. {
  2757. return parseInt(classlist.split(/\s+row_/)[1]);
  2758. }
  2759. /**
  2760. * Changes status of slider
  2761. */
  2762. function PMA_set_status_label($element)
  2763. {
  2764. var text = $element.css('display') == 'none'
  2765. ? '+ '
  2766. : '- ';
  2767. $element.closest('.slide-wrapper').prev().find('span').text(text);
  2768. }
  2769. /**
  2770. * var toggleButton This is a function that creates a toggle
  2771. * sliding button given a jQuery reference
  2772. * to the correct DOM element
  2773. */
  2774. var toggleButton = function ($obj) {
  2775. // In rtl mode the toggle switch is flipped horizontally
  2776. // so we need to take that into account
  2777. if ($('span.text_direction', $obj).text() == 'ltr') {
  2778. var right = 'right';
  2779. } else {
  2780. var right = 'left';
  2781. }
  2782. /**
  2783. * var h Height of the button, used to scale the
  2784. * background image and position the layers
  2785. */
  2786. var h = $obj.height();
  2787. $('img', $obj).height(h);
  2788. $('table', $obj).css('bottom', h-1);
  2789. /**
  2790. * var on Width of the "ON" part of the toggle switch
  2791. * var off Width of the "OFF" part of the toggle switch
  2792. */
  2793. var on = $('td.toggleOn', $obj).width();
  2794. var off = $('td.toggleOff', $obj).width();
  2795. // Make the "ON" and "OFF" parts of the switch the same size
  2796. // + 2 pixels to avoid overflowed
  2797. $('td.toggleOn > div', $obj).width(Math.max(on, off) + 2);
  2798. $('td.toggleOff > div', $obj).width(Math.max(on, off) + 2);
  2799. /**
  2800. * var w Width of the central part of the switch
  2801. */
  2802. var w = parseInt(($('img', $obj).height() / 16) * 22, 10);
  2803. // Resize the central part of the switch on the top
  2804. // layer to match the background
  2805. $('table td:nth-child(2) > div', $obj).width(w);
  2806. /**
  2807. * var imgw Width of the background image
  2808. * var tblw Width of the foreground layer
  2809. * var offset By how many pixels to move the background
  2810. * image, so that it matches the top layer
  2811. */
  2812. var imgw = $('img', $obj).width();
  2813. var tblw = $('table', $obj).width();
  2814. var offset = parseInt(((imgw - tblw) / 2), 10);
  2815. // Move the background to match the layout of the top layer
  2816. $obj.find('img').css(right, offset);
  2817. /**
  2818. * var offw Outer width of the "ON" part of the toggle switch
  2819. * var btnw Outer width of the central part of the switch
  2820. */
  2821. var offw = $('td.toggleOff', $obj).outerWidth();
  2822. var btnw = $('table td:nth-child(2)', $obj).outerWidth();
  2823. // Resize the main div so that exactly one side of
  2824. // the switch plus the central part fit into it.
  2825. $obj.width(offw + btnw + 2);
  2826. /**
  2827. * var move How many pixels to move the
  2828. * switch by when toggling
  2829. */
  2830. var move = $('td.toggleOff', $obj).outerWidth();
  2831. // If the switch is initialized to the
  2832. // OFF state we need to move it now.
  2833. if ($('div.container', $obj).hasClass('off')) {
  2834. if (right == 'right') {
  2835. $('div.container', $obj).animate({'left': '-=' + move + 'px'}, 0);
  2836. } else {
  2837. $('div.container', $obj).animate({'left': '+=' + move + 'px'}, 0);
  2838. }
  2839. }
  2840. // Attach an 'onclick' event to the switch
  2841. $('div.container', $obj).click(function () {
  2842. if ($(this).hasClass('isActive')) {
  2843. return false;
  2844. } else {
  2845. $(this).addClass('isActive');
  2846. }
  2847. var $msg = PMA_ajaxShowMessage();
  2848. var $container = $(this);
  2849. var callback = $('span.callback', this).text();
  2850. // Perform the actual toggle
  2851. if ($(this).hasClass('on')) {
  2852. if (right == 'right') {
  2853. var operator = '-=';
  2854. } else {
  2855. var operator = '+=';
  2856. }
  2857. var url = $(this).find('td.toggleOff > span').text();
  2858. var removeClass = 'on';
  2859. var addClass = 'off';
  2860. } else {
  2861. if (right == 'right') {
  2862. var operator = '+=';
  2863. } else {
  2864. var operator = '-=';
  2865. }
  2866. var url = $(this).find('td.toggleOn > span').text();
  2867. var removeClass = 'off';
  2868. var addClass = 'on';
  2869. }
  2870. $.post(url, {'ajax_request': true}, function(data) {
  2871. if (data.success == true) {
  2872. PMA_ajaxRemoveMessage($msg);
  2873. $container
  2874. .removeClass(removeClass)
  2875. .addClass(addClass)
  2876. .animate({'left': operator + move + 'px'}, function () {
  2877. $container.removeClass('isActive');
  2878. });
  2879. eval(callback);
  2880. } else {
  2881. PMA_ajaxShowMessage(data.error, false);
  2882. $container.removeClass('isActive');
  2883. }
  2884. });
  2885. });
  2886. };
  2887. /**
  2888. * Unbind all event handlers before tearing down a page
  2889. */
  2890. AJAX.registerTeardown('functions.js', function() {
  2891. $('div.container').unbind('click');
  2892. });
  2893. /**
  2894. * Initialise all toggle buttons
  2895. */
  2896. AJAX.registerOnload('functions.js', function () {
  2897. $('div.toggleAjax').each(function () {
  2898. var $button = $(this).show();
  2899. $button.find('img').each(function() {
  2900. if (this.complete) {
  2901. toggleButton($button);
  2902. } else {
  2903. $(this).load(function () {
  2904. toggleButton($button);
  2905. });
  2906. }
  2907. });
  2908. });
  2909. });
  2910. /**
  2911. * Unbind all event handlers before tearing down a page
  2912. */
  2913. AJAX.registerTeardown('functions.js', function() {
  2914. $('.vpointer').die('hover');
  2915. $('.vmarker').die('click');
  2916. $('#pageselector').die('change');
  2917. $('a.formLinkSubmit').die('click');
  2918. $('#update_recent_tables').unbind('ready');
  2919. });
  2920. /**
  2921. * Vertical pointer
  2922. */
  2923. AJAX.registerOnload('functions.js', function() {
  2924. $('.vpointer').live('hover',
  2925. //handlerInOut
  2926. function(e) {
  2927. var $this_td = $(this);
  2928. var row_num = PMA_getRowNumber($this_td.attr('class'));
  2929. // for all td of the same vertical row, toggle hover
  2930. $('.vpointer').filter('.row_' + row_num).toggleClass('hover');
  2931. }
  2932. );
  2933. /**
  2934. * Vertical marker
  2935. */
  2936. $('.vmarker').live('click', function(e) {
  2937. // do not trigger when clicked on anchor
  2938. if ($(e.target).is('a, img, a *')) {
  2939. return;
  2940. }
  2941. var $this_td = $(this);
  2942. var row_num = PMA_getRowNumber($this_td.attr('class'));
  2943. // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
  2944. var $checkbox = $('.vmarker').filter('.row_' + row_num + ':first').find(':checkbox');
  2945. if ($checkbox.length) {
  2946. // checkbox in a row, add or remove class depending on checkbox state
  2947. var checked = $checkbox.prop('checked');
  2948. if (!$(e.target).is(':checkbox, label')) {
  2949. checked = !checked;
  2950. $checkbox.prop('checked', checked);
  2951. }
  2952. // for all td of the same vertical row, toggle the marked class
  2953. if (checked) {
  2954. $('.vmarker').filter('.row_' + row_num).addClass('marked');
  2955. } else {
  2956. $('.vmarker').filter('.row_' + row_num).removeClass('marked');
  2957. }
  2958. } else {
  2959. // normaln data table, just toggle class
  2960. $('.vmarker').filter('.row_' + row_num).toggleClass('marked');
  2961. }
  2962. });
  2963. /**
  2964. * Autosubmit page selector
  2965. */
  2966. $('select.pageselector').live('change', function(event) {
  2967. event.stopPropagation();
  2968. // Check where to load the new content
  2969. if ($(this).closest("#pma_navigation").length == 0) {
  2970. // For the main page we don't need to do anything,
  2971. $(this).closest("form").submit();
  2972. } else {
  2973. // but for the navigation we need to manually replace the content
  2974. PMA_navigationTreePagination($(this));
  2975. }
  2976. });
  2977. /**
  2978. * Load version information asynchronously.
  2979. */
  2980. if ($('li.jsversioncheck').length > 0) {
  2981. $.ajax({
  2982. dataType: "json",
  2983. url: 'version_check.php',
  2984. method: "POST",
  2985. data: {
  2986. "server": PMA_commonParams.get('server'),
  2987. "token": PMA_commonParams.get('token'),
  2988. },
  2989. success: PMA_current_version
  2990. });
  2991. }
  2992. if ($('#is_git_revision').length > 0) {
  2993. setTimeout(PMA_display_git_revision, 10);
  2994. }
  2995. /**
  2996. * Slider effect.
  2997. */
  2998. PMA_init_slider();
  2999. /**
  3000. * Enables the text generated by PMA_Util::linkOrButton() to be clickable
  3001. */
  3002. $('a.formLinkSubmit').live('click', function(e) {
  3003. if ($(this).attr('href').indexOf('=') != -1) {
  3004. var data = $(this).attr('href').substr($(this).attr('href').indexOf('#')+1).split('=', 2);
  3005. $(this).parents('form').append('<input type="hidden" name="' + data[0] + '" value="' + data[1] + '"/>');
  3006. }
  3007. $(this).parents('form').submit();
  3008. return false;
  3009. });
  3010. if ($('#update_recent_tables').length) {
  3011. $.get(
  3012. $('#update_recent_tables').attr('href'),
  3013. function (data) {
  3014. if (data.success == true) {
  3015. $('#recentTable').html(data.options);
  3016. }
  3017. }
  3018. );
  3019. }
  3020. }); // end of $()
  3021. /**
  3022. * Initializes slider effect.
  3023. */
  3024. function PMA_init_slider()
  3025. {
  3026. $('div.pma_auto_slider').each(function() {
  3027. var $this = $(this);
  3028. if ($this.data('slider_init_done')) {
  3029. return;
  3030. }
  3031. var $wrapper = $('<div>', {'class': 'slide-wrapper'});
  3032. $wrapper.toggle($this.is(':visible'));
  3033. $('<a>', {href: '#'+this.id, "class":'ajax'})
  3034. .text(this.title)
  3035. .prepend($('<span>'))
  3036. .insertBefore($this)
  3037. .click(function() {
  3038. var $wrapper = $this.closest('.slide-wrapper');
  3039. var visible = $this.is(':visible');
  3040. if (!visible) {
  3041. $wrapper.show();
  3042. }
  3043. $this[visible ? 'hide' : 'show']('blind', function() {
  3044. $wrapper.toggle(!visible);
  3045. PMA_set_status_label($this);
  3046. });
  3047. return false;
  3048. });
  3049. $this.wrap($wrapper);
  3050. PMA_set_status_label($this);
  3051. $this.data('slider_init_done', 1);
  3052. });
  3053. }
  3054. /**
  3055. * Initializes slider effect.
  3056. */
  3057. AJAX.registerOnload('functions.js', function() {
  3058. PMA_init_slider();
  3059. });
  3060. /**
  3061. * Restores sliders to the state they were in before initialisation.
  3062. */
  3063. AJAX.registerTeardown('functions.js', function() {
  3064. $('div.pma_auto_slider').each(function() {
  3065. var $this = $(this);
  3066. $this.removeData();
  3067. $this.parent().replaceWith($this);
  3068. $this.parent().children('a').remove();
  3069. });
  3070. });
  3071. /**
  3072. * Creates a message inside an object with a sliding effect
  3073. *
  3074. * @param msg A string containing the text to display
  3075. * @param $obj a jQuery object containing the reference
  3076. * to the element where to put the message
  3077. * This is optional, if no element is
  3078. * provided, one will be created below the
  3079. * navigation links at the top of the page
  3080. *
  3081. * @return bool True on success, false on failure
  3082. */
  3083. function PMA_slidingMessage(msg, $obj)
  3084. {
  3085. if (msg == undefined || msg.length == 0) {
  3086. // Don't show an empty message
  3087. return false;
  3088. }
  3089. if ($obj == undefined || ! $obj instanceof jQuery || $obj.length == 0) {
  3090. // If the second argument was not supplied,
  3091. // we might have to create a new DOM node.
  3092. if ($('#PMA_slidingMessage').length == 0) {
  3093. $('#page_content').prepend(
  3094. '<span id="PMA_slidingMessage" '
  3095. + 'style="display: inline-block;"></span>'
  3096. );
  3097. }
  3098. $obj = $('#PMA_slidingMessage');
  3099. }
  3100. if ($obj.has('div').length > 0) {
  3101. // If there already is a message inside the
  3102. // target object, we must get rid of it
  3103. $obj
  3104. .find('div')
  3105. .first()
  3106. .fadeOut(function () {
  3107. $obj
  3108. .children()
  3109. .remove();
  3110. $obj
  3111. .append('<div style="display: none;">' + msg + '</div>')
  3112. .animate({
  3113. height: $obj.find('div').first().height()
  3114. })
  3115. .find('div')
  3116. .first()
  3117. .fadeIn();
  3118. });
  3119. } else {
  3120. // Object does not already have a message
  3121. // inside it, so we simply slide it down
  3122. var h = $obj
  3123. .width('100%')
  3124. .html('<div style="display: none;">' + msg + '</div>')
  3125. .find('div')
  3126. .first()
  3127. .height();
  3128. $obj
  3129. .find('div')
  3130. .first()
  3131. .css('height', 0)
  3132. .show()
  3133. .animate({
  3134. height: h
  3135. }, function() {
  3136. // Set the height of the parent
  3137. // to the height of the child
  3138. $obj
  3139. .height(
  3140. $obj
  3141. .find('div')
  3142. .first()
  3143. .height()
  3144. );
  3145. });
  3146. }
  3147. return true;
  3148. } // end PMA_slidingMessage()
  3149. /**
  3150. * Unbind all event handlers before tearing down a page
  3151. */
  3152. AJAX.registerTeardown('functions.js', function() {
  3153. $("#drop_tbl_anchor.ajax").die('click');
  3154. $("#truncate_tbl_anchor.ajax").die('click');
  3155. });
  3156. /**
  3157. * Attach Ajax event handlers for Drop Table.
  3158. */
  3159. AJAX.registerOnload('functions.js', function() {
  3160. $("#drop_tbl_anchor.ajax").live('click', function(event) {
  3161. event.preventDefault();
  3162. /**
  3163. * @var question String containing the question to be asked for confirmation
  3164. */
  3165. var question = PMA_messages.strDropTableStrongWarning + ' ';
  3166. question += $.sprintf(
  3167. PMA_messages.strDoYouReally,
  3168. 'DROP TABLE ' + escapeHtml(PMA_commonParams.get('table'))
  3169. );
  3170. $(this).PMA_confirm(question, $(this).attr('href'), function(url) {
  3171. var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
  3172. $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
  3173. if (data.success == true) {
  3174. PMA_ajaxRemoveMessage($msgbox);
  3175. // Table deleted successfully, refresh both the frames
  3176. PMA_reloadNavigation();
  3177. PMA_commonParams.set('table', '');
  3178. PMA_commonActions.refreshMain(
  3179. PMA_commonParams.get('opendb_url'),
  3180. function () {
  3181. PMA_ajaxShowMessage(data.message);
  3182. }
  3183. );
  3184. } else {
  3185. PMA_ajaxShowMessage(data.error, false);
  3186. }
  3187. }); // end $.get()
  3188. }); // end $.PMA_confirm()
  3189. }); //end of Drop Table Ajax action
  3190. $("#truncate_tbl_anchor.ajax").live('click', function(event) {
  3191. event.preventDefault();
  3192. /**
  3193. * @var question String containing the question to be asked for confirmation
  3194. */
  3195. var question = PMA_messages.strTruncateTableStrongWarning + ' ';
  3196. question += $.sprintf(
  3197. PMA_messages.strDoYouReally,
  3198. 'TRUNCATE ' + escapeHtml(PMA_commonParams.get('table'))
  3199. );
  3200. $(this).PMA_confirm(question, $(this).attr('href'), function(url) {
  3201. PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
  3202. $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
  3203. if ($("#sqlqueryresults").length != 0) {
  3204. $("#sqlqueryresults").remove();
  3205. }
  3206. if ($("#result_query").length != 0) {
  3207. $("#result_query").remove();
  3208. }
  3209. if (data.success == true) {
  3210. PMA_ajaxShowMessage(data.message);
  3211. $("<div id='sqlqueryresults'></div>").prependTo("#page_content");
  3212. $("#sqlqueryresults").html(data.sql_query);
  3213. } else {
  3214. PMA_ajaxShowMessage(data.error, false);
  3215. }
  3216. }); // end $.get()
  3217. }); // end $.PMA_confirm()
  3218. }); //end of Truncate Table Ajax action
  3219. }); // end of $() for Truncate Table
  3220. /**
  3221. * Attach CodeMirror2 editor to SQL edit area.
  3222. */
  3223. AJAX.registerOnload('functions.js', function() {
  3224. var $elm = $('#sqlquery');
  3225. if ($elm.length > 0) {
  3226. if (typeof CodeMirror != 'undefined') {
  3227. // for codemirror
  3228. codemirror_editor = CodeMirror.fromTextArea($elm[0], {
  3229. lineNumbers: true,
  3230. matchBrackets: true,
  3231. indentUnit: 4,
  3232. mode: "text/x-mysql",
  3233. lineWrapping: true
  3234. });
  3235. codemirror_editor.focus();
  3236. $(codemirror_editor.getWrapperElement()).bind(
  3237. 'keydown',
  3238. catchKeypressesFromSqlTextboxes
  3239. );
  3240. } else {
  3241. // without codemirror
  3242. $elm.focus().bind('keydown', catchKeypressesFromSqlTextboxes);
  3243. }
  3244. }
  3245. });
  3246. AJAX.registerTeardown('functions.js', function() {
  3247. if (codemirror_editor) {
  3248. $('#sqlquery').text(codemirror_editor.getValue());
  3249. codemirror_editor.toTextArea();
  3250. codemirror_editor = false;
  3251. }
  3252. });
  3253. /**
  3254. * jQuery plugin to cancel selection in HTML code.
  3255. */
  3256. (function ($) {
  3257. $.fn.noSelect = function (p) { //no select plugin by Paulo P.Marinas
  3258. var prevent = (p == null) ? true : p;
  3259. if (prevent) {
  3260. return this.each(function () {
  3261. if ($.browser.msie || $.browser.safari) {
  3262. $(this).bind('selectstart', function () {
  3263. return false;
  3264. });
  3265. } else if ($.browser.mozilla) {
  3266. $(this).css('MozUserSelect', 'none');
  3267. $('body').trigger('focus');
  3268. } else if ($.browser.opera) {
  3269. $(this).bind('mousedown', function () {
  3270. return false;
  3271. });
  3272. } else {
  3273. $(this).attr('unselectable', 'on');
  3274. }
  3275. });
  3276. } else {
  3277. return this.each(function () {
  3278. if ($.browser.msie || $.browser.safari) {
  3279. $(this).unbind('selectstart');
  3280. } else if ($.browser.mozilla) {
  3281. $(this).css('MozUserSelect', 'inherit');
  3282. } else if ($.browser.opera) {
  3283. $(this).unbind('mousedown');
  3284. } else {
  3285. $(this).removeAttr('unselectable');
  3286. }
  3287. });
  3288. }
  3289. }; //end noSelect
  3290. })(jQuery);
  3291. /**
  3292. * jQuery plugin to correctly filter input fields by value, needed
  3293. * because some nasty values may break selector syntax
  3294. */
  3295. (function ($) {
  3296. $.fn.filterByValue = function (value) {
  3297. return this.filter(function () {
  3298. return $(this).val() === value;
  3299. });
  3300. };
  3301. })(jQuery);
  3302. /**
  3303. * Create a jQuery UI tooltip
  3304. *
  3305. * @param $elements jQuery object representing the elements
  3306. * @param item the item
  3307. * (see http://api.jqueryui.com/tooltip/#option-items)
  3308. * @param myContent content of the tooltip
  3309. * @param additionalOptions to override the default options
  3310. *
  3311. */
  3312. function PMA_tooltip($elements, item, myContent, additionalOptions)
  3313. {
  3314. if ($('#no_hint').length > 0) {
  3315. return;
  3316. }
  3317. var defaultOptions = {
  3318. content: myContent,
  3319. items: item,
  3320. tooltipClass: "tooltip",
  3321. track: true,
  3322. show: false,
  3323. hide: false
  3324. };
  3325. $elements.tooltip($.extend(true, defaultOptions, additionalOptions));
  3326. }
  3327. /**
  3328. * Return value of a cell in a table.
  3329. */
  3330. function PMA_getCellValue(td) {
  3331. var $td = $(td);
  3332. if ($td.is('.null')) {
  3333. return '';
  3334. } else if (! $td.is('.to_be_saved') && $td.data('original_data')) {
  3335. return $td.data('original_data');
  3336. } else {
  3337. return $td.text();
  3338. }
  3339. }
  3340. /**
  3341. * Unbind all event handlers before tearing down a page
  3342. */
  3343. AJAX.registerTeardown('functions.js', function() {
  3344. $('a.themeselect').die('click');
  3345. $('.autosubmit').die('change');
  3346. $('a.take_theme').unbind('click');
  3347. });
  3348. AJAX.registerOnload('functions.js', function() {
  3349. /**
  3350. * Theme selector.
  3351. */
  3352. $('a.themeselect').live('click', function(e) {
  3353. window.open(
  3354. e.target,
  3355. 'themes',
  3356. 'left=10,top=20,width=510,height=350,scrollbars=yes,status=yes,resizable=yes'
  3357. );
  3358. return false;
  3359. });
  3360. /**
  3361. * Automatic form submission on change.
  3362. */
  3363. $('.autosubmit').live('change', function(e) {
  3364. $(this).closest('form').submit();
  3365. });
  3366. /**
  3367. * Theme changer.
  3368. */
  3369. $('a.take_theme').click(function(e) {
  3370. var what = this.name;
  3371. if (window.opener && window.opener.document.forms['setTheme'].elements['set_theme']) {
  3372. window.opener.document.forms['setTheme'].elements['set_theme'].value = what;
  3373. window.opener.document.forms['setTheme'].submit();
  3374. window.close();
  3375. return false;
  3376. }
  3377. return true;
  3378. });
  3379. });
  3380. /**
  3381. * Clear text selection
  3382. */
  3383. function PMA_clearSelection() {
  3384. if (document.selection && document.selection.empty) {
  3385. document.selection.empty();
  3386. } else if (window.getSelection) {
  3387. var sel = window.getSelection();
  3388. if (sel.empty) {
  3389. sel.empty();
  3390. }
  3391. if (sel.removeAllRanges) {
  3392. sel.removeAllRanges();
  3393. }
  3394. }
  3395. }
  3396. /**
  3397. * HTML escaping
  3398. */
  3399. function escapeHtml(unsafe) {
  3400. return unsafe
  3401. .replace(/&/g, "&amp;")
  3402. .replace(/</g, "&lt;")
  3403. .replace(/>/g, "&gt;")
  3404. .replace(/"/g, "&quot;")
  3405. .replace(/'/g, "&#039;");
  3406. }
  3407. /**
  3408. * Print button
  3409. */
  3410. function printPage()
  3411. {
  3412. // Do print the page
  3413. if (typeof(window.print) != 'undefined') {
  3414. window.print();
  3415. }
  3416. }
  3417. /**
  3418. * Unbind all event handlers before tearing down a page
  3419. */
  3420. AJAX.registerTeardown('functions.js', function() {
  3421. $('input#print').unbind('click');
  3422. $('span a.create_view.ajax').die('click');
  3423. $('#createViewDialog').find('input, select').die('keydown');
  3424. });
  3425. AJAX.registerOnload('functions.js', function() {
  3426. $('input#print').click(printPage);
  3427. /**
  3428. * Ajaxification for the "Create View" action
  3429. */
  3430. $('span a.create_view.ajax').live('click', function (e) {
  3431. e.preventDefault();
  3432. PMA_createViewDialog($(this));
  3433. });
  3434. /**
  3435. * Attach Ajax event handlers for input fields in the editor
  3436. * and used to submit the Ajax request when the ENTER key is pressed.
  3437. */
  3438. $('#createViewDialog').find('input, select').live('keydown', function (e) {
  3439. if (e.which === 13) { // 13 is the ENTER key
  3440. e.preventDefault();
  3441. $(this).closest('.ui-dialog').find('.ui-button:first').click();
  3442. }
  3443. }); // end $.live()
  3444. });
  3445. function PMA_createViewDialog($this)
  3446. {
  3447. var $msg = PMA_ajaxShowMessage();
  3448. var syntaxHighlighter = null;
  3449. $.get($this.attr('href') + '&ajax_request=1', function (data) {
  3450. if (data.success == true) {
  3451. PMA_ajaxRemoveMessage($msg);
  3452. var buttonOptions = {};
  3453. buttonOptions[PMA_messages['strGo']] = function () {
  3454. if (typeof CodeMirror !== 'undefined') {
  3455. syntaxHighlighter.save();
  3456. }
  3457. $msg = PMA_ajaxShowMessage();
  3458. $.get('view_create.php', $('#createViewDialog').find('form').serialize(), function (data) {
  3459. PMA_ajaxRemoveMessage($msg);
  3460. if (data.success === true) {
  3461. $('#createViewDialog').dialog("close");
  3462. $('#result_query').html(data.message);
  3463. PMA_reloadNavigation();
  3464. } else {
  3465. PMA_ajaxShowMessage(data.error, false);
  3466. }
  3467. });
  3468. };
  3469. buttonOptions[PMA_messages['strClose']] = function () {
  3470. $(this).dialog("close");
  3471. };
  3472. var $dialog = $('<div/>').attr('id', 'createViewDialog').append(data.message).dialog({
  3473. width: 500,
  3474. minWidth: 300,
  3475. maxWidth: 620,
  3476. modal: true,
  3477. buttons: buttonOptions,
  3478. title: $('legend', $(data.message)).html(),
  3479. close: function () {
  3480. $(this).remove();
  3481. }
  3482. });
  3483. $dialog.find('legend').remove();
  3484. // Attach syntax highlited editor
  3485. if (typeof CodeMirror !== 'undefined') {
  3486. var $elm = $dialog.find('textarea');
  3487. var opts = {lineNumbers: true, matchBrackets: true, indentUnit: 4, mode: "text/x-mysql"};
  3488. syntaxHighlighter = CodeMirror.fromTextArea($elm[0], opts);
  3489. }
  3490. $('input:visible[type=text]', $dialog).first().focus();
  3491. } else {
  3492. PMA_ajaxShowMessage(data.error);
  3493. }
  3494. });
  3495. }
  3496. /**
  3497. * Makes the breadcrumbs and the menu bar float at the top of the viewport
  3498. */
  3499. $(function () {
  3500. if ($("#floating_menubar").length && $('#PMA_disable_floating_menubar').length == 0) {
  3501. var left = $('html').attr('dir') == 'ltr' ? 'left' : 'right';
  3502. $("#floating_menubar")
  3503. .css('margin-' + left, $('#pma_navigation').width() + $('#pma_navigation_resizer').width())
  3504. .css(left, 0)
  3505. .css({
  3506. 'position': 'fixed',
  3507. 'top': 0,
  3508. 'width': '100%',
  3509. 'z-index': 500
  3510. })
  3511. .append($('#serverinfo'))
  3512. .append($('#topmenucontainer'));
  3513. // Allow the DOM to render, then adjust the padding on the body
  3514. setTimeout(function () {
  3515. $('body').css(
  3516. 'padding-top',
  3517. $('#floating_menubar').outerHeight(true)
  3518. );
  3519. $('#topmenu').menuResizer('resize');
  3520. }, 4);
  3521. }
  3522. });
  3523. /**
  3524. * Scrolls the page to the top if clicking the serverinfo bar
  3525. */
  3526. $(function () {
  3527. $(document).delegate("#serverinfo, #goto_pagetop", "click", function (event) {
  3528. event.preventDefault();
  3529. $('html, body').animate({scrollTop: 0}, 'fast');
  3530. });
  3531. });
  3532. /**
  3533. * Watches checkboxes in a form to set the checkall box accordingly
  3534. */
  3535. var checkboxes_sel = "input.checkall:checkbox:enabled";
  3536. $(checkboxes_sel).live("change", function () {
  3537. var $form = $(this.form);
  3538. // total number of checkboxes in current form
  3539. var total_boxes = $form.find(checkboxes_sel).length;
  3540. // number of checkboxes checked in current form
  3541. var checked_boxes = $form.find(checkboxes_sel + ":checked").length;
  3542. var $checkall = $form.find("input#checkall");
  3543. if (total_boxes == checked_boxes) {
  3544. $checkall.prop({checked: true, indeterminate: false});
  3545. }
  3546. else if (checked_boxes > 0) {
  3547. $checkall.prop({checked: true, indeterminate: true});
  3548. }
  3549. else {
  3550. $checkall.prop({checked: false, indeterminate: false});
  3551. }
  3552. });
  3553. $("input#checkall").live("change", function() {
  3554. var is_checked = $(this).is(":checked");
  3555. $(this.form).find(checkboxes_sel).prop("checked", is_checked)
  3556. .parents("tr").toggleClass("marked", is_checked);
  3557. });
  3558. /**
  3559. * Toggles row colors of a set of 'tr' elements starting from a given element
  3560. *
  3561. * @param $start Starting element
  3562. */
  3563. function toggleRowColors($start)
  3564. {
  3565. for (var $curr_row = $start; $curr_row.length > 0; $curr_row = $curr_row.next()) {
  3566. if ($curr_row.hasClass('odd')) {
  3567. $curr_row.removeClass('odd').addClass('even');
  3568. } else if ($curr_row.hasClass('even')) {
  3569. $curr_row.removeClass('even').addClass('odd');
  3570. }
  3571. }
  3572. }
  3573. /**
  3574. * Formats a byte number to human-readable form
  3575. *
  3576. * @param bytes the bytes to format
  3577. * @param optional subdecimals the number of digits after the point
  3578. * @param optional pointchar the char to use as decimal point
  3579. */
  3580. function formatBytes(bytes, subdecimals, pointchar) {
  3581. if (!subdecimals) {
  3582. var subdecimals = 0;
  3583. }
  3584. if (!pointchar) {
  3585. var pointchar = '.';
  3586. }
  3587. var units = ['B', 'KiB', 'MiB', 'GiB'];
  3588. for (var i = 0; bytes > 1024 && i < units.length; i++) {
  3589. bytes /= 1024;
  3590. }
  3591. var factor = Math.pow(10, subdecimals);
  3592. bytes = Math.round(bytes * factor) / factor;
  3593. bytes = bytes.toString().split('.').join(pointchar);
  3594. return bytes + ' ' + units[i];
  3595. }
  3596. AJAX.registerOnload('functions.js', function () {
  3597. /**
  3598. * Opens pma more themes link in themes browser, in new window instead of popup
  3599. * This way, we don't break HTML validity
  3600. */
  3601. $("a._blank").prop("target", "_blank");
  3602. /**
  3603. * Reveal the login form to users with JS enabled
  3604. * and focus the appropriate input field
  3605. */
  3606. var $loginform = $('#loginform');
  3607. if ($loginform.length) {
  3608. $loginform.find('.js-show').show();
  3609. if ($('#input_username').val()) {
  3610. $('#input_password').focus();
  3611. } else {
  3612. $('#input_username').focus();
  3613. }
  3614. }
  3615. });
  3616. /**
  3617. * When user gets an ajax session expiry message, we show a login link
  3618. */
  3619. $('a.login-link').live('click', function(e) {
  3620. e.preventDefault();
  3621. window.location.reload(true);
  3622. });
  3623. /**
  3624. * Formats timestamp for display
  3625. */
  3626. function PMA_formatDateTime(date, seconds) {
  3627. var result = $.datepicker.formatDate('yy-mm-dd', date);
  3628. var timefmt = 'HH:mm';
  3629. if (seconds) {
  3630. timefmt = 'HH:mm:ss';
  3631. }
  3632. return result + ' ' + $.datepicker.formatTime(
  3633. timefmt, {
  3634. hour: date.getHours(),
  3635. minute: date.getMinutes(),
  3636. second: date.getSeconds()
  3637. }
  3638. );
  3639. }