dolibarr  16.0.5
lib_head.js.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2005-2018 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2005-2014 Regis Houssin <regis.houssin@inodbox.com>
4  * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <https://www.gnu.org/licenses/>.
18  * or see https://www.gnu.org/
19  */
20 
27 if (!defined('NOREQUIRESOC')) {
28  define('NOREQUIRESOC', '1');
29 }
30 if (!defined('NOCSRFCHECK')) {
31  define('NOCSRFCHECK', 1);
32 }
33 if (!defined('NOTOKENRENEWAL')) {
34  define('NOTOKENRENEWAL', 1);
35 }
36 if (!defined('NOLOGIN')) {
37  define('NOLOGIN', 1);
38 }
39 if (!defined('NOREQUIREMENU')) {
40  define('NOREQUIREMENU', 1);
41 }
42 if (!defined('NOREQUIREHTML')) {
43  define('NOREQUIREHTML', 1);
44 }
45 if (!defined('NOREQUIREAJAX')) {
46  define('NOREQUIREAJAX', '1');
47 }
48 
49 session_cache_limiter('public');
50 
51 require_once '../../main.inc.php';
52 
53 
54 /*
55  * View
56  */
57 
58 // Define javascript type
59 top_httphead('text/javascript; charset=UTF-8');
60 // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access.
61 if (empty($dolibarr_nocache)) {
62  header('Cache-Control: max-age=10800, public, must-revalidate');
63 } else {
64  header('Cache-Control: no-cache');
65 }
66 
67 
68 
69 // Define tradMonths javascript array (we define this in datepicker AND in parent page to avoid errors with IE8)
70 $tradMonths = array(
71 dol_escape_js($langs->transnoentitiesnoconv("Month01")),
72 dol_escape_js($langs->transnoentitiesnoconv("Month02")),
73 dol_escape_js($langs->transnoentitiesnoconv("Month03")),
74 dol_escape_js($langs->transnoentitiesnoconv("Month04")),
75 dol_escape_js($langs->transnoentitiesnoconv("Month05")),
76 dol_escape_js($langs->transnoentitiesnoconv("Month06")),
77 dol_escape_js($langs->transnoentitiesnoconv("Month07")),
78 dol_escape_js($langs->transnoentitiesnoconv("Month08")),
79 dol_escape_js($langs->transnoentitiesnoconv("Month09")),
80 dol_escape_js($langs->transnoentitiesnoconv("Month10")),
81 dol_escape_js($langs->transnoentitiesnoconv("Month11")),
82 dol_escape_js($langs->transnoentitiesnoconv("Month12"))
83 );
84 
85 $tradMonthsShort = array(
86 $langs->trans("MonthShort01"),
87 $langs->trans("MonthShort02"),
88 $langs->trans("MonthShort03"),
89 $langs->trans("MonthShort04"),
90 $langs->trans("MonthShort05"),
91 $langs->trans("MonthShort06"),
92 $langs->trans("MonthShort07"),
93 $langs->trans("MonthShort08"),
94 $langs->trans("MonthShort09"),
95 $langs->trans("MonthShort10"),
96 $langs->trans("MonthShort11"),
97 $langs->trans("MonthShort12")
98 );
99 
100 $tradDays = array(
101 $langs->trans("Sunday"),
102 $langs->trans("Monday"),
103 $langs->trans("Tuesday"),
104 $langs->trans("Wednesday"),
105 $langs->trans("Thursday"),
106 $langs->trans("Friday"),
107 $langs->trans("Saturday")
108 );
109 
110 $tradDaysShort = array(
111 $langs->trans("ShortSunday"),
112 $langs->trans("ShortMonday"),
113 $langs->trans("ShortTuesday"),
114 $langs->trans("ShortWednesday"),
115 $langs->trans("ShortThursday"),
116 $langs->trans("ShortFriday"),
117 $langs->trans("ShortSaturday")
118 );
119 
120 $tradDaysMin = array(
121 $langs->trans("SundayMin"),
122 $langs->trans("MondayMin"),
123 $langs->trans("TuesdayMin"),
124 $langs->trans("WednesdayMin"),
125 $langs->trans("ThursdayMin"),
126 $langs->trans("FridayMin"),
127 $langs->trans("SaturdayMin")
128 );
129 
130 
131 $dec = ',';
132 $thousand = ' ';
133 if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
134  $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
135 }
136 if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
137  $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
138 }
139 if ($thousand == 'Space') {
140  $thousand = ' ';
141 }
142 
143 ?>
144 // Javascript libraries for Dolibarr ERP CRM (https://www.dolibarr.org)
145 
146 // For jQuery date picker
147 var tradMonths = <?php echo json_encode($tradMonths) ?>;
148 var tradMonthsShort = <?php echo json_encode($tradMonthsShort) ?>;
149 var tradDays = <?php echo json_encode($tradDays) ?>;
150 var tradDaysShort = <?php echo json_encode($tradDaysShort) ?>;
151 var tradDaysMin = <?php echo json_encode($tradDaysMin) ?>;
152 var currencyCache = <?php echo json_encode($langs->cache_currencies) ?>;
153 
154 // For JQuery date picker
155 $(document).ready(function() {
156  $.datepicker.setDefaults({
157  autoSize: true,
158  changeMonth: true,
159  changeYear: true,
160  altField: '#timestamp',
161  altFormat: '@' // Gives a timestamp dateformat
162  });
163 });
164 
165 jQuery(function($){
166  $.datepicker.regional['<?php echo $langs->defaultlang ?>'] = {
167  closeText: '<?php echo $langs->trans("Close2") ?>',
168  prevText: '<?php echo $langs->trans("Previous") ?>',
169  nextText: '<?php echo $langs->trans("Next") ?>',
170  currentText: '<?php echo $langs->trans("Now") ?>',
171  monthNames: tradMonths,
172  monthNamesShort: tradMonthsShort,
173  dayNames: tradDays,
174  dayNamesShort: tradDaysShort,
175  dayNamesMin: tradDaysMin,
176  weekHeader: '<?php echo $langs->trans("Week"); ?>',
177  dateFormat: '<?php echo $langs->trans("FormatDateShortJQuery"); ?>', /* Note dd/mm/yy means year on 4 digit in jquery format */
178  firstDay: <?php echo (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : '1'); ?>,
179  isRTL: <?php echo ($langs->trans("DIRECTION") == 'rtl' ? 'true' : 'false'); ?>,
180  showMonthAfterYear: false, /* TODO add specific to country */
181  yearSuffix: '' /* TODO add specific to country */
182  };
183  $.datepicker.setDefaults($.datepicker.regional['<?php echo $langs->defaultlang ?>']);
184 });
185 
186 
187 
192 var select2arrayoflanguage = {
193  matches: function (matches) { return matches + " <?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2ResultFoundUseArrows")); ?>"; },
194  noResults: function () { return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2NotFound")); ?>"; },
195  inputTooShort: function (input) {
196  var n = input.minimum;
197  /*console.log(input);
198  console.log(input.minimum);*/
199  if (n > 1) return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2Enter")); ?> " + n + " <?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2MoreCharacters")); ?>";
200  else return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2Enter")); ?> " + n + " <?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2MoreCharacter")); ?>"
201  },
202  loadMore: function (pageNumber) { return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2LoadingMoreResults")); ?>"; },
203  searching: function () { return "<?php echo dol_escape_js($langs->transnoentitiesnoconv("Select2SearchInProgress")); ?>"; }
204 };
205 
206 
211 // Returns an object given an id
212 function getObjectFromID(id){
213  var theObject;
214  if(document.getElementById)
215  theObject=document.getElementById(id);
216  else
217  theObject=document.all[id];
218  return theObject;
219 }
220 
221 // Called after selection of a date to save details into detailed fields
222 function dpChangeDay(dateFieldID, format)
223 {
224  //showDP.datefieldID=dateFieldID;
225  console.log("Call dpChangeDay, we save date into detailed fields from format = "+format);
226 
227  var thefield=getObjectFromID(dateFieldID);
228  var thefieldday=getObjectFromID(dateFieldID+"day");
229  var thefieldmonth=getObjectFromID(dateFieldID+"month");
230  var thefieldyear=getObjectFromID(dateFieldID+"year");
231 
232  var date=getDateFromFormat(thefield.value, format);
233  //console.log(date);
234  if (date)
235  {
236  thefieldday.value=date.getDate();
237  if(thefieldday.onchange) thefieldday.onchange.call(thefieldday);
238  thefieldmonth.value=date.getMonth()+1;
239  if(thefieldmonth.onchange) thefieldmonth.onchange.call(thefieldmonth);
240  thefieldyear.value=date.getFullYear();
241  if(thefieldyear.onchange) thefieldyear.onchange.call(thefieldyear);
242  }
243  else
244  {
245  thefieldday.value='';
246  if(thefieldday.onchange) thefieldday.onchange.call(thefieldday);
247  thefieldmonth.value='';
248  if(thefieldmonth.onchange) thefieldmonth.onchange.call(thefieldmonth);
249  thefieldyear.value='';
250  if(thefieldyear.onchange) thefieldyear.onchange.call(thefieldyear);
251  }
252 }
253 
254 /*
255  * =================================================================
256  * Function:
257  * formatDate (javascript object Date(), format) Purpose: Returns a date in the
258  * output format specified. The format string can use the following tags: Field |
259  * Tags -------------+------------------------------- Year | yyyy (4 digits), yy
260  * (2 digits) Month | MM (2 digits) Day of Month | dd (2 digits) Hour (1-12) |
261  * hh (2 digits) Hour (0-23) | HH (2 digits) Minute | mm (2 digits) Second | ss
262  * (2 digits) Author: Laurent Destailleur Author: Matelli (see
263  * http://matelli.fr/showcases/patchs-dolibarr/update-date-input-in-action-form.html)
264  * Licence: GPL
265  * ==================================================================
266  */
267 function formatDate(date,format)
268 {
269  // alert('formatDate date='+date+' format='+format);
270 
271  // Force parametres en chaine
272  format=format+"";
273 
274  var result="";
275 
276  var year=date.getYear()+""; if (year.length < 4) { year=""+(year-0+1900); }
277  var month=date.getMonth()+1;
278  var day=date.getDate();
279  var hour=date.getHours();
280  var minute=date.getMinutes();
281  var seconde=date.getSeconds();
282 
283  var i=0;
284  while (i < format.length)
285  {
286  c=format.charAt(i); // Recupere char du format
287  substr="";
288  j=i;
289  while ((format.charAt(j)==c) && (j < format.length)) // Recupere char successif identiques
290  {
291  substr += format.charAt(j++);
292  }
293 
294  // alert('substr='+substr);
295  if (substr == 'yyyy') { result=result+year; }
296  else if (substr == 'yy') { result=result+year.substring(2,4); }
297  else if (substr == 'M') { result=result+month; }
298  else if (substr == 'MM') { result=result+(month<1||month>9?"":"0")+month; }
299  else if (substr == 'd') { result=result+day; }
300  else if (substr == 'dd') { result=result+(day<1||day>9?"":"0")+day; }
301  else if (substr == 'hh') { if (hour > 12) hour-=12; result=result+(hour<0||hour>9?"":"0")+hour; }
302  else if (substr == 'HH') { result=result+(hour<0||hour>9?"":"0")+hour; }
303  else if (substr == 'mm') { result=result+(minute<0||minute>9?"":"0")+minute; }
304  else if (substr == 'ss') { result=result+(seconde<0||seconde>9?"":"0")+seconde; }
305  else { result=result+substr; }
306 
307  i+=substr.length;
308  }
309 
310  // alert(result);
311  return result;
312 }
313 
314 
315 /*
316  * =================================================================
317  * Function: getDateFromFormat(date_string, format_string)
318  * Purpose: This function takes a date string and a format string.
319  * It parses the date string with format and it
320  * returns the date as a javascript Date() object. If date does not match
321  * format, it returns 0. The format string can use the following tags:
322  * Field | Tags
323  * -------------+-----------------------------------
324  * Year | yyyy (4 digits), yy (2 digits)
325  * Month | MM (2 digits)
326  * Day of Month | dd (2 digits)
327  * Hour (1-12) | hh (2 digits)
328  * Hour (0-23) | HH (2 digits)
329  * Minute | mm (2 digits)
330  * Second | ss (2 digits)
331  * Author: Laurent Destailleur
332  * Licence: GPL
333  * ==================================================================
334  */
335 function getDateFromFormat(val,format)
336 {
337  // alert('getDateFromFormat val='+val+' format='+format);
338 
339  // Force parametres en chaine
340  val=val+"";
341  format=format+"";
342 
343  if (val == '') return 0;
344 
345  var now=new Date();
346  var year=now.getYear(); if (year.length < 4) { year=""+(year-0+1900); }
347  var month=now.getMonth()+1;
348  var day=now.getDate();
349  var hour=now.getHours();
350  var minute=now.getMinutes();
351  var seconde=now.getSeconds();
352 
353  var i=0;
354  var d=0; // -d- follows the date string while -i- follows the format
355  // string
356 
357  while (i < format.length)
358  {
359  c=format.charAt(i); // Recupere char du format
360  substr="";
361  j=i;
362  while ((format.charAt(j)==c) && (j < format.length)) // Recupere char
363  // successif
364  // identiques
365  {
366  substr += format.charAt(j++);
367  }
368 
369  // alert('substr='+substr);
370  if (substr == "yyyy") year=getIntegerInString(val,d,4,4);
371  if (substr == "yy") year=""+(getIntegerInString(val,d,2,2)-0+1900);
372  if (substr == "MM" ||substr == "M")
373  {
374  month=getIntegerInString(val,d,1,2);
375  if (month) d -= 2- month.length;
376  }
377  if (substr == "dd")
378  {
379  day=getIntegerInString(val,d,1,2);
380  if (day) d -= 2- day.length;
381  }
382  if (substr == "HH" ||substr == "hh" )
383  {
384  hour=getIntegerInString(val,d,1,2);
385  if (dhouray) d -= 2- hour.length;
386  }
387  if (substr == "mm"){
388  minute=getIntegerInString(val,d,1,2);
389  if (minute) d -= 2- minute.length;
390  }
391  if (substr == "ss")
392  {
393  seconde=getIntegerInString(val,d,1,2);
394  if (seconde) d -= 2- seconde.length;
395  }
396 
397  i+=substr.length;
398  d+=substr.length;
399  }
400 
401  // Check if format param are ok
402  if (year==null||year<1) { return 0; }
403  if (month==null||(month<1)||(month>12)) { return 0; }
404  if (day==null||(day<1)||(day>31)) { return 0; }
405  if (hour==null||(hour<0)||(hour>24)) { return 0; }
406  if (minute==null||(minute<0)||(minute>60)) { return 0; }
407  if (seconde==null||(seconde<0)||(seconde>60)) { return 0; }
408 
409  // alert(year+' '+month+' '+day+' '+hour+' '+minute+' '+seconde);
410  return new Date(year,month-1,day,hour,minute,seconde);
411 }
412 
413 /*
414  * =================================================================
415  * Function: stringIsInteger(string)
416  * Purpose: Return true if string is an integer
417  * ==================================================================
418  */
419 function stringIsInteger(str)
420 {
421  var digits="1234567890";
422  for (var i=0; i < str.length; i++)
423  {
424  if (digits.indexOf(str.charAt(i))==-1)
425  {
426  return false;
427  }
428  }
429  return true;
430 }
431 
432 /*
433  * =================================================================
434  * Function: getIntegerInString(string,pos,minlength,maxlength)
435  * Purpose: Return part of string from position i that is integer
436  * ==================================================================
437  */
438 function getIntegerInString(str,i,minlength,maxlength)
439 {
440  for (var x=maxlength; x>=minlength; x--)
441  {
442  var substr=str.substring(i,i+x);
443  if (substr.length < minlength) { return null; }
444  if (stringIsInteger(substr)) { return substr; }
445  }
446  return null;
447 }
448 
449 
450 /*
451  * =================================================================
452  * Purpose: Clean string to have it url encoded
453  * Input: s
454  * Author: Laurent Destailleur
455  * Licence: GPL
456  * ==================================================================
457  */
458 function urlencode(s) {
459  news=s;
460  news=news.replace(/\+/gi,'%2B');
461  news=news.replace(/&/gi,'%26');
462  return news;
463 }
464 
465 /*
466  * =================================================================
467  * Purpose: Clean string to have it url encoded
468  * Input: s
469  * Author: Laurent Destailleur
470  * Licence: GPL
471  * ==================================================================
472  */
473 function htmlEntityDecodeJs(inp){
474  var replacements = {'&lt;':'<','&gt;':'>','&sol;':'/','&quot;':'"','&apos;':'\'','&amp;':'&','&nbsp;':' '};
475  if (inp)
476  {
477  for(var r in replacements){
478  inp = inp.replace(new RegExp(r,'g'),replacements[r]);
479  }
480  return inp.replace(/&#(\d+);/g, function(match, dec) {
481  return String.fromCharCode(dec);
482  });
483  }
484  else { return ''; }
485 }
486 
487 
488 /*
489  * =================================================================
490  * Purpose: Applique un delai avant execution. Used for autocompletion of companies.
491  * Input: funct, delay
492  * Author: Regis Houssin
493  * Licence: GPL
494  * ==================================================================
495  */
496  function ac_delay(funct,delay) {
497  // delay before start of action
498  setTimeout(funct,delay);
499 }
500 
501 
502 /*
503  * =================================================================
504  * Purpose:
505  * Clean values of a "Sortable.serialize". Used by drag and drop.
506  * Input: expr
507  * Author: Regis Houssin
508  * Licence: GPL
509  * ==================================================================
510  */
511 function cleanSerialize(expr) {
512  if (typeof(expr) != 'string') return '';
513  var reg = new RegExp("(&)", "g");
514  var reg2 = new RegExp("[^A-Z0-9,]", "g");
515  var liste1 = expr.replace(reg, ",");
516  return liste1.replace(reg2, "");
517 }
518 
519 
520 /*
521  * =================================================================
522  * Purpose: Display a temporary message in input text fields (For showing help message on
523  * input field).
524  * Input: fieldId
525  * Input: message
526  * Author: Regis Houssin
527  * Licence: GPL
528  * ==================================================================
529  */
530 function displayMessage(fieldId,message) {
531  var textbox = document.getElementById(fieldId);
532  if (textbox.value == '') {
533  textbox.style.color = 'grey';
534  textbox.value = message;
535  }
536 }
537 
538 /*
539  * =================================================================
540  * Purpose: Hide a temporary message in input text fields (For showing help message on
541  * input field).
542  * Input: fiedId
543  * Input: message
544  * Author: Regis Houssin
545  * Licence: GPL
546  * ==================================================================
547  */
548 function hideMessage(fieldId,message) {
549  var textbox = document.getElementById(fieldId);
550  textbox.style.color = 'black';
551  if (textbox.value == message) textbox.value = '';
552 }
553 
554 
555 /*
556  * Used by button to set on/off.
557  * Call url then make complementary action (like show/hide, enable/disable or set another option).
558  *
559  * @param string url Url (warning: as any url called in ajax mode, the url called here must not renew the token)
560  * @param string code Code
561  * @param string intput Array of complementary actions to do if success
562  * @param int entity Entity
563  * @param int strict Strict
564  * @param int forcereload Force reload
565  * @param int userid User id
566  * @param int value Value to set
567  * @param string token Token
568  */
569 function setConstant(url, code, input, entity, strict, forcereload, userid, token, value) {
570  var saved_url = url; /* avoid undefined url */
571  $.post( url, {
572  action: "set",
573  name: code,
574  entity: entity,
575  token: token,
576  value: value
577  },
578  function() { /* handler for success of post */
579  console.log("Ajax url request to set constant is a success. Make complementary actions and then forcereload="+forcereload+" value="+value);
580  if (value == 0) {
581  $("#set_" + code).show();
582  $("#del_" + code).hide();
583  } else {
584  $("#set_" + code).hide();
585  $("#del_" + code).show();
586  }
587  $.each(input, function(type, data) {
588  // Enable another element
589  if (type == "disabled" && strict != 1) {
590  $.each(data, function(key, value) {
591  var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
592  $(newvalue).removeAttr("disabled");
593  if ($(newvalue).hasClass("butActionRefused") == true) {
594  $(newvalue).removeClass("butActionRefused");
595  $(newvalue).addClass("butAction");
596  }
597  });
598  } else if (type == "enabled") {
599  $.each(data, function(key, value) {
600  var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
601  if (strict == 1)
602  $(newvalue).removeAttr("disabled");
603  else
604  $(newvalue).attr("disabled", true);
605  if ($(newvalue).hasClass("butAction") == true) {
606  $(newvalue).removeClass("butAction");
607  $(newvalue).addClass("butActionRefused");
608  }
609  });
610  // Show another element
611  } else if (type == "showhide" || type == "show") {
612  $.each(data, function(key, value) {
613  var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
614  $(newvalue).show();
615  });
616  // Set another constant
617  } else if (type == "set") {
618  $.each(data, function(key, value) {
619  $("#set_" + key).hide();
620  $("#del_" + key).show();
621  $.post( saved_url, {
622  action: "set",
623  name: key,
624  value: value,
625  entity: entity,
626  token: token
627  });
628  });
629  }
630  });
631  if (forcereload) {
632  var url = window.location.href;
633  if (url.indexOf('dol_resetcache') < 0) {
634  if (url.indexOf('?') > -1) {
635  url = url + "&dol_resetcache=1";
636  } else {
637  url = url + "?dol_resetcache=1";
638  }
639  }
640  var page_y = $(document).scrollTop();
641  url = url.replace(/page_y=\d+/g, '');
642  if (page_y > 0) {
643  if (url.indexOf('?') > -1) {
644  url = url + "&page_y="+page_y;
645  } else {
646  url = url + "?page_y="+page_y;
647  }
648  }
649  url = url.replace(/&&+/, '&');
650  console.log("url ro redirect = "+url);
651 
652  window.location.href = url;
653  //location.reload();
654  return false;
655  }
656  }).fail(function(error) { console.log("Error, we force reload"); location.reload(); }); /* When it fails, we always force reload to have setEventErrorMessages in session visible */
657 }
658 
659 /*
660  * Used by button to set on/off
661  * Call url then make complementary action (like show/hide, enable/disable or set another option).
662  *
663  * @param string url Url (warning: as any url called in ajax mode, the url called here must not renew the token)
664  * @param string code Code
665  * @param string intput Array of complementary actions to do if success
666  * @param int entity Entity
667  * @param int strict Strict
668  * @param int forcereload Force reload
669  * @param int userid User id
670  * @param string token Token
671  */
672 function delConstant(url, code, input, entity, strict, forcereload, userid, token) {
673  var saved_url = url; /* avoid undefined url */
674  $.post( url, {
675  action: "del",
676  name: code,
677  entity: entity,
678  token: token
679  },
680  function() {
681  console.log("Ajax url request to delete constant is success. Make complementary actions and then forcereload="+forcereload);
682  $("#del_" + code).hide();
683  $("#set_" + code).show();
684  $.each(input, function(type, data) {
685  // Disable another element
686  if (type == "disabled") {
687  $.each(data, function(key, value) {
688  var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
689  $(newvalue).attr("disabled", true);
690  if ($(newvalue).hasClass("butAction") == true) {
691  $(newvalue).removeClass("butAction");
692  $(newvalue).addClass("butActionRefused");
693  }
694  });
695  } else if (type == "enabled" && strict != 1) {
696  $.each(data, function(key, value) {
697  var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
698  $(newvalue).removeAttr("disabled");
699  if ($(newvalue).hasClass("butActionRefused") == true) {
700  $(newvalue).removeClass("butActionRefused");
701  $(newvalue).addClass("butAction");
702  }
703  });
704  // Hide another element
705  } else if (type == "showhide" || type == "hide") {
706  $.each(data, function(key, value) {
707  var newvalue=((value.search("^#") < 0 && value.search("^\.") < 0) ? "#" : "") + value;
708  $(newvalue).hide();
709  });
710  // Delete another constant
711  } else if (type == "del") {
712  $.each(data, function(key, value) {
713  $("#del_" + value).hide();
714  $("#set_" + value).show();
715  $.post( saved_url, {
716  action: "del",
717  name: value,
718  entity: entity,
719  token: token
720  });
721  });
722  }
723  });
724  if (forcereload) {
725  var url = window.location.href;
726  if (url.indexOf('dol_resetcache') < 0) {
727  if (url.indexOf('?') > -1) {
728  url = url + "&dol_resetcache=1";
729  } else {
730  url = url + "?dol_resetcache=1";
731  }
732  }
733  var page_y = $(document).scrollTop();
734  url = url.replace(/page_y=\d+/g, '');
735  if (page_y > 0) {
736  if (url.indexOf('?') > -1) {
737  url = url + "&page_y="+page_y;
738  } else {
739  url = url + "?page_y="+page_y;
740  }
741  }
742  url = url.replace(/&&+/, '&');
743  console.log("url ro redirect = "+url);
744 
745  window.location.href = url;
746  //location.reload();
747  return false;
748  }
749  }).fail(function(error) { console.log("Error, we force reload"); location.reload(); }); /* When it fails, we always force reload to have setEventErrorMessages in session visible */
750 }
751 
752 /*
753  * Call the setConstant or delConstant but with a confirmation before.
754  * Used by button to set on/off.
755  *
756  * @param string action Action
757  * @param string url Url
758  * @param string code Code
759  * @param string intput Array of complementary actions to do if success
760  * @param string box Box
761  * @param int entity Entity
762  * @param int yesButton yesButton
763  * @param int noButton noButton
764  * @param int strict Strict
765  * @param int userid User id
766  * @param string token Token
767  */
768 function confirmConstantAction(action, url, code, input, box, entity, yesButton, noButton, strict, userid, token) {
769  var boxConfirm = box;
770  $("#confirm_" + code)
771  .attr("title", boxConfirm.title)
772  .html(boxConfirm.content)
773  .dialog({
774  resizable: false,
775  height: 170,
776  width: 500,
777  modal: true,
778  buttons: [
779  {
780  id : 'yesButton_' + code,
781  text : yesButton,
782  click : function() {
783  if (action == "set") {
784  setConstant(url, code, input, entity, strict, 0, userid, token, 1);
785  } else if (action == "del") {
786  delConstant(url, code, input, entity, strict, 0, userid, token);
787  }
788  // Close dialog
789  $(this).dialog("close");
790  // Execute another method
791  if (boxConfirm.method) {
792  var fnName = boxConfirm.method;
793  if (window.hasOwnProperty(fnName)) {
794  window[fnName]();
795  }
796  }
797  }
798  },
799  {
800  id : 'noButton_' + code,
801  text : noButton,
802  click : function() {
803  $(this).dialog("close");
804  }
805  }
806  ]
807  });
808  // For information dialog box only, hide the noButton
809  if (boxConfirm.info) {
810  $("#noButton_" + code).button().hide();
811  }
812 }
813 
814 
815 /*
816  * =================================================================
817  * This is to allow to transform all select box into ajax autocomplete box
818  * with just one line:
819  * $(function() { $( "#idofmylist" ).combobox(); });
820  * Do not use it on large combo boxes
821  * =================================================================
822  */
823 (function( $ ) {
824  $.widget( "ui.combobox", {
825  options: {
826  minLengthToAutocomplete: 0
827  },
828  _create: function() {
829  var savMinLengthToAutocomplete = this.options.minLengthToAutocomplete;
830  var self = this,
831  select = this.element.hide(),
832  selected = select.children( ":selected" ),
833  value = selected.val() ? selected.text() : "";
834  var input = this.input = $( "<input>" )
835  .insertAfter( select )
836  .val( value )
837  .attr('id', 'inputautocomplete'+select.attr('id'))
838  .autocomplete({
839  delay: 0,
840  minLength: this.options.minLengthToAutocomplete,
841  source: function( request, response ) {
842  var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
843  response( select.children( "option:enabled" ).map(function() {
844  var text = $( this ).text();
845  if ( this.value && ( !request.term || matcher.test(text) ) )
846  return {
847  label: text.replace(
848  new RegExp(
849  "(?![^&;]+;)(?!<[^<>]*)(" +
850  $.ui.autocomplete.escapeRegex(request.term) +
851  ")(?![^<>]*>)(?![^&;]+;)", "gi"
852  ), "<strong>$1</strong>" ),
853  value: text,
854  option: this
855  };
856  }) );
857  },
858  select: function( event, ui ) {
859  ui.item.option.selected = true;
860  self._trigger( "selected", event, {
861  item: ui.item.option
862  });
863  },
864  change: function( event, ui ) {
865  if ( !ui.item ) {
866  var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
867  valid = false;
868  select.children( "option" ).each(function() {
869  if ( $( this ).text().match( matcher ) ) {
870  this.selected = valid = true;
871  return false;
872  }
873  });
874  if ( !valid ) {
875  // remove invalid value, as it didnt match anything
876  $( this ).val( "" );
877  select.val( "" );
878  input.data("ui-autocomplete").term = "";
879  return false;
880  }
881  }
882  }
883  })
884  .addClass( "ui-widget ui-widget-content ui-corner-left dolibarrcombobox" );
885 
886  input.data("ui-autocomplete")._renderItem = function( ul, item ) {
887  return $("<li>")
888  .data( "ui-autocomplete-item", item ) // jQuery UI > 1.10.0
889  .append( "<a>" + item.label + "</a>" )
890  .appendTo( ul );
891  };
892 
893  this.button = $( "<button type=\'button\'>&nbsp;</button>" )
894  .attr( "tabIndex", -1 )
895  .attr( "title", "Show All Items" )
896  .insertAfter( input )
897  .button({
898  icons: {
899  primary: "ui-icon-triangle-1-s"
900  },
901  text: false
902  })
903  .removeClass( "ui-corner-all" )
904  .addClass( "ui-corner-right ui-button-icon" )
905  .click(function() {
906  // close if already visible
907  if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
908  input.autocomplete( "close" );
909  return;
910  }
911 
912  // pass empty string as value to search for, displaying all results
913  input.autocomplete({ minLength: 0 });
914  input.autocomplete( "search", "" );
915  input.autocomplete({ minLength: savMinLengthToAutocomplete });
916  input.focus();
917  });
918  },
919 
920  destroy: function() {
921  this.input.remove();
922  this.button.remove();
923  this.element.show();
924  $.Widget.prototype.destroy.call( this );
925  }
926  });
927 })( jQuery );
928 
929 
930 
937 function copyToClipboard(text,text2)
938 {
939  text = text.replace(/<br>/g,"\n");
940  var newElem = '<textarea id="coordsforpopup" style="border: none; width: 90%; height: 120px;">'+text+'</textarea><br><br>'+text2;
941  /* alert(newElem); */
942  $("#dialogforpopup").html(newElem);
943  $("#dialogforpopup").dialog();
944  $("#coordsforpopup").select();
945  return false;
946 }
947 
948 
957 function newpopup(url, title) {
958  var argv = newpopup.arguments;
959  var argc = newpopup.arguments.length;
960  tmp=url;
961  console.log("newpopup "+argv[2]+" "+argv[3]);
962  var l = (argc > 2) ? argv[2] : 600;
963  var h = (argc > 3) ? argv[3] : 400;
964  var left = (screen.width - l)/2;
965  var top = (screen.height - h)/2;
966  var wfeatures = "directories=0,menubar=0,status=0,resizable=0,scrollbars=1,toolbar=0,width=" + l +",height=" + h + ",left=" + left + ",top=" + top;
967  fen=window.open(tmp,title,wfeatures);
968  return false;
969 }
970 
981 function document_preview(file, type, title)
982 {
983  var ValidImageTypes = ["image/gif", "image/jpeg", "image/png", "image/webp"];
984  var showOriginalSizeButton = false;
985 
986  console.log("document_preview A click was done. file="+file+", type="+type+", title="+title);
987 
988  if ($.inArray(type, ValidImageTypes) < 0) {
989  /* Not an image */
990  var width='85%';
991  var object_width='100%';
992  var height = ($( window ).height() - 60) * 0.90;
993  var object_height='98%';
994 
995  show_preview('notimage');
996 
997  } else {
998  /* This is an image */
999  var object_width=0;
1000  var object_height=0;
1001 
1002  var img = new Image();
1003 
1004  img.onload = function() {
1005  object_width = this.width;
1006  object_height = this.height;
1007 
1008  width = $( window ).width()*0.90;
1009  console.log("object_width="+object_width+" window width="+width);
1010  if(object_width < width){
1011  console.log("Object width is small, we set width of popup according to image width.");
1012  width = object_width + 30
1013  }
1014  height = $( window ).height()*0.85;
1015  console.log("object_height="+object_height+" window height="+height);
1016  if(object_height < height){
1017  console.log("Object height is small, we set height of popup according to image height.");
1018  height = object_height + 80
1019  }
1020  else
1021  {
1022  showOriginalSizeButton = true;
1023  }
1024 
1025  show_preview('image');
1026 
1027  };
1028  img.src = file;
1029 
1030  }
1031 
1032  function show_preview(mode) {
1033  /* console.log("mode="+mode+" file="+file+" type="+type+" width="+width+" height="+height); */
1034  var newElem = '<object name="objectpreview" data="'+file+'" type="'+type+'" width="'+object_width+'" height="'+object_height+'" param="noparam"></object>';
1035 
1036  optionsbuttons = {}
1037  if (mode == 'image' && showOriginalSizeButton)
1038  {
1039  optionsbuttons = {
1040  "<?php echo dol_escape_js($langs->transnoentitiesnoconv("OriginalSize")); ?>": function() { console.log("Click on original size"); jQuery(".ui-dialog-content.ui-widget-content > object").css({ "max-height": "none" }); },
1041  "<?php echo dol_escape_js($langs->transnoentitiesnoconv("CloseWindow")); ?>": function() { $( this ).dialog( "close" ); }
1042  };
1043  }
1044 
1045  $("#dialogforpopup").html(newElem);
1046 
1047  $("#dialogforpopup").dialog({
1048  closeOnEscape: true,
1049  resizable: true,
1050  width: width,
1051  height: height,
1052  modal: true,
1053  title: title,
1054  buttons: optionsbuttons
1055  });
1056 
1057  if (showOriginalSizeButton)
1058  {
1059  jQuery(".ui-dialog-content.ui-widget-content > object").css({ "max-height": "100%", "width": "auto", "margin-left": "auto", "margin-right": "auto", "display": "block" });
1060  }
1061  }
1062 }
1063 
1064 /*
1065  * Provide a function to get an URL GET parameter in javascript
1066  *
1067  * @param string name Name of parameter
1068  * @param mixed valueifnotfound Value if not found
1069  * @return string Value
1070  */
1071 function getParameterByName(name, valueifnotfound)
1072 {
1073  name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
1074  var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
1075  results = regex.exec(location.search);
1076  return results === null ? valueifnotfound : decodeURIComponent(results[1].replace(/\+/g, " "));
1077 }
1078 
1079 
1080 // Code in the public domain from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
1081 (function() {
1090  function decimalAdjust(type, value, exp) {
1091  // If the exp is undefined or zero...
1092  if (typeof exp === 'undefined' || +exp === 0) {
1093  return Math[type](value);
1094  }
1095  value = +value;
1096  exp = +exp;
1097  // If the value is not a number or the exp is not an integer...
1098  if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
1099  return NaN;
1100  }
1101  // Shift
1102  value = value.toString().split('e');
1103  value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
1104  // Shift back
1105  value = value.toString().split('e');
1106  return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
1107  }
1108 
1109  // Decimal round
1110  if (!Math.round10) {
1111  Math.round10 = function(value, exp) {
1112  return decimalAdjust('round', value, exp);
1113  };
1114  }
1115  // Decimal floor
1116  if (!Math.floor10) {
1117  Math.floor10 = function(value, exp) {
1118  return decimalAdjust('floor', value, exp);
1119  };
1120  }
1121  // Decimal ceil
1122  if (!Math.ceil10) {
1123  Math.ceil10 = function(value, exp) {
1124  return decimalAdjust('ceil', value, exp);
1125  };
1126  }
1127 })();
1128 
1129 // Another solution, easier, to build a javascript rounding function
1130 function dolroundjs(number, decimals) { return +(Math.round(number + "e+" + decimals) + "e-" + decimals); }
1131 
1149 function pricejs(amount, mode = 'MT', currency_code = '', force_locale = '') {
1150  var main_max_dec_shown = <?php echo (int) str_replace('.', '', $conf->global->MAIN_MAX_DECIMALS_SHOWN); ?>;
1151  var main_rounding_unit = <?php echo (int) $conf->global->MAIN_MAX_DECIMALS_UNIT; ?>;
1152  var main_rounding_tot = <?php echo (int) $conf->global->MAIN_MAX_DECIMALS_TOT; ?>;
1153  var main_decimal_separator = <?php echo json_encode($dec) ?>;
1154  var main_thousand_separator = <?php echo json_encode($thousand) ?>;
1155  var locale_code = force_locale || <?php echo json_encode($langs->defaultlang) ?>;
1156  var amountAsLocalizedString;
1157  var useIntl = Boolean(Intl && Intl.NumberFormat);
1158  var nDigits;
1159  if (currency_code === 'auto') currency_code = <?php echo json_encode($conf->currency) ?>;
1160 
1161  if (mode === 'MU') nDigits = main_rounding_unit;
1162  else if (mode === 'MT') nDigits = main_rounding_tot;
1163  else return 'Bad value for parameter mode';
1164 
1165  if (useIntl) {
1166  // simple version: let the browser decide how to format the number using the provided language / currency
1167  // parameters
1168  var formattingOptions = {
1169  minimumFractionDigits: nDigits,
1170  maximumFractionDigits: nDigits
1171  };
1172  if (currency_code) {
1173  formattingOptions['style'] = 'currency';
1174  formattingOptions['currency'] = currency_code;
1175  }
1176  return Intl.NumberFormat(locale_code.replace('_', '-'), formattingOptions).format(amount);
1177  }
1178 
1179  // No Intl -> attempt to format the number in a way similar to Dolibarr PHP's `price()` function
1180  amountAsLocalizedString = amount.toFixed(nDigits).replace(
1181  /((?!^)(?:\d{3})*)(?:\.(\d+))?$/,
1182  (fullMatch, digitsByThree, decimals) =>
1183  digitsByThree.replace(
1184  /\d{3}/g,
1185  (groupOfThree) => main_thousand_separator + groupOfThree
1186  ) + (decimals !== undefined ? main_decimal_separator + decimals : '')
1187  ).replace(/ /, ' ');
1188  if (!currency_code) return amountAsLocalizedString;
1189 
1190  // print with currency
1191  var currency_symbol = currency_code;
1192 
1193  // codes of languages / currencies where the symbol must be placed before the amount
1194  var currencyBeforeAmountCodes = {
1195  currency: ['AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD'],
1196  language: ['nl_NL']
1197  };
1198 
1199  if (currencyCache[currency_code]
1200  && currencyCache[currency_code]['unicode']
1201  && currencyCache[currency_code]['unicode'].length) {
1202  currency_symbol = currencyCache[currency_code]['unicode'].reduce(function (res, cur) {return res + cur}, '');
1203  }
1204 
1205  if (currencyBeforeAmountCodes.currency.indexOf(currency_code) >= 0
1206  || currencyBeforeAmountCodes.language.indexOf(locale_code)) {
1207  // if we use a language or a currency where the symbol is placed before the amount
1208  return currency_symbol + amountAsLocalizedString;
1209  }
1210 
1211  // by default: currency symbol after the amount
1212  return amountAsLocalizedString + ' ' + currency_symbol;
1213 }
1214 
1222 function price2numjs(amount) {
1223  if (amount == '') return '';
1224 
1225  var dec = <?php echo json_encode($dec) ?>;
1226  var thousand = <?php echo json_encode($thousand) ?>;
1227 
1228  var main_max_dec_shown = <?php echo (int) str_replace('.', '', $conf->global->MAIN_MAX_DECIMALS_SHOWN); ?>;
1229  var main_rounding_unit = <?php echo (int) $conf->global->MAIN_MAX_DECIMALS_UNIT; ?>;
1230  var main_rounding_tot = <?php echo (int) $conf->global->MAIN_MAX_DECIMALS_TOT; ?>;
1231 
1232  var amount = amount.toString();
1233 
1234  // rounding for unit price
1235  var rounding = main_rounding_unit;
1236  var pos = amount.indexOf(dec);
1237  var decpart = '';
1238  if (pos >= 0) decpart = amount.substr(pos + 1).replace('/0+$/i', ''); // Remove 0 for decimal part
1239  var nbdec = decpart.length;
1240  if (nbdec > rounding) rounding = nbdec;
1241  // If rounding higher than max shown
1242  if (rounding > main_max_dec_shown) rounding = main_max_dec_shown;
1243  if (thousand != ',' && thousand != '.') amount = amount.replace(',', '.');
1244  amount = amount.replace(' ', ''); // To avoid spaces
1245  amount = amount.replace(thousand, ''); // Replace of thousand before replace of dec to avoid pb if thousand is .
1246  amount = amount.replace(dec, '.');
1247  //console.log("amount before="+amount+" rouding="+rounding)
1248  var res = Math.round10(amount, - rounding);
1249  // Other solution is
1250  // var res = dolroundjs(amount, rounding)
1251  console.log("price2numjs text="+amount+" return="+res);
1252  return res;
1253 }
1254 
1255 
1256 <?php
1257 if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && !defined('DISABLE_JQUERY_JNOTIFY')) {
1258  ?>
1259 // Defined properties for JNotify
1260 $(document).ready(function() {
1261  if (typeof $.jnotify == 'function')
1262  {
1263  $.jnotify.setup({
1264  delay: 3000 // the default time to show each notification (in milliseconds)
1265  , sticky: false // determines if the message should be considered "sticky" (user must manually close notification)
1266  , closeLabel: "&times;" // the HTML to use for the "Close" link
1267  , showClose: true // determines if the "Close" link should be shown if notification is also sticky
1268  , fadeSpeed: 1000 // the speed to fade messages out (in milliseconds)
1269  , slideSpeed: 250 // the speed used to slide messages out (in milliseconds)
1270  , classContainer: "jnotify-container"
1271  , classNotification: "jnotify-notification"
1272  , classBackground: "jnotify-background"
1273  , classClose: "jnotify-close"
1274  , classMessage: "jnotify-message"
1275  , init: null // callback that occurs when the main jnotify container is created
1276  , create: null // callback that occurs when when the note is created (occurs just before appearing in DOM)
1277  , beforeRemove: null // callback that occurs when before the notification starts to fade away
1278  });
1279  }
1280 });
1281 <?php } ?>
1282 
1283 // Force to hide menus when page is inside an iFrame so we can show any page into a dialog popup
1284 $(document).ready(function() {
1285  if (window.location && window.location.pathname.indexOf("externalsite/frametop.php") == -1 && window.location !== window.parent.location ) {
1286  console.log("Page is detected to be into an iframe, we hide by CSS the menus");
1287  // The page is in an iframe
1288  jQuery(".side-nav-vert, .side-nav, .websitebar").hide();
1289  jQuery(".id-container").css('width', '100%');
1290 
1291  }
1292 });
1293 
1294 
1295 /*
1296  * Hacky fix for a bug in select2 with jQuery 3.6.0's new nested-focus "protection"
1297  * see: https://github.com/select2/select2/issues/5993
1298  * see: https://github.com/jquery/jquery/issues/4382
1299  *
1300  * TODO: Recheck with the select2 GH issue and remove once this is fixed on their side
1301  */
1302 $(document).on('select2:open', () => {
1303  console.log("Execute the focus (click on combo or use space when on component");
1304  let allFound = document.querySelectorAll('.select2-container--open .select2-search__field');
1305  $(this).one('mouseup keyup',()=>{
1306  setTimeout(()=>{
1307  allFound[allFound.length - 1].focus();
1308  },0);
1309  });
1310 });
1311 
1312 // End of lib_head.js.php
pricejs
pricejs(amount, mode='MT', currency_code='', force_locale='')
Function similar to PHP price()
Definition: lib_head.js.php:1149
document_preview
document_preview(file, type, title)
Function show document preview.
Definition: lib_head.js.php:981
getParameterByName
getParameterByName(name, valueifnotfound)
Definition: lib_head.js.php:1071
fail
if(empty($user->rights->takepos->run) &&!defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) if((getDolGlobalString('TAKEPOS_PHONE_BASIC_LAYOUT')==1 && $conf->browser->layout=='phone')||defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) fail($message)
Abort invoice creationg with a given error message.
Definition: invoice.php:111
top_httphead
if(!defined('NOREQUIREMENU')) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
Definition: main.inc.php:1407
name
$conf db name
Definition: repair.php:122
price2numjs
price2numjs(amount)
Function similar to PHP price2num()
Definition: lib_head.js.php:1222
copyToClipboard
copyToClipboard(text, text2)
Function to output a dialog box for copy/paste.
Definition: lib_head.js.php:937
dol_escape_js
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
Definition: functions.lib.php:1423
code
print *****$script_file(".$version.") pid code
! Closing after partial payment: discount_vat, badcustomer or badsupplier, bankcharge,...
Definition: sync_members_ldap2dolibarr.php:60
newpopup
newpopup(url, title)
Show a popup HTML page.
Definition: lib_head.js.php:957
type
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition: repair.php:119