PageRenderTime 76ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/htdocs/core/class/html.form.class.php

https://github.com/asterix14/dolibarr
PHP | 3852 lines | 2695 code | 371 blank | 786 comment | 790 complexity | 4cf4b83662b932defac5e6b03335469a MD5 | raw file
Possible License(s): LGPL-2.0
  1. <?php
  2. /* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2011 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
  7. * Copyright (C) 2005-2011 Regis Houssin <regis@dolibarr.fr>
  8. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  9. * Copyright (C) 2006 Marc Barilley/Ocebo <marc@ocebo.com>
  10. * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerker@telenet.be>
  11. * Copyright (C) 2007 Patrick Raguin <patrick.raguin@gmail.com>
  12. * Copyright (C) 2010 Juanjo Menent <jmenent@2byte.es>
  13. * Copyright (C) 2010 Philippe Grand <philippe.grand@atoo-net.com>
  14. * Copyright (C) 2011 Herve Prot <herve.prot@symeos.com>
  15. *
  16. * This program is free software; you can redistribute it and/or modify
  17. * it under the terms of the GNU General Public License as published by
  18. * the Free Software Foundation; either version 2 of the License, or
  19. * (at your option) any later version.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU General Public License
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  28. */
  29. /**
  30. * \file htdocs/core/class/html.form.class.php
  31. * \ingroup core
  32. * \brief File of class with all html predefined components
  33. */
  34. /**
  35. * \class Form
  36. * \brief Class to manage generation of HTML components
  37. * \remarks Only common components must be here.
  38. */
  39. class Form
  40. {
  41. var $db;
  42. var $error;
  43. // Cache arrays
  44. var $cache_types_paiements=array();
  45. var $cache_conditions_paiements=array();
  46. var $cache_availability=array();
  47. var $cache_demand_reason=array();
  48. var $cache_type_fees=array();
  49. var $tva_taux_value;
  50. var $tva_taux_libelle;
  51. /**
  52. * Constructor
  53. *
  54. * @param DoliDB $db Database handler
  55. */
  56. public function __construct($db)
  57. {
  58. $this->db = $db;
  59. }
  60. /**
  61. * Output key field for an editable field
  62. *
  63. * @param string $text Text of label or key to translate
  64. * @param string $htmlname Name of select field
  65. * @param string $preselected Name of Value to show/edit (not used in this function)
  66. * @param object $object Object
  67. * @param boolean $perm Permission to allow button to edit parameter
  68. * @param string $typeofdata Type of data ('string' by default, 'email', 'numeric:99', 'text' or 'textarea', 'day' or 'datepicker', 'ckeditor:dolibarr_zzz:width:height', 'select:xxx'...)
  69. * @return string HTML edit field
  70. */
  71. function editfieldkey($text,$htmlname,$preselected,$object,$perm,$typeofdata='string')
  72. {
  73. global $conf,$langs;
  74. $ret='';
  75. if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE))
  76. {
  77. if ($perm)
  78. {
  79. $tmp=explode(':',$typeofdata);
  80. $ret.= '<div class="editkey_'.$tmp[0].'" id="'.$htmlname.'">';
  81. $ret.= $langs->trans($text);
  82. $ret.= '</div>'."\n";
  83. }
  84. else
  85. {
  86. $ret.= $langs->trans($text);
  87. }
  88. }
  89. else
  90. {
  91. $ret.='<table class="nobordernopadding" width="100%"><tr><td nowrap="nowrap">';
  92. $ret.=$langs->trans($text);
  93. $ret.='</td>';
  94. if (GETPOST('action') != 'edit'.$htmlname && $perm) $ret.='<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&amp;id='.$object->id.'">'.img_edit($langs->trans('Edit'),1).'</a></td>';
  95. $ret.='</tr></table>';
  96. }
  97. return $ret;
  98. }
  99. /**
  100. * Output val field for an editable field
  101. *
  102. * @param string $text Text of label (not used in this function)
  103. * @param string $htmlname Name of select field
  104. * @param string $value Value to show/edit
  105. * @param object $object Object
  106. * @param boolean $perm Permission to allow button to edit parameter
  107. * @param string $typeofdata Type of data ('string' by default, 'email', 'numeric:99', 'text' or 'textarea', 'day' or 'datepicker', 'ckeditor:dolibarr_zzz:width:height', 'select:xxx'...)
  108. * @param string $editvalue When in edit mode, use this value as $value instead of value
  109. * @param object $extObject External object
  110. * @return string HTML edit field
  111. */
  112. function editfieldval($text,$htmlname,$value,$object,$perm,$typeofdata='string',$editvalue='',$extObject=false)
  113. {
  114. global $conf,$langs,$db;
  115. $ret='';
  116. // When option to edit inline is activated
  117. if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE))
  118. {
  119. $ret.=$this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $extObject);
  120. }
  121. else
  122. {
  123. if (GETPOST('action') == 'edit'.$htmlname)
  124. {
  125. $ret.="\n";
  126. $ret.='<form method="post" action="'.$_SERVER["PHP_SELF"].'">';
  127. $ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
  128. $ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  129. $ret.='<input type="hidden" name="id" value="'.$object->id.'">';
  130. $ret.='<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  131. $ret.='<tr><td>';
  132. if (preg_match('/^(string|email|numeric)/',$typeofdata))
  133. {
  134. $tmp=explode(':',$typeofdata);
  135. $ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue?$editvalue:$value).'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
  136. }
  137. else if ($typeofdata == 'text' || $typeofdata == 'textarea' || $typeofdata == 'note')
  138. {
  139. $ret.='<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" cols="70">'.($editvalue?$editvalue:$value).'</textarea>';
  140. }
  141. else if ($typeofdata == 'day' || $typeofdata == 'datepicker')
  142. {
  143. $ret.=$this->form_date($_SERVER['PHP_SELF'].'?id='.$object->id,$value,$htmlname);
  144. }
  145. else if (preg_match('/^ckeditor/',$typeofdata))
  146. {
  147. $tmp=explode(':',$typeofdata);
  148. require_once(DOL_DOCUMENT_ROOT."/core/class/doleditor.class.php");
  149. $doleditor=new DolEditor($htmlname,($editvalue?$editvalue:$value),($tmp[2]?$tmp[2]:''),($tmp[3]?$tmp[3]:'100'),($tmp[1]?$tmp[1]:'dolibarr_notes'),'In',false,true,true);
  150. $ret.=$doleditor->Create(1);
  151. }
  152. $ret.='</td>';
  153. if ($typeofdata != 'day' && $typeofdata != 'datepicker') $ret.='<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  154. $ret.='</tr></table>'."\n";
  155. $ret.='</form>'."\n";
  156. }
  157. else
  158. {
  159. if ($typeofdata == 'email') $ret.=dol_print_email($value,0,0,0,0,1);
  160. elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret.=dol_print_date($value,'day');
  161. elseif ($typeofdata == 'text' || $typeofdata == 'textarea') $ret.=dol_htmlentitiesbr($value);
  162. else if (preg_match('/^ckeditor/',$typeofdata))
  163. {
  164. $tmpcontent=dol_htmlentitiesbr($value);
  165. $firstline=preg_replace('/<br>.*/','',$tmpcontent);
  166. $firstline=preg_replace('/[\n\r].*/','',$firstline);
  167. $ret.=$firstline.((strlen($firstline) != strlen($tmpcontent))?'...':'');
  168. }
  169. else $ret.=$value;
  170. }
  171. }
  172. return $ret;
  173. }
  174. /**
  175. * Output edit in place form
  176. *
  177. * @param object $object Object
  178. * @param string $value Value to show/edit
  179. * @param string $htmlname DIV ID (field name)
  180. * @param int $condition Condition to edit
  181. * @param string $inputType Type of input ('numeric', 'datepicker', 'textarea', 'ckeditor:dolibarr_zzz', 'select:xxx')
  182. * @param object $extObject External object
  183. * @return string HTML edit in place
  184. */
  185. private function editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $extObject=false)
  186. {
  187. global $conf;
  188. $out='';
  189. // Check parameters
  190. if ($inputType == 'textarea') $value = dol_nl2br($value);
  191. else if (preg_match('/^numeric/',$inputType)) $value = price($value);
  192. else if ($inputType == 'datepicker') $value = dol_print_date($value, 'day');
  193. if ($condition)
  194. {
  195. $element = false;
  196. $table_element = false;
  197. $fk_element = false;
  198. $loadmethod = false;
  199. $savemethod = false;
  200. $ext_element = false;
  201. //$ext_table_element = false;
  202. //$ext_fk_element = false;
  203. if (is_object($object))
  204. {
  205. $element = $object->element;
  206. $table_element = $object->table_element;
  207. $fk_element = $object->id;
  208. }
  209. if (is_object($extObject))
  210. {
  211. $ext_element = $extObject->element;
  212. //$ext_table_element = $extObject->table_element;
  213. //$ext_fk_element = $extObject->id;
  214. }
  215. if (preg_match('/^(string|email|numeric)/',$inputType))
  216. {
  217. $tmp=explode(':',$inputType);
  218. $inputType=$tmp[0]; $inputOption=$tmp[1];
  219. if (! empty($tmp[2])) $savemethod=$tmp[2];
  220. }
  221. if (preg_match('/^datepicker/',$inputType))
  222. {
  223. $tmp=explode(':',$inputType);
  224. $inputType=$tmp[0]; $inputOption=$tmp[1];
  225. if (! empty($tmp[2])) $savemethod=$tmp[2];
  226. $out.= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
  227. }
  228. else if (preg_match('/^select/',$inputType))
  229. {
  230. $tmp=explode(':',$inputType);
  231. $inputType=$tmp[0]; $loadmethod=$tmp[1];
  232. if (! empty($tmp[2])) $savemethod=$tmp[2];
  233. }
  234. else if (preg_match('/^ckeditor/',$inputType))
  235. {
  236. $tmp=explode(':',$inputType);
  237. $inputType=$tmp[0]; $toolbar=$tmp[1];
  238. if (! empty($tmp[2])) $width=$tmp[2];
  239. if (! empty($tmp[3])) $heigth=$tmp[3];
  240. if (! empty($tmp[4])) $savemethod=$tmp[4];
  241. if (! empty($conf->fckeditor->enabled))
  242. {
  243. $out.= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
  244. }
  245. else
  246. {
  247. $inputType = 'textarea';
  248. }
  249. }
  250. $out.= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
  251. $out.= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
  252. $out.= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
  253. $out.= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
  254. $out.= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
  255. $out.= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
  256. //$out.= '<input id="ext_table_element_'.$htmlname.'" value="'.$ext_table_element.'" type="hidden"/>'."\n";
  257. //$out.= '<input id="ext_fk_element_'.$htmlname.'" value="'.$ext_fk_element.'" type="hidden"/>'."\n";
  258. $out.= '<div id="val_'.$htmlname.'" class="editval_'.$inputType.'">'.$value.'</div>'."\n";
  259. }
  260. else
  261. {
  262. $out = $value;
  263. }
  264. return $out;
  265. }
  266. /**
  267. * Show a text and picto with tooltip on text or picto
  268. *
  269. * @param string $text Text to show
  270. * @param string $htmltext Content html of tooltip. Must be HTML/UTF8 encoded.
  271. * @param int $tooltipon 1=tooltip sur texte, 2=tooltip sur picto, 3=tooltip sur les 2
  272. * @param int $direction -1=Le picto est avant, 0=pas de picto, 1=le picto est apres
  273. * @param string $img Code img du picto (use img_xxx() function to get it)
  274. * @param string $extracss Add a CSS style to td tags
  275. * @param int $notabs Do not include table and tr tags
  276. * @param string $incbefore Include code before the text
  277. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  278. * @return string Code html du tooltip (texte+picto)
  279. * @see Use function textwithpicto if you can.
  280. */
  281. function textwithtooltip($text,$htmltext,$tooltipon=1,$direction=0,$img='',$extracss='',$notabs=0,$incbefore='',$noencodehtmltext=0)
  282. {
  283. global $conf;
  284. if ($incbefore) $text = $incbefore.$text;
  285. if (! $htmltext) return $text;
  286. // Sanitize tooltip
  287. $htmltext=str_replace("\\","\\\\",$htmltext);
  288. $htmltext=str_replace("\r","",$htmltext);
  289. $htmltext=str_replace("\n","",$htmltext);
  290. $htmltext=str_replace('"',"&quot;",$htmltext);
  291. if ($tooltipon == 2 || $tooltipon == 3) $paramfortooltipimg=' class="classfortooltip'.($extracss?' '.$extracss:'').'" title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on td img tag to store tooltip
  292. else $paramfortooltipimg =($extracss?' class="'.$extracss.'"':''); // Attribut to put on td text tag
  293. if ($tooltipon == 1 || $tooltipon == 3) $paramfortooltiptd=' class="classfortooltip'.($extracss?' '.$extracss:'').'" title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on td tag to store tooltip
  294. else $paramfortooltiptd =($extracss?' class="'.$extracss.'"':''); // Attribut to put on td text tag
  295. $s="";
  296. if (empty($notabs)) $s.='<table class="nobordernopadding" summary=""><tr>';
  297. if ($direction > 0)
  298. {
  299. if ($text != '')
  300. {
  301. $s.='<td'.$paramfortooltiptd.'>'.$text;
  302. if ($direction) $s.='&nbsp;';
  303. $s.='</td>';
  304. }
  305. if ($direction) $s.='<td'.$paramfortooltipimg.' valign="top" width="14">'.$img.'</td>';
  306. }
  307. else
  308. {
  309. if ($direction) $s.='<td'.$paramfortooltipimg.' valign="top" width="14">'.$img.'</td>';
  310. if ($text != '')
  311. {
  312. $s.='<td'.$paramfortooltiptd.'>';
  313. if ($direction) $s.='&nbsp;';
  314. $s.=$text.'</td>';
  315. }
  316. }
  317. if (empty($notabs)) $s.='</tr></table>';
  318. return $s;
  319. }
  320. /**
  321. * Show a text with a picto and a tooltip on picto
  322. *
  323. * @param text Text to show
  324. * @param htmltooltip Content of tooltip
  325. * @param direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  326. * @param type Type of picto (info, help, warning, superadmin...)
  327. * @param extracss Add a CSS style to td tags
  328. * @param noencodehtmltext Do not encode into html entity the htmltext
  329. * @return string HTML code of text, picto, tooltip
  330. */
  331. function textwithpicto($text,$htmltext,$direction=1,$type='help',$extracss='',$noencodehtmltext=0)
  332. {
  333. global $conf;
  334. if ("$type" == "0") $type='info'; // For backward compatibility
  335. $alt='';
  336. // If info or help with no javascript, show only text
  337. if (empty($conf->use_javascript_ajax))
  338. {
  339. if ($type == 'info' || $type == 'help') return $text;
  340. else { $alt=$htmltext; $htmltext=''; }
  341. }
  342. // If info or help with smartphone, show only text
  343. if (! empty($conf->browser->phone))
  344. {
  345. if ($type == 'info' || $type == 'help') return $text;
  346. }
  347. // Info or help
  348. if ($type == 'info') $img=img_help(0,$alt);
  349. if ($type == 'help' || $type ==1) $img=img_help(1,$alt);
  350. if ($type == 'superadmin') $img=img_picto($alt,"redstar");
  351. if ($type == 'admin') $img=img_picto($alt,"star");
  352. // Warnings
  353. if ($type == 'warning') $img=img_warning($alt);
  354. return $this->textwithtooltip($text,$htmltext,2,$direction,$img,$extracss,0,'',$noencodehtmltext);
  355. }
  356. /**
  357. * Return combo list of activated countries, into language of user
  358. *
  359. * @param selected Id or Code or Label of preselected country
  360. * @param htmlname Name of html select object
  361. * @param htmloption Options html on select object
  362. */
  363. function select_pays($selected='',$htmlname='pays_id',$htmloption='')
  364. {
  365. print $this->select_country($selected,$htmlname,$htmloption);
  366. }
  367. /**
  368. * Return combo list of activated countries, into language of user
  369. *
  370. * @param selected Id or Code or Label of preselected country
  371. * @param htmlname Name of html select object
  372. * @param htmloption Options html on select object
  373. * @return string HTML string with select
  374. */
  375. function select_country($selected='',$htmlname='pays_id',$htmloption='')
  376. {
  377. global $conf,$langs;
  378. $langs->load("dict");
  379. $out='';
  380. $countryArray=array();
  381. $label=array();
  382. $sql = "SELECT rowid, code as code_iso, libelle as label";
  383. $sql.= " FROM ".MAIN_DB_PREFIX."c_pays";
  384. $sql.= " WHERE active = 1";
  385. $sql.= " ORDER BY code ASC";
  386. dol_syslog("Form::select_country sql=".$sql);
  387. $resql=$this->db->query($sql);
  388. if ($resql)
  389. {
  390. $out.= '<select id="select'.$htmlname.'" class="flat selectpays" name="'.$htmlname.'" '.$htmloption.'>';
  391. $num = $this->db->num_rows($resql);
  392. $i = 0;
  393. if ($num)
  394. {
  395. $foundselected=false;
  396. while ($i < $num)
  397. {
  398. $obj = $this->db->fetch_object($resql);
  399. $countryArray[$i]['rowid'] = $obj->rowid;
  400. $countryArray[$i]['code_iso'] = $obj->code_iso;
  401. $countryArray[$i]['label'] = ($obj->code_iso && $langs->transnoentitiesnoconv("Country".$obj->code_iso)!="Country".$obj->code_iso?$langs->transnoentitiesnoconv("Country".$obj->code_iso):($obj->label!='-'?$obj->label:''));
  402. $label[$i] = $countryArray[$i]['label'];
  403. $i++;
  404. }
  405. array_multisort($label, SORT_ASC, $countryArray);
  406. foreach ($countryArray as $row)
  407. {
  408. //print 'rr'.$selected.'-'.$row['label'].'-'.$row['code_iso'].'<br>';
  409. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['label']) )
  410. {
  411. $foundselected=true;
  412. $out.= '<option value="'.$row['rowid'].'" selected="selected">';
  413. }
  414. else
  415. {
  416. $out.= '<option value="'.$row['rowid'].'">';
  417. }
  418. $out.= $row['label'];
  419. if ($row['code_iso']) $out.= ' ('.$row['code_iso'] . ')';
  420. $out.= '</option>';
  421. }
  422. }
  423. $out.= '</select>';
  424. }
  425. else
  426. {
  427. dol_print_error($this->db);
  428. }
  429. return $out;
  430. }
  431. /**
  432. * Retourne la liste des types de comptes financiers
  433. *
  434. * @param selected Type pre-selectionne
  435. * @param htmlname Nom champ formulaire
  436. */
  437. function select_type_comptes_financiers($selected=1,$htmlname='type')
  438. {
  439. global $langs;
  440. $langs->load("banks");
  441. $type_available=array(0,1,2);
  442. print '<select class="flat" name="'.$htmlname.'">';
  443. $num = count($type_available);
  444. $i = 0;
  445. if ($num)
  446. {
  447. while ($i < $num)
  448. {
  449. if ($selected == $type_available[$i])
  450. {
  451. print '<option value="'.$type_available[$i].'" selected="selected">'.$langs->trans("BankType".$type_available[$i]).'</option>';
  452. }
  453. else
  454. {
  455. print '<option value="'.$type_available[$i].'">'.$langs->trans("BankType".$type_available[$i]).'</option>';
  456. }
  457. $i++;
  458. }
  459. }
  460. print '</select>';
  461. }
  462. /**
  463. * Return list of social contributions.
  464. * Use mysoc->pays_id or mysoc->pays_code so they must be defined.
  465. *
  466. * @param selected Preselected type
  467. * @param htmlname Name of field in form
  468. * @param useempty Set to 1 if we want an empty value
  469. * @param maxlen Max length of text in combo box
  470. * @param help Add or not the admin help picto
  471. */
  472. function select_type_socialcontrib($selected='',$htmlname='actioncode', $useempty=0, $maxlen=40, $help=1)
  473. {
  474. global $db,$langs,$user,$mysoc;
  475. if (empty($mysoc->pays_id) && empty($mysoc->pays_code))
  476. {
  477. dol_print_error('','Call to select_type_socialcontrib with mysoc country not yet defined');
  478. exit;
  479. }
  480. if (! empty($mysoc->pays_id))
  481. {
  482. $sql = "SELECT c.id, c.libelle as type";
  483. $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c";
  484. $sql.= " WHERE c.active = 1";
  485. $sql.= " AND c.fk_pays = ".$mysoc->pays_id;
  486. $sql.= " ORDER BY c.libelle ASC";
  487. }
  488. else
  489. {
  490. $sql = "SELECT c.id, c.libelle as type";
  491. $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c, ".MAIN_DB_PREFIX."c_pays as p";
  492. $sql.= " WHERE c.active = 1 AND c.fk_pays = p.rowid";
  493. $sql.= " AND p.code = '".$mysoc->pays_code."'";
  494. $sql.= " ORDER BY c.libelle ASC";
  495. }
  496. dol_syslog("Form::select_type_socialcontrib sql=".$sql, LOG_DEBUG);
  497. $resql=$db->query($sql);
  498. if ($resql)
  499. {
  500. $num = $db->num_rows($resql);
  501. if ($num)
  502. {
  503. print '<select class="flat" name="'.$htmlname.'">';
  504. $i = 0;
  505. if ($useempty) print '<option value="0">&nbsp;</option>';
  506. while ($i < $num)
  507. {
  508. $obj = $db->fetch_object($resql);
  509. print '<option value="'.$obj->id.'"';
  510. if ($obj->id == $selected) print ' selected="selected"';
  511. print '>'.dol_trunc($obj->type,$maxlen);
  512. $i++;
  513. }
  514. print '</select>';
  515. if ($user->admin && $help) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"),1);
  516. }
  517. else
  518. {
  519. print $langs->trans("ErrorNoSocialContributionForSellerCountry",$mysoc->pays_code);
  520. }
  521. }
  522. else
  523. {
  524. dol_print_error($db,$db->lasterror());
  525. }
  526. }
  527. /**
  528. * Return list of types of lines (product or service)
  529. * Example: 0=product, 1=service, 9=other (for external module)
  530. *
  531. * @param selected Preselected type
  532. * @param htmlname Name of field in html form
  533. * @param showempty Add an empty field
  534. * @param hidetext Do not show label before combo box
  535. * @param forceall Force to show products and services in combo list, whatever are activated modules
  536. */
  537. function select_type_of_lines($selected='',$htmlname='type',$showempty=0,$hidetext=0,$forceall=0)
  538. {
  539. global $db,$langs,$user,$conf;
  540. // If product & services are enabled or both disabled.
  541. if ($forceall || ($conf->product->enabled && $conf->service->enabled)
  542. || (empty($conf->product->enabled) && empty($conf->service->enabled)))
  543. {
  544. if (empty($hidetext)) print $langs->trans("Type").': ';
  545. print '<select class="flat" name="'.$htmlname.'">';
  546. if ($showempty)
  547. {
  548. print '<option value="-1"';
  549. if ($selected == -1) print ' selected="selected"';
  550. print '>&nbsp;</option>';
  551. }
  552. print '<option value="0"';
  553. if (0 == $selected) print ' selected="selected"';
  554. print '>'.$langs->trans("Product");
  555. print '<option value="1"';
  556. if (1 == $selected) print ' selected="selected"';
  557. print '>'.$langs->trans("Service");
  558. print '</select>';
  559. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"),1);
  560. }
  561. if (! $forceall && empty($conf->product->enabled) && $conf->service->enabled)
  562. {
  563. print '<input type="hidden" name="'.$htmlname.'" value="1">';
  564. }
  565. if (! $forceall && $conf->product->enabled && empty($conf->service->enabled))
  566. {
  567. print '<input type="hidden" name="'.$htmlname.'" value="0">';
  568. }
  569. }
  570. /**
  571. * Load into cache cache_types_fees, array of types of fees
  572. *
  573. * @return int Nb of lines loaded, 0 if already loaded, <0 if ko
  574. * TODO move in DAO class
  575. */
  576. function load_cache_types_fees()
  577. {
  578. global $langs;
  579. $langs->load("trips");
  580. if (count($this->cache_types_fees)) return 0; // Cache already load
  581. $sql = "SELECT c.code, c.libelle as label";
  582. $sql.= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
  583. $sql.= " ORDER BY lower(c.libelle) ASC";
  584. dol_syslog(get_class($this).'::load_cache_types_fees sql='.$sql, LOG_DEBUG);
  585. $resql=$this->db->query($sql);
  586. if ($resql)
  587. {
  588. $num = $this->db->num_rows($resql);
  589. $i = 0;
  590. while ($i < $num)
  591. {
  592. $obj = $this->db->fetch_object($resql);
  593. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  594. $label=($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  595. $this->cache_types_fees[$obj->code] = $label;
  596. $i++;
  597. }
  598. return $num;
  599. }
  600. else
  601. {
  602. dol_print_error($this->db);
  603. return -1;
  604. }
  605. }
  606. /**
  607. * Return list of types of notes
  608. *
  609. * @param string $selected Preselected type
  610. * @param string $htmlname Name of field in form
  611. * @param int $showempty Add an empty field
  612. * @return void
  613. */
  614. function select_type_fees($selected='',$htmlname='type',$showempty=0)
  615. {
  616. global $user, $langs;
  617. dol_syslog(get_class($this)."::select_type_fees ".$selected.", ".$htmlname, LOG_DEBUG);
  618. $this->load_cache_types_fees();
  619. print '<select class="flat" name="'.$htmlname.'">';
  620. if ($showempty)
  621. {
  622. print '<option value="-1"';
  623. if ($selected == -1) print ' selected="selected"';
  624. print '>&nbsp;</option>';
  625. }
  626. foreach($this->cache_types_fees as $key => $value)
  627. {
  628. print '<option value="'.$key.'"';
  629. if ($key == $selected) print ' selected="selected"';
  630. print '>';
  631. print $value;
  632. print '</option>';
  633. }
  634. print '</select>';
  635. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"),1);
  636. }
  637. /**
  638. * Output html form to select a third party
  639. *
  640. * @param selected Preselected type
  641. * @param htmlname Name of field in form
  642. * @param filter Optionnal filters criteras
  643. * @param showempty Add an empty field
  644. * @param showtype Show third party type in combolist (customer, prospect or supplier)
  645. * @param forcecombo Force to use combo box
  646. */
  647. function select_societes($selected='',$htmlname='socid',$filter='',$showempty=0, $showtype=0, $forcecombo=0)
  648. {
  649. print $this->select_company($selected,$htmlname,$filter,$showempty,$showtype,$forcecombo);
  650. }
  651. /**
  652. * Output html form to select a third party
  653. *
  654. * @param selected Preselected type
  655. * @param htmlname Name of field in form
  656. * @param filter Optionnal filters criteras
  657. * @param showempty Add an empty field
  658. * @param showtype Show third party type in combolist (customer, prospect or supplier)
  659. * @param forcecombo Force to use combo box
  660. */
  661. function select_company($selected='',$htmlname='socid',$filter='',$showempty=0, $showtype=0, $forcecombo=0)
  662. {
  663. global $conf,$user,$langs;
  664. $out='';
  665. // On recherche les societes
  666. $sql = "SELECT s.rowid, s.nom, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  667. $sql.= " FROM ".MAIN_DB_PREFIX ."societe as s";
  668. if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  669. $sql.= " WHERE s.entity = ".$conf->entity;
  670. if ($filter) $sql.= " AND ".$filter;
  671. if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
  672. $sql.= " ORDER BY nom ASC";
  673. dol_syslog("Form::select_societes sql=".$sql);
  674. $resql=$this->db->query($sql);
  675. if ($resql)
  676. {
  677. if ($conf->use_javascript_ajax && $conf->global->COMPANY_USE_SEARCH_TO_SELECT && ! $forcecombo)
  678. {
  679. //$minLength = (is_numeric($conf->global->COMPANY_USE_SEARCH_TO_SELECT)?$conf->global->COMPANY_USE_SEARCH_TO_SELECT:2);
  680. $out.= ajax_combobox($htmlname);
  681. }
  682. $out.= '<select id="'.$htmlname.'" class="flat" name="'.$htmlname.'">';
  683. if ($showempty) $out.= '<option value="-1">&nbsp;</option>';
  684. $num = $this->db->num_rows($resql);
  685. $i = 0;
  686. if ($num)
  687. {
  688. while ($i < $num)
  689. {
  690. $obj = $this->db->fetch_object($resql);
  691. $label=$obj->nom;
  692. if ($showtype)
  693. {
  694. if ($obj->client || $obj->fournisseur) $label.=' (';
  695. if ($obj->client == 1 || $obj->client == 3) $label.=$langs->trans("Customer");
  696. if ($obj->client == 2 || $obj->client == 3) $label.=($obj->client==3?', ':'').$langs->trans("Prospect");
  697. if ($obj->fournisseur) $label.=($obj->client?', ':'').$langs->trans("Supplier");
  698. if ($obj->client || $obj->fournisseur) $label.=')';
  699. }
  700. if ($selected > 0 && $selected == $obj->rowid)
  701. {
  702. $out.= '<option value="'.$obj->rowid.'" selected="selected">'.$label.'</option>';
  703. }
  704. else
  705. {
  706. $out.= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  707. }
  708. $i++;
  709. }
  710. }
  711. $out.= '</select>';
  712. }
  713. else
  714. {
  715. dol_print_error($this->db);
  716. }
  717. return $out;
  718. }
  719. /**
  720. * Return HTML combo list of absolute discounts
  721. *
  722. * @param selected Id remise fixe pre-selectionnee
  723. * @param htmlname Nom champ formulaire
  724. * @param filter Criteres optionnels de filtre
  725. * @param maxvalue Max value for lines that can be selected
  726. * @return int Return number of qualifed lines in list
  727. */
  728. function select_remises($selected='',$htmlname='remise_id',$filter='',$socid, $maxvalue=0)
  729. {
  730. global $langs,$conf;
  731. // On recherche les remises
  732. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  733. $sql.= " re.description, re.fk_facture_source";
  734. $sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re";
  735. $sql.= " WHERE fk_soc = ".$socid;
  736. if ($filter) $sql.= " AND ".$filter;
  737. $sql.= " ORDER BY re.description ASC";
  738. dol_syslog("Form::select_remises sql=".$sql);
  739. $resql=$this->db->query($sql);
  740. if ($resql)
  741. {
  742. print '<select class="flat" name="'.$htmlname.'">';
  743. $num = $this->db->num_rows($resql);
  744. $qualifiedlines=$num;
  745. $i = 0;
  746. if ($num)
  747. {
  748. print '<option value="0">&nbsp;</option>';
  749. while ($i < $num)
  750. {
  751. $obj = $this->db->fetch_object($resql);
  752. $desc=dol_trunc($obj->description,40);
  753. if ($desc=='(CREDIT_NOTE)') $desc=$langs->trans("CreditNote");
  754. if ($desc=='(DEPOSIT)') $desc=$langs->trans("Deposit");
  755. $selectstring='';
  756. if ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected="selected"';
  757. $disabled='';
  758. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue)
  759. {
  760. $qualifiedlines--;
  761. $disabled=' disabled="disabled"';
  762. }
  763. print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
  764. $i++;
  765. }
  766. }
  767. print '</select>';
  768. return $qualifiedlines;
  769. }
  770. else
  771. {
  772. dol_print_error($this->db);
  773. return -1;
  774. }
  775. }
  776. /**
  777. * Return list of all contacts (for a third party or all)
  778. *
  779. * @param socid Id ot third party or 0 for all
  780. * @param selected Id contact pre-selectionne
  781. * @param htmlname Name of HTML field ('none' for a not editable field)
  782. * @param show_empty 0=no empty value, 1=add an empty value
  783. * @param exclude List of contacts id to exclude
  784. * @param limitto Disable answers that are not id in this array list
  785. * @param showfunction Add function into label
  786. * @param moreclass Add more class to class style
  787. * @return int <0 if KO, Nb of contact in list if OK
  788. */
  789. function select_contacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='')
  790. {
  791. global $conf,$langs;
  792. // On recherche les societes
  793. $sql = "SELECT s.rowid, s.name, s.firstname, s.poste FROM";
  794. $sql.= " ".MAIN_DB_PREFIX ."socpeople as s";
  795. $sql.= " WHERE entity = ".$conf->entity;
  796. if ($socid > 0) $sql.= " AND fk_soc=".$socid;
  797. $sql.= " ORDER BY s.name ASC";
  798. dol_syslog("Form::select_contacts sql=".$sql);
  799. $resql=$this->db->query($sql);
  800. if ($resql)
  801. {
  802. $num=$this->db->num_rows($resql);
  803. if ($num == 0) return 0;
  804. if ($htmlname != 'none') print '<select class="flat'.($moreclass?' '.$moreclass:'').'" id="'.$htmlname.'" name="'.$htmlname.'">';
  805. if ($showempty) print '<option value="0"></option>';
  806. $num = $this->db->num_rows($resql);
  807. $i = 0;
  808. if ($num)
  809. {
  810. include_once(DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php');
  811. $contactstatic=new Contact($this->db);
  812. while ($i < $num)
  813. {
  814. $obj = $this->db->fetch_object($resql);
  815. $contactstatic->id=$obj->rowid;
  816. $contactstatic->name=$obj->name;
  817. $contactstatic->firstname=$obj->firstname;
  818. if ($htmlname != 'none')
  819. {
  820. $disabled=0;
  821. if (is_array($exclude) && count($exclude) && in_array($obj->rowid,$exclude)) $disabled=1;
  822. if (is_array($limitto) && count($limitto) && ! in_array($obj->rowid,$limitto)) $disabled=1;
  823. if ($selected && $selected == $obj->rowid)
  824. {
  825. print '<option value="'.$obj->rowid.'"';
  826. if ($disabled) print ' disabled="disabled"';
  827. print ' selected="selected">';
  828. print $contactstatic->getFullName($langs);
  829. if ($showfunction && $obj->poste) print ' ('.$obj->poste.')';
  830. print '</option>';
  831. }
  832. else
  833. {
  834. print '<option value="'.$obj->rowid.'"';
  835. if ($disabled) print ' disabled="disabled"';
  836. print '>';
  837. print $contactstatic->getFullName($langs);
  838. if ($showfunction && $obj->poste) print ' ('.$obj->poste.')';
  839. print '</option>';
  840. }
  841. }
  842. else
  843. {
  844. if ($selected == $obj->rowid)
  845. {
  846. print $contactstatic->getFullName($langs);
  847. if ($showfunction && $obj->poste) print ' ('.$obj->poste.')';
  848. }
  849. }
  850. $i++;
  851. }
  852. }
  853. if ($htmlname != 'none')
  854. {
  855. print '</select>';
  856. }
  857. return $num;
  858. }
  859. else
  860. {
  861. dol_print_error($this->db);
  862. return -1;
  863. }
  864. }
  865. /**
  866. * Return select list of users
  867. *
  868. * @param selected Id user preselected
  869. * @param htmlname Field name in form
  870. * @param show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  871. * @param exclude Array list of users id to exclude
  872. * @param disabled If select list must be disabled
  873. * @param include Array list of users id to include
  874. * @param enableonly Array list of users id to be enabled. All other must be disabled
  875. * @param force_entity Possibility to force entity
  876. */
  877. function select_users($selected='',$htmlname='userid',$show_empty=0,$exclude='',$disabled=0,$include='',$enableonly='',$force_entity=0)
  878. {
  879. print $this->select_dolusers($selected,$htmlname,$show_empty,$exclude,$disabled,$include,$enableonly,$force_entity);
  880. }
  881. /**
  882. * Return select list of users
  883. *
  884. * @param selected User id or user object of user preselected. If -1, we use id of current user.
  885. * @param htmlname Field name in form
  886. * @param show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  887. * @param exclude Array list of users id to exclude
  888. * @param disabled If select list must be disabled
  889. * @param include Array list of users id to include
  890. * @param enableonly Array list of users id to be enabled. All other must be disabled
  891. * @param force_entity Possibility to force entity
  892. */
  893. function select_dolusers($selected='',$htmlname='userid',$show_empty=0,$exclude='',$disabled=0,$include='',$enableonly='',$force_entity=0)
  894. {
  895. global $conf,$user,$langs;
  896. // If no preselected user defined, we take current user
  897. if ($selected < -1 && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected=$user->id;
  898. // Permettre l'exclusion d'utilisateurs
  899. if (is_array($exclude)) $excludeUsers = implode("','",$exclude);
  900. // Permettre l'inclusion d'utilisateurs
  901. if (is_array($include)) $includeUsers = implode("','",$include);
  902. $out='';
  903. // On recherche les utilisateurs
  904. $sql = "SELECT u.rowid, u.name, u.firstname, u.login, u.admin, u.entity";
  905. if(! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  906. {
  907. $sql.= ", e.label";
  908. }
  909. $sql.= " FROM ".MAIN_DB_PREFIX ."user as u";
  910. if(! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  911. {
  912. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX ."entity as e on e.rowid=u.entity";
  913. if ($force_entity) $sql.= " WHERE u.entity IN (0,".$force_entity.")";
  914. else $sql.= " WHERE u.entity IS NOT NULL";
  915. }
  916. else
  917. {
  918. $sql.= " WHERE u.entity IN (0,".$conf->entity.")";
  919. }
  920. if (is_array($exclude) && $excludeUsers) $sql.= " AND u.rowid NOT IN ('".$excludeUsers."')";
  921. if (is_array($include) && $includeUsers) $sql.= " AND u.rowid IN ('".$includeUsers."')";
  922. $sql.= " ORDER BY u.name ASC";
  923. dol_syslog("Form::select_dolusers sql=".$sql);
  924. $resql=$this->db->query($sql);
  925. if ($resql)
  926. {
  927. $num = $this->db->num_rows($resql);
  928. $i = 0;
  929. if ($num)
  930. {
  931. $out.= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled="disabled"':'').'>';
  932. if ($show_empty) $out.= '<option value="-1"'.($id==-1?' selected="selected"':'').'>&nbsp;</option>'."\n";
  933. $userstatic=new User($this->db);
  934. while ($i < $num)
  935. {
  936. $obj = $this->db->fetch_object($resql);
  937. $userstatic->id=$obj->rowid;
  938. $userstatic->nom=$obj->name;
  939. $userstatic->prenom=$obj->firstname;
  940. $disableline=0;
  941. if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=1;
  942. if ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && $selected == $obj->rowid))
  943. {
  944. $out.= '<option value="'.$obj->rowid.'"';
  945. if ($disableline) $out.= ' disabled="disabled"';
  946. $out.= ' selected="selected">';
  947. }
  948. else
  949. {
  950. $out.= '<option value="'.$obj->rowid.'"';
  951. if ($disableline) $out.= ' disabled="disabled"';
  952. $out.= '>';
  953. }
  954. $out.= $userstatic->getFullName($langs);
  955. if(! empty($conf->multicompany->enabled) && empty($conf->multicompany->transverse_mode) && $conf->entity == 1 && $user->admin && ! $user->entity)
  956. {
  957. if ($obj->admin && ! $obj->entity) $out.=" (".$langs->trans("AllEntities").")";
  958. else $out.=" (".$obj->label.")";
  959. }
  960. //if ($obj->admin) $out.= ' *';
  961. if ($conf->global->MAIN_SHOW_LOGIN) $out.= ' ('.$obj->login.')';
  962. $out.= '</option>';
  963. $i++;
  964. }
  965. }
  966. else
  967. {
  968. $out.= '<select class="flat" name="'.$htmlname.'" disabled="disabled">';
  969. $out.= '<option value="">'.$langs->trans("None").'</option>';
  970. }
  971. $out.= '</select>';
  972. }
  973. else
  974. {
  975. dol_print_error($this->db);
  976. }
  977. return $out;
  978. }
  979. /**
  980. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_do
  981. *
  982. * @param int $selected Preselected products
  983. * @param string $htmlname Name of HTML seletc field (must be unique in page)
  984. * @param int $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  985. * @param int $limit Limit on number of returned lines
  986. * @param int $price_level Level of price to show
  987. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  988. * @param int $finished 2=all, 1=finished, 0=raw material
  989. * @param string $selected_input_value Value of preselected input text (with ajax)
  990. * @return void
  991. */
  992. function select_produits($selected='',$htmlname='productid',$filtertype='',$limit=20,$price_level=0,$status=1,$finished=2,$selected_input_value='',$hidelabel=0)
  993. {
  994. global $langs,$conf;
  995. $price_level = (! empty($price_level) ? $price_level : 0);
  996. if ($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)
  997. {
  998. if ($selected && empty($selected_input_value))
  999. {
  1000. require_once(DOL_DOCUMENT_ROOT."/product/class/product.class.php");
  1001. $product = new Product($this->db);
  1002. $product->fetch($selected);
  1003. $selected_input_value=$product->ref;
  1004. }
  1005. // mode=1 means customers products
  1006. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajaxproducts.php', 'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT);
  1007. if (! $hidelabel) print $langs->trans("RefOrLabel").' : ';
  1008. print '<input type="text" size="20" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'" />';
  1009. }
  1010. else
  1011. {
  1012. $this->select_produits_do($selected,$htmlname,$filtertype,$limit,$price_level,'',$status,$finished,0);
  1013. }
  1014. print '<br>';
  1015. }
  1016. /**
  1017. * Return list of products for a customer
  1018. *
  1019. * @param int $selected Preselected product
  1020. * @param string $htmlname Name of select html
  1021. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1022. * @param int $limit Limite sur le nombre de lignes retournees
  1023. * @param int $price_level Level of price to show
  1024. * @param string $filterkey Filter on product
  1025. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  1026. * @param int $finished Filter on finished field: 2=No filter
  1027. * @param int $disableout Disable print output
  1028. * @return array Array of keys for json
  1029. */
  1030. function select_produits_do($selected='',$htmlname='productid',$filtertype='',$limit=20,$price_level=0,$filterkey='',$status=1,$finished=2,$disableout=0)
  1031. {
  1032. global $langs,$conf,$user,$db;
  1033. $sql = "SELECT ";
  1034. $sql.= " p.rowid, p.label, p.ref, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.duration, p.stock";
  1035. // Multilang : we add translation
  1036. if ($conf->global->MAIN_MULTILANGS)
  1037. {
  1038. $sql.= ", pl.label as label_translated";
  1039. }
  1040. $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
  1041. // Multilang : we add translation
  1042. if ($conf->global->MAIN_MULTILANGS)
  1043. {
  1044. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='". $langs->getDefaultLang() ."'";
  1045. }
  1046. $sql.= ' WHERE p.entity IN (0,'.(! empty($conf->entities['product']) ? $conf->entities['product'] : $conf->entity).')';
  1047. if ($finished == 0)
  1048. {
  1049. $sql.= " AND p.finished = ".$finished;
  1050. }
  1051. elseif ($finished == 1)
  1052. {
  1053. $sql.= " AND p.finished = ".$finished;
  1054. if ($status >= 0) $sql.= " AND p.tosell = ".$status;
  1055. }
  1056. elseif ($status >= 0)
  1057. {
  1058. $sql.= " AND p.tosell = ".$status;
  1059. }
  1060. if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$filtertype;
  1061. // Add criteria on ref/label
  1062. if ($filterkey && $filterkey != '')
  1063. {
  1064. if (! empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)) // Can use index
  1065. {
  1066. $sql.=" AND (p.ref LIKE '".$filterkey."%' OR p.label LIKE '".$filterkey."%'";
  1067. if ($conf->global->MAIN_MULTILANGS) $sql.=" OR pl.label LIKE '".$filterkey."%'";
  1068. $sql.=")";
  1069. }
  1070. else
  1071. {
  1072. $sql.=" AND (p.ref LIKE '%".$filterkey."%' OR p.label LIKE '%".$filterkey."%'";
  1073. if ($conf->global->MAIN_MULTILANGS) $sql.=" OR pl.label LIKE '%".$filterkey."%'";
  1074. $sql.=")";
  1075. }
  1076. }
  1077. $sql.= $db->order("p.ref");
  1078. $sql.= $db->plimit($limit);
  1079. // Build output string
  1080. $outselect='';
  1081. $outjson=array();
  1082. dol_syslog("Form::select_produits_do search product sql=".$sql, LOG_DEBUG);
  1083. $result=$this->db->query($sql);
  1084. if ($result)
  1085. {
  1086. $num = $this->db->num_rows($result);
  1087. $outselect.='<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
  1088. $outselect.='<option value="0" selected="selected">&nbsp;</option>';
  1089. $i = 0;
  1090. while ($num && $i < $num)
  1091. {
  1092. $outkey='';
  1093. $outval='';
  1094. $outref='';
  1095. $objp = $this->db->fetch_object($result);
  1096. $label=$objp->label;
  1097. if (! empty($objp->label_translated)) $label=$objp->label_translated;
  1098. if ($filterkey && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
  1099. $outkey=$objp->rowid;
  1100. $outref=$objp->ref;
  1101. $opt = '<option value="'.$objp->rowid.'"';
  1102. $opt.= ($objp->rowid == $selected)?' selected="selected"':'';
  1103. if ($conf->stock->enabled && $objp->fk_product_type == 0 && isset($objp->stock))
  1104. {
  1105. if ($objp->stock > 0)
  1106. {
  1107. $opt.= ' style="background-color:#32CD32; color:#F5F5F5;"';
  1108. }
  1109. else if ($objp->stock <= 0)
  1110. {
  1111. $opt.= ' style="background-color:#FF0000; color:#F5F5F5;"';
  1112. }
  1113. }
  1114. $opt.= '>';
  1115. $opt.= $langs->convToOutputCharset($objp->ref).' - '.$langs->convToOutputCharset(dol_trunc($label,32)).' - ';
  1116. $objRef = $objp->ref;
  1117. if ($filterkey && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
  1118. $outval.=$objRef.' - '.dol_trunc($label,32).' - ';
  1119. $found=0;
  1120. $currencytext=$langs->trans("Currency".$conf->monnaie);
  1121. $currencytextnoent=$langs->transnoentities("Currency".$conf->monnaie);
  1122. if (dol_strlen($currencytext) > 10) $currencytext=$conf->monnaie; // If text is too long, we use the short code
  1123. if (dol_strlen($currencytextnoent) > 10) $currencytextnoent=$conf->monnaie; // If text is too long, we use the short code
  1124. // Multiprice
  1125. if ($price_level >= 1) // If we need a particular price level (from 1 to 6)
  1126. {
  1127. $sql= "SELECT price, price_ttc, price_base_type ";
  1128. $sql.= "FROM ".MAIN_DB_PREFIX."product_price ";
  1129. $sql.= "WHERE fk_product='".$objp->rowid."'";
  1130. $sql.= " AND price_level=".$price_level;
  1131. $sql.= " ORDER BY date_price";
  1132. $sql.= " DESC limit 1";
  1133. dol_syslog("Form::select_produits_do search price for level '.$price_level.' sql=".$sql);
  1134. $result2 = $this->db->query($sql);
  1135. if ($result2)
  1136. {
  1137. $objp2 = $this->db->fetch_object($result2);
  1138. if ($objp2)
  1139. {
  1140. $found=1;
  1141. if ($objp2->price_base_type == 'HT')
  1142. {
  1143. $opt.= price($objp2->price,1).' '.$currencytext.' '.$langs->trans("HT");
  1144. $outval.= price($objp2->price,1).' '.$currencytextnoent.' '.$langs->transnoentities("HT");
  1145. }
  1146. else
  1147. {
  1148. $opt.= price($objp2->price_ttc,1).' '.$currencytext.' '.$langs->trans("TTC");
  1149. $outval.= price($objp2->price_ttc,1).' '.$currencytextnoent.' '.$langs->transnoentities("TTC");
  1150. }
  1151. }
  1152. }
  1153. else
  1154. {
  1155. dol_print_error($this->db);
  1156. }
  1157. }
  1158. // If level no defined or multiprice not found, we used the default price
  1159. if (! $found)
  1160. {
  1161. if ($objp->price_base_type == 'HT')
  1162. {
  1163. $opt.= price($objp->price,1).' '.$currencytext.' '.$langs->trans("HT");
  1164. $outval.= price($objp->price,1).' '.$currencytextnoent.' '.$langs->transnoentities("HT");
  1165. }
  1166. else
  1167. {
  1168. $opt.= price($objp->price_ttc,1).' '.$currencytext.' '.$langs->trans("TTC");
  1169. $outval.= price($objp->price_ttc,1).' '.$currencytextnoent.' '.$langs->transnoentities("TTC");
  1170. }
  1171. }
  1172. if ($conf->stock->enabled && isset($objp->stock) && $objp->fk_product_type == 0)
  1173. {
  1174. $opt.= ' - '.$langs->trans("Stock").':'.$objp->stock;
  1175. $outval.=' - '.$langs->transnoentities("Stock").':'.$objp->stock;
  1176. }
  1177. if ($objp->duration)
  1178. {
  1179. $duration_value = substr($objp->duration,0,dol_strlen($objp->duration)-1);
  1180. $duration_unit = substr($objp->duration,-1);
  1181. if ($duration_value > 1)
  1182. {
  1183. $dur=array("h"=>$langs->trans("Hours"),"d"=>$langs->trans("Days"),"w"=>$langs->trans("Weeks"),"m"=>$langs->trans("Months"),"y"=>$langs->trans("Years"));
  1184. }
  1185. else
  1186. {
  1187. $dur=array("h"=>$langs->trans("Hour"),"d"=>$langs->trans("Day"),"w"=>$langs->trans("Week"),"m"=>$langs->trans("Month"),"y"=>$langs->trans("Year"));
  1188. }
  1189. $opt.= ' - '.$duration_value.' '.$langs->trans($dur[$duration_unit]);
  1190. $outval.=' - '.$duration_value.' '.$langs->transnoentities($dur[$duration_unit]);
  1191. }
  1192. $opt.= "</option>\n";
  1193. // Add new entry
  1194. // "key" value of json key array is used by jQuery automatically as selected value
  1195. // "label" value of json key array is used by jQuery automatically as text for combo box
  1196. $outselect.=$opt;
  1197. array_push($outjson,array('key'=>$outkey,'value'=>$outref,'label'=>$outval));
  1198. $i++;
  1199. }
  1200. $outselect.='</select>';
  1201. $this->db->free($result);
  1202. if (empty($disableout)) print $outselect;
  1203. return $outjson;
  1204. }
  1205. else
  1206. {
  1207. dol_print_error($db);
  1208. }
  1209. }
  1210. /**
  1211. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_fournisseurs_do
  1212. *
  1213. * @param int $socid Id third party
  1214. * @param string $selected Preselected product
  1215. * @param string $htmlname Name of HTML Select
  1216. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1217. * @param string $filtre For a SQL filter
  1218. * @return void
  1219. */
  1220. function select_produits_fournisseurs($socid,$selected='',$htmlname='productid',$filtertype='',$filtre)
  1221. {
  1222. global $langs,$conf;
  1223. if ($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)
  1224. {
  1225. // mode=2 means suppliers products
  1226. print ajax_autocompleter('', $htmlname, DOL_URL_ROOT.'/product/ajaxproducts.php', ($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT);
  1227. print $langs->trans("RefOrLabel").' : <input type="text" size="16" name="search_'.$htmlname.'" id="search_'.$htmlname.'">';
  1228. print '<br>';
  1229. }
  1230. else
  1231. {
  1232. $this->select_produits_fournisseurs_do($socid,$selected,$htmlname,$filtertype,$filtre,'',-1,0);
  1233. }
  1234. }
  1235. /**
  1236. * Retourne la liste des produits de fournisseurs
  1237. *
  1238. * @param socid Id societe fournisseur (0 pour aucun filtre)
  1239. * @param selected Produit pre-selectionne
  1240. * @param htmlname Nom de la zone select
  1241. * @param filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1242. * @param filtre Pour filtre sql
  1243. * @param filterkey Filtre des produits
  1244. * @param status -1=Return all products, 0=Products not on sell, 1=Products on sell
  1245. * @param disableout Disable print output
  1246. * @return array Array of keys for json
  1247. */
  1248. function select_produits_fournisseurs_do($socid,$selected='',$htmlname='productid',$filtertype='',$filtre='',$filterkey='',$statut=-1,$disableout=0)
  1249. {
  1250. global $langs,$conf;
  1251. $langs->load('stocks');
  1252. $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration,";
  1253. $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.unitprice,";
  1254. $sql.= " s.nom";
  1255. $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
  1256. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  1257. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  1258. $sql.= " WHERE p.entity = ".$conf->entity;
  1259. $sql.= " AND p.tobuy = 1";
  1260. if ($socid) $sql.= " AND pfp.fk_soc = ".$socid;
  1261. if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$filtertype;
  1262. if (! empty($filtre)) $sql.=" ".$filtre;
  1263. // Add criteria on ref/label
  1264. if ($filterkey && $filterkey != '')
  1265. {
  1266. if (! empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE))
  1267. {
  1268. $sql.=" AND (pfp.ref_fourn LIKE '".$filterkey."%' OR p.ref LIKE '".$filterkey."%' OR p.label LIKE '".$filterkey."%')";
  1269. }
  1270. else
  1271. {
  1272. $sql.=" AND (pfp.ref_fourn LIKE '%".$filterkey."%' OR p.ref LIKE '%".$filterkey."%' OR p.label LIKE '%".$filterkey."%')";
  1273. }
  1274. }
  1275. $sql.= " ORDER BY pfp.ref_fourn DESC";
  1276. // Build output string
  1277. $outselect='';
  1278. $outjson=array();
  1279. dol_syslog(get_class($this)."::select_produits_fournisseurs_do sql=".$sql,LOG_DEBUG);
  1280. $result=$this->db->query($sql);
  1281. if ($result)
  1282. {
  1283. $num = $this->db->num_rows($result);
  1284. $outselect.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">';
  1285. if (! $selected) $outselect.='<option value="0" selected="selected">&nbsp;</option>';
  1286. else $outselect.='<option value="0">&nbsp;</option>';
  1287. $i = 0;
  1288. while ($i < $num)
  1289. {
  1290. $objp = $this->db->fetch_object($result);
  1291. $outkey=$objp->idprodfournprice;
  1292. $outref=$objp->ref;
  1293. $outval='';
  1294. $opt = '<option value="'.$objp->idprodfournprice.'"';
  1295. if ($selected == $objp->idprodfournprice) $opt.= ' selected="selected"';
  1296. if ($objp->fprice == '') $opt.=' disabled="disabled"';
  1297. $opt.= '>';
  1298. $objRef = $objp->ref;
  1299. if ($filterkey && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
  1300. $objRefFourn = $objp->ref_fourn;
  1301. if ($filterkey && $filterkey != '') $objRefFourn=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRefFourn,1);
  1302. $label = $objp->label;
  1303. if ($filterkey && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
  1304. $opt.=$langs->convToOutputCharset($objp->ref).' ('.$langs->convToOutputCharset($objp->ref_fourn).') - ';
  1305. $outval.=$objRef.' ('.$objRefFourn.') - ';
  1306. $opt.=$langs->convToOutputCharset(dol_trunc($objp->label,18)).' - ';
  1307. $outval.=dol_trunc($label,18).' - ';
  1308. if ($objp->fprice != '') // Keep != ''
  1309. {
  1310. $currencytext=$langs->trans("Currency".$conf->monnaie);
  1311. $currencytextnoent=$langs->transnoentities("Currency".$conf->monnaie);
  1312. if (dol_strlen($currencytext) > 10) $currencytext=$conf->monnaie; // If text is too long, we use the short code
  1313. if (dol_strlen($currencytextnoent) > 10) $currencytextnoent=$conf->monnaie; // If text is too long, we use the short code
  1314. $opt.= price($objp->fprice).' '.$currencytext."/".$objp->quantity;
  1315. $outval.= price($objp->fprice).' '.$currencytextnoent."/".$objp->quantity;
  1316. if ($objp->quantity == 1)
  1317. {
  1318. $opt.= strtolower($langs->trans("Unit"));
  1319. $outval.=strtolower($langs->transnoentities("Unit"));
  1320. }
  1321. else
  1322. {
  1323. $opt.= strtolower($langs->trans("Units"));
  1324. $outval.=strtolower($langs->transnoentities("Units"));
  1325. }
  1326. if ($objp->quantity >= 1)
  1327. {
  1328. $opt.=" (".price($objp->unitprice).' '.$currencytext."/".strtolower($langs->trans("Unit")).")";
  1329. $outval.=" (".price($objp->unitprice).' '.$currencytextnoent."/".strtolower($langs->transnoentities("Unit")).")";
  1330. }
  1331. if ($objp->duration)
  1332. {
  1333. $opt .= " - ".$objp->duration;
  1334. $outval.=" - ".$objp->duration;
  1335. }
  1336. if (! $socid)
  1337. {
  1338. $opt .= " - ".dol_trunc($objp->nom,8);
  1339. $outval.=" - ".dol_trunc($objp->nom,8);
  1340. }
  1341. }
  1342. else
  1343. {
  1344. $opt.= $langs->trans("NoPriceDefinedForThisSupplier");
  1345. $outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
  1346. }
  1347. $opt .= "</option>\n";
  1348. // Add new entry
  1349. // "key" value of json key array is used by jQuery automatically as selected value
  1350. // "label" value of json key array is used by jQuery automatically as text for combo box
  1351. $outselect.=$opt;
  1352. array_push($outjson,array('key'=>$outkey,'value'=>$outref,'label'=>$outval));
  1353. $i++;
  1354. }
  1355. $outselect.='</select>';
  1356. $this->db->free($result);
  1357. if (empty($disableout)) print $outselect;
  1358. return $outjson;
  1359. }
  1360. else
  1361. {
  1362. dol_print_error($db);
  1363. }
  1364. }
  1365. /**
  1366. * Return list of suppliers prices for a product
  1367. *
  1368. * @param int $productid Id of product
  1369. * @param string $htmlname Name of HTML field
  1370. * @return void
  1371. */
  1372. function select_product_fourn_price($productid,$htmlname='productfournpriceid')
  1373. {
  1374. global $langs,$conf;
  1375. $langs->load('stocks');
  1376. $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration,";
  1377. $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.unitprice,";
  1378. $sql.= " s.nom";
  1379. $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
  1380. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  1381. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  1382. $sql.= " WHERE p.entity = ".$conf->entity;
  1383. $sql.= " AND p.tobuy = 1";
  1384. $sql.= " AND s.fournisseur = 1";
  1385. $sql.= " AND p.rowid = ".$productid;
  1386. $sql.= " ORDER BY s.nom, pfp.ref_fourn DESC";
  1387. dol_syslog("Form::select_product_fourn_price sql=".$sql,LOG_DEBUG);
  1388. $result=$this->db->query($sql);
  1389. if ($result)
  1390. {
  1391. $num = $this->db->num_rows($result);
  1392. $form = '<select class="flat" name="'.$htmlname.'">';
  1393. if (! $num)
  1394. {
  1395. $form.= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
  1396. }
  1397. else
  1398. {
  1399. $form.= '<option value="0">&nbsp;</option>';
  1400. $i = 0;
  1401. while ($i < $num)
  1402. {
  1403. $objp = $this->db->fetch_object($result);
  1404. $opt = '<option value="'.$objp->idprodfournprice.'"';
  1405. $opt.= '>'.$objp->nom.' - '.$objp->ref_fourn.' - ';
  1406. if ($objp->quantity == 1)
  1407. {
  1408. $opt.= price($objp->fprice);
  1409. $opt.= $langs->trans("Currency".$conf->monnaie)."/";
  1410. }
  1411. $opt.= $objp->quantity.' ';
  1412. if ($objp->quantity == 1)
  1413. {
  1414. $opt.= strtolower($langs->trans("Unit"));
  1415. }
  1416. else
  1417. {
  1418. $opt.= strtolower($langs->trans("Units"));
  1419. }
  1420. if ($objp->quantity > 1)
  1421. {
  1422. $opt.=" - ";
  1423. $opt.= price($objp->unitprice).$langs->trans("Currency".$conf->monnaie)."/".strtolower($langs->trans("Unit"));
  1424. }
  1425. if ($objp->duration) $opt .= " - ".$objp->duration;
  1426. $opt .= "</option>\n";
  1427. $form.= $opt;
  1428. $i++;
  1429. }
  1430. $form.= '</select>';
  1431. $this->db->free($result);
  1432. }
  1433. return $form;
  1434. }
  1435. else
  1436. {
  1437. dol_print_error($db);
  1438. }
  1439. }
  1440. /**
  1441. * Return list of delivery address
  1442. *
  1443. * @param string $selected Id contact pre-selectionn
  1444. * @param int $socid Id of company
  1445. * @param string $htmlname Name of HTML field
  1446. * @param int $showempty Add an empty field
  1447. * @return void
  1448. */
  1449. function select_address($selected='', $socid, $htmlname='address_id',$showempty=0)
  1450. {
  1451. // On recherche les utilisateurs
  1452. $sql = "SELECT a.rowid, a.label";
  1453. $sql .= " FROM ".MAIN_DB_PREFIX ."societe_address as a";
  1454. $sql .= " WHERE a.fk_soc = ".$socid;
  1455. $sql .= " ORDER BY a.label ASC";
  1456. dol_syslog("Form::select_address sql=".$sql);
  1457. $resql=$this->db->query($sql);
  1458. if ($resql)
  1459. {
  1460. print '<select class="flat" name="'.$htmlname.'">';
  1461. if ($showempty) print '<option value="0">&nbsp;</option>';
  1462. $num = $this->db->num_rows($resql);
  1463. $i = 0;
  1464. if ($num)
  1465. {
  1466. while ($i < $num)
  1467. {
  1468. $obj = $this->db->fetch_object($resql);
  1469. if ($selected && $selected == $obj->rowid)
  1470. {
  1471. print '<option value="'.$obj->rowid.'" selected="selected">'.$obj->label.'</option>';
  1472. }
  1473. else
  1474. {
  1475. print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
  1476. }
  1477. $i++;
  1478. }
  1479. }
  1480. print '</select>';
  1481. return $num;
  1482. }
  1483. else
  1484. {
  1485. dol_print_error($this->db);
  1486. }
  1487. }
  1488. /**
  1489. * Charge dans cache la liste des conditions de paiements possibles
  1490. *
  1491. * @return int Nb lignes chargees, 0 si deja chargees, <0 si ko
  1492. */
  1493. function load_cache_conditions_paiements()
  1494. {
  1495. global $langs;
  1496. if (count($this->cache_conditions_paiements)) return 0; // Cache deja charge
  1497. $sql = "SELECT rowid, code, libelle";
  1498. $sql.= " FROM ".MAIN_DB_PREFIX.'c_payment_term';
  1499. $sql.= " WHERE active=1";
  1500. $sql.= " ORDER BY sortorder";
  1501. dol_syslog('Form::load_cache_conditions_paiements sql='.$sql,LOG_DEBUG);
  1502. $resql = $this->db->query($sql);
  1503. if ($resql)
  1504. {
  1505. $num = $this->db->num_rows($resql);
  1506. $i = 0;
  1507. while ($i < $num)
  1508. {
  1509. $obj = $this->db->fetch_object($resql);
  1510. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1511. $libelle=($langs->trans("PaymentConditionShort".$obj->code)!=("PaymentConditionShort".$obj->code)?$langs->trans("PaymentConditionShort".$obj->code):($obj->libelle!='-'?$obj->libelle:''));
  1512. $this->cache_conditions_paiements[$obj->rowid]['code'] =$obj->code;
  1513. $this->cache_conditions_paiements[$obj->rowid]['label']=$libelle;
  1514. $i++;
  1515. }
  1516. return 1;
  1517. }
  1518. else {
  1519. dol_print_error($this->db);
  1520. return -1;
  1521. }
  1522. }
  1523. /**
  1524. * Charge dans cache la liste des dĂŠlais de livraison possibles
  1525. *
  1526. * @return int Nb lignes chargees, 0 si deja chargees, <0 si ko
  1527. */
  1528. function load_cache_availability()
  1529. {
  1530. global $langs;
  1531. if (count($this->cache_availability)) return 0; // Cache deja charge
  1532. $sql = "SELECT rowid, code, label";
  1533. $sql.= " FROM ".MAIN_DB_PREFIX.'c_availability';
  1534. $sql.= " WHERE active=1";
  1535. $sql.= " ORDER BY rowid";
  1536. dol_syslog('Form::load_cache_availability sql='.$sql,LOG_DEBUG);
  1537. $resql = $this->db->query($sql);
  1538. if ($resql)
  1539. {
  1540. $num = $this->db->num_rows($resql);
  1541. $i = 0;
  1542. while ($i < $num)
  1543. {
  1544. $obj = $this->db->fetch_object($resql);
  1545. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1546. $label=($langs->trans("AvailabilityType".$obj->code)!=("AvailabilityType".$obj->code)?$langs->trans("AvailabilityType".$obj->code):($obj->label!='-'?$obj->label:''));
  1547. $this->cache_availability[$obj->rowid]['code'] =$obj->code;
  1548. $this->cache_availability[$obj->rowid]['label']=$label;
  1549. $i++;
  1550. }
  1551. return 1;
  1552. }
  1553. else {
  1554. dol_print_error($this->db);
  1555. return -1;
  1556. }
  1557. }
  1558. /**
  1559. * Retourne la liste des types de delais de livraison possibles
  1560. *
  1561. * @param selected Id du type de delais pre-selectionne
  1562. * @param htmlname Nom de la zone select
  1563. * @param filtertype To add a filter
  1564. * @param addempty Add empty entry
  1565. */
  1566. function select_availability($selected='',$htmlname='availid',$filtertype='',$addempty=0)
  1567. {
  1568. global $langs,$user;
  1569. $this->load_cache_availability();
  1570. print '<select class="flat" name="'.$htmlname.'">';
  1571. if ($addempty) print '<option value="0">&nbsp;</option>';
  1572. foreach($this->cache_availability as $id => $arrayavailability)
  1573. {
  1574. if ($selected == $id)
  1575. {
  1576. print '<option value="'.$id.'" selected="selected">';
  1577. }
  1578. else
  1579. {
  1580. print '<option value="'.$id.'">';
  1581. }
  1582. print $arrayavailability['label'];
  1583. print '</option>';
  1584. }
  1585. print '</select>';
  1586. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"),1);
  1587. }
  1588. /**
  1589. * Load into cache cache_demand_reason, array of input reasons
  1590. *
  1591. * @return int Nb of lines loaded, 0 if already loaded, <0 if ko
  1592. */
  1593. function load_cache_demand_reason()
  1594. {
  1595. global $langs;
  1596. if (count($this->cache_demand_reason)) return 0; // Cache already loaded
  1597. $sql = "SELECT rowid, code, label";
  1598. $sql.= " FROM ".MAIN_DB_PREFIX.'c_input_reason';
  1599. $sql.= " WHERE active=1";
  1600. $sql.= " ORDER BY rowid";
  1601. dol_syslog('Form::load_cache_demand_reason sql='.$sql,LOG_DEBUG);
  1602. $resql = $this->db->query($sql);
  1603. if ($resql)
  1604. {
  1605. $num = $this->db->num_rows($resql);
  1606. $i = 0;
  1607. $tmparray=array();
  1608. while ($i < $num)
  1609. {
  1610. $obj = $this->db->fetch_object($resql);
  1611. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1612. $label=($langs->trans("DemandReasonType".$obj->code)!=("DemandReasonType".$obj->code)?$langs->trans("DemandReasonType".$obj->code):($obj->label!='-'?$obj->label:''));
  1613. $tmparray[$obj->rowid]['id'] =$obj->rowid;
  1614. $tmparray[$obj->rowid]['code'] =$obj->code;
  1615. $tmparray[$obj->rowid]['label']=$label;
  1616. $i++;
  1617. }
  1618. $this->cache_demand_reason=dol_sort_array($tmparray,'label', $order='asc');
  1619. unset($tmparray);
  1620. return 1;
  1621. }
  1622. else {
  1623. dol_print_error($this->db);
  1624. return -1;
  1625. }
  1626. }
  1627. /**
  1628. * Return list of events that triggered an object creation
  1629. *
  1630. * @param selected Id du type d'origine pre-selectionne
  1631. * @param htmlname Nom de la zone select
  1632. * @param exclude To exclude a code value (Example: SRC_PROP)
  1633. * @param addempty Add an empty entry
  1634. */
  1635. function select_demand_reason($selected='',$htmlname='demandreasonid',$exclude='',$addempty=0)
  1636. {
  1637. global $langs,$user;
  1638. $this->load_cache_demand_reason();
  1639. print '<select class="flat" name="'.$htmlname.'">';
  1640. if ($addempty) print '<option value="0"'.(empty($selected)?' selected="selected"':'').'>&nbsp;</option>';
  1641. foreach($this->cache_demand_reason as $id => $arraydemandreason)
  1642. {
  1643. if ($arraydemandreason['code']==$exclude) continue;
  1644. if ($selected == $arraydemandreason['id'])
  1645. {
  1646. print '<option value="'.$arraydemandreason['id'].'" selected="selected">';
  1647. }
  1648. else
  1649. {
  1650. print '<option value="'.$arraydemandreason['id'].'">';
  1651. }
  1652. print $arraydemandreason['label'];
  1653. print '</option>';
  1654. }
  1655. print '</select>';
  1656. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"),1);
  1657. }
  1658. /**
  1659. * Charge dans cache la liste des types de paiements possibles
  1660. *
  1661. * @return int Nb lignes chargees, 0 si deja chargees, <0 si ko
  1662. */
  1663. function load_cache_types_paiements()
  1664. {
  1665. global $langs;
  1666. if (count($this->cache_types_paiements)) return 0; // Cache deja charge
  1667. $sql = "SELECT id, code, libelle, type";
  1668. $sql.= " FROM ".MAIN_DB_PREFIX."c_paiement";
  1669. $sql.= " WHERE active > 0";
  1670. $sql.= " ORDER BY id";
  1671. dol_syslog('Form::load_cache_types_paiements sql='.$sql,LOG_DEBUG);
  1672. $resql = $this->db->query($sql);
  1673. if ($resql)
  1674. {
  1675. $num = $this->db->num_rows($resql);
  1676. $i = 0;
  1677. while ($i < $num)
  1678. {
  1679. $obj = $this->db->fetch_object($resql);
  1680. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1681. $libelle=($langs->trans("PaymentTypeShort".$obj->code)!=("PaymentTypeShort".$obj->code)?$langs->trans("PaymentTypeShort".$obj->code):($obj->libelle!='-'?$obj->libelle:''));
  1682. $this->cache_types_paiements[$obj->id]['code'] =$obj->code;
  1683. $this->cache_types_paiements[$obj->id]['label']=$libelle;
  1684. $this->cache_types_paiements[$obj->id]['type'] =$obj->type;
  1685. $i++;
  1686. }
  1687. return $num;
  1688. }
  1689. else
  1690. {
  1691. dol_print_error($this->db);
  1692. return -1;
  1693. }
  1694. }
  1695. /**
  1696. * Retourne la liste des types de paiements possibles
  1697. *
  1698. * @param selected Id du type de paiement pre-selectionne
  1699. * @param htmlname Nom de la zone select
  1700. * @param filtertype Pour filtre
  1701. * @param addempty Ajoute entree vide
  1702. */
  1703. function select_conditions_paiements($selected='',$htmlname='condid',$filtertype=-1,$addempty=0)
  1704. {
  1705. global $langs,$user;
  1706. $this->load_cache_conditions_paiements();
  1707. print '<select class="flat" name="'.$htmlname.'">';
  1708. if ($addempty) print '<option value="0">&nbsp;</option>';
  1709. foreach($this->cache_conditions_paiements as $id => $arrayconditions)
  1710. {
  1711. if ($selected == $id)
  1712. {
  1713. print '<option value="'.$id.'" selected="selected">';
  1714. }
  1715. else
  1716. {
  1717. print '<option value="'.$id.'">';
  1718. }
  1719. print $arrayconditions['label'];
  1720. print '</option>';
  1721. }
  1722. print '</select>';
  1723. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"),1);
  1724. }
  1725. /**
  1726. * Return list of payment methods
  1727. *
  1728. * @param selected Id du mode de paiement pre-selectionne
  1729. * @param htmlname Nom de la zone select
  1730. * @param filtertype To filter on field type in llx_c_paiement (array('code'=>xx,'label'=>zz))
  1731. * @param format 0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code
  1732. * @param empty 1=peut etre vide, 0 sinon
  1733. * @param noadmininfo 0=Add admin info, 1=Disable admin info
  1734. * @param maxlength Max length of label
  1735. */
  1736. function select_types_paiements($selected='',$htmlname='paiementtype',$filtertype='',$format=0, $empty=0, $noadmininfo=0,$maxlength=0)
  1737. {
  1738. global $langs,$user;
  1739. dol_syslog("Form::select_type_paiements $selected, $htmlname, $filtertype, $format",LOG_DEBUG);
  1740. $filterarray=array();
  1741. if ($filtertype == 'CRDT') $filterarray=array(0,2);
  1742. elseif ($filtertype == 'DBIT') $filterarray=array(1,2);
  1743. elseif ($filtertype != '' && $filtertype != '-1') $filterarray=explode(',',$filtertype);
  1744. $this->load_cache_types_paiements();
  1745. print '<select id="select'.$htmlname.'" class="flat selectpaymenttypes" name="'.$htmlname.'">';
  1746. if ($empty) print '<option value="">&nbsp;</option>';
  1747. foreach($this->cache_types_paiements as $id => $arraytypes)
  1748. {
  1749. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  1750. if (count($filterarray) && ! in_array($arraytypes['type'],$filterarray)) continue;
  1751. // We discard empty line if showempty is on because an empty line has already been output.
  1752. if ($empty && empty($arraytypes['code'])) continue;
  1753. if ($format == 0) print '<option value="'.$id.'"';
  1754. if ($format == 1) print '<option value="'.$arraytypes['code'].'"';
  1755. if ($format == 2) print '<option value="'.$arraytypes['code'].'"';
  1756. if ($format == 3) print '<option value="'.$id.'"';
  1757. // Si selected est text, on compare avec code, sinon avec id
  1758. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) print ' selected="selected"';
  1759. elseif ($selected == $id) print ' selected="selected"';
  1760. print '>';
  1761. if ($format == 0) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
  1762. if ($format == 1) $value=$arraytypes['code'];
  1763. if ($format == 2) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
  1764. if ($format == 3) $value=$arraytypes['code'];
  1765. print $value?$value:'&nbsp;';
  1766. print '</option>';
  1767. }
  1768. print '</select>';
  1769. if ($user->admin && ! $noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"),1);
  1770. }
  1771. /**
  1772. * Selection HT or TTC
  1773. *
  1774. * @param selected Id pre-selectionne
  1775. * @param htmlname Nom de la zone select
  1776. */
  1777. function select_PriceBaseType($selected='',$htmlname='price_base_type')
  1778. {
  1779. print $this->load_PriceBaseType($selected,$htmlname);
  1780. }
  1781. /**
  1782. * Selection HT or TTC
  1783. *
  1784. * @param selected Id pre-selectionne
  1785. * @param htmlname Nom de la zone select
  1786. */
  1787. function load_PriceBaseType($selected='',$htmlname='price_base_type')
  1788. {
  1789. global $langs;
  1790. $return='';
  1791. $return.= '<select class="flat" name="'.$htmlname.'">';
  1792. $options = array(
  1793. 'HT'=>$langs->trans("HT"),
  1794. 'TTC'=>$langs->trans("TTC")
  1795. );
  1796. foreach($options as $id => $value)
  1797. {
  1798. if ($selected == $id)
  1799. {
  1800. $return.= '<option value="'.$id.'" selected="selected">'.$value;
  1801. }
  1802. else
  1803. {
  1804. $return.= '<option value="'.$id.'">'.$value;
  1805. }
  1806. $return.= '</option>';
  1807. }
  1808. $return.= '</select>';
  1809. return $return;
  1810. }
  1811. /**
  1812. * Return combo list of differents status of a proposal
  1813. * Values are id of table c_propalst
  1814. *
  1815. * @param selected etat pre-selectionne
  1816. * @param short Use short labels
  1817. */
  1818. function select_propal_statut($selected='',$short=0)
  1819. {
  1820. global $langs;
  1821. $sql = "SELECT id, code, label, active FROM ".MAIN_DB_PREFIX."c_propalst";
  1822. $sql .= " WHERE active = 1";
  1823. dol_syslog("Form::select_propal_statut sql=".$sql);
  1824. $resql=$this->db->query($sql);
  1825. if ($resql)
  1826. {
  1827. print '<select class="flat" name="propal_statut">';
  1828. print '<option value="">&nbsp;</option>';
  1829. $num = $this->db->num_rows($resql);
  1830. $i = 0;
  1831. if ($num)
  1832. {
  1833. while ($i < $num)
  1834. {
  1835. $obj = $this->db->fetch_object($resql);
  1836. if ($selected == $obj->id)
  1837. {
  1838. print '<option value="'.$obj->id.'" selected="selected">';
  1839. }
  1840. else
  1841. {
  1842. print '<option value="'.$obj->id.'">';
  1843. }
  1844. $key=$obj->code;
  1845. if ($langs->trans("PropalStatus".$key.($short?'Short':'')) != "PropalStatus".$key.($short?'Short':''))
  1846. {
  1847. print $langs->trans("PropalStatus".$key.($short?'Short':''));
  1848. }
  1849. else
  1850. {
  1851. $conv_to_new_code=array('PR_DRAFT'=>'Draft','PR_OPEN'=>'Opened','PR_CLOSED'=>'Closed','PR_SIGNED'=>'Signed','PR_NOTSIGNED'=>'NotSigned','PR_FAC'=>'Billed');
  1852. if (! empty($conv_to_new_code[$obj->code])) $key=$conv_to_new_code[$obj->code];
  1853. print ($langs->trans("PropalStatus".$key.($short?'Short':''))!="PropalStatus".$key.($short?'Short':''))?$langs->trans("PropalStatus".$key.($short?'Short':'')):$obj->label;
  1854. }
  1855. print '</option>';
  1856. $i++;
  1857. }
  1858. }
  1859. print '</select>';
  1860. }
  1861. else
  1862. {
  1863. dol_print_error($this->db);
  1864. }
  1865. }
  1866. /**
  1867. * Return a HTML select list of bank accounts
  1868. *
  1869. * @param selected Id account pre-selected
  1870. * @param htmlname Name of select zone
  1871. * @param statut Status of searched accounts (0=open, 1=closed)
  1872. * @param filtre To filter list
  1873. * @param useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
  1874. * @param moreattrib To add more attribute on select
  1875. */
  1876. function select_comptes($selected='',$htmlname='accountid',$statut=0,$filtre='',$useempty=0,$moreattrib='')
  1877. {
  1878. global $langs, $conf;
  1879. $langs->load("admin");
  1880. $sql = "SELECT rowid, label, bank";
  1881. $sql.= " FROM ".MAIN_DB_PREFIX."bank_account";
  1882. $sql.= " WHERE clos = '".$statut."'";
  1883. $sql.= " AND entity = ".$conf->entity;
  1884. if ($filtre) $sql.=" AND ".$filtre;
  1885. $sql.= " ORDER BY label";
  1886. dol_syslog("Form::select_comptes sql=".$sql);
  1887. $result = $this->db->query($sql);
  1888. if ($result)
  1889. {
  1890. $num = $this->db->num_rows($result);
  1891. $i = 0;
  1892. if ($num)
  1893. {
  1894. print '<select id="select'.$htmlname.'" class="flat selectbankaccount" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
  1895. if ($useempty == 1 || ($useempty == 2 && $num > 1))
  1896. {
  1897. print '<option value="'.$obj->rowid.'">&nbsp;</option>';
  1898. }
  1899. while ($i < $num)
  1900. {
  1901. $obj = $this->db->fetch_object($result);
  1902. if ($selected == $obj->rowid)
  1903. {
  1904. print '<option value="'.$obj->rowid.'" selected="selected">';
  1905. }
  1906. else
  1907. {
  1908. print '<option value="'.$obj->rowid.'">';
  1909. }
  1910. print $obj->label;
  1911. print '</option>';
  1912. $i++;
  1913. }
  1914. print "</select>";
  1915. }
  1916. else
  1917. {
  1918. print $langs->trans("NoActiveBankAccountDefined");
  1919. }
  1920. }
  1921. else {
  1922. dol_print_error($this->db);
  1923. }
  1924. }
  1925. /**
  1926. * Return list of categories having choosed type
  1927. *
  1928. * @param type Type de categories (0=product, 1=supplier, 2=customer, 3=member)
  1929. * @param selected Id of category preselected
  1930. * @param select_name HTML field name
  1931. * @param maxlength Maximum length for labels
  1932. * @param excludeafterid Exclude all categories after this leaf in category tree.
  1933. */
  1934. function select_all_categories($type, $selected='', $select_name="", $maxlength=64, $excludeafterid=0)
  1935. {
  1936. global $langs;
  1937. $langs->load("categories");
  1938. if ($select_name=="") $select_name="catMere";
  1939. $cat = new Categorie($this->db);
  1940. $cate_arbo = $cat->get_full_arbo($type,$excludeafterid);
  1941. $output = '<select class="flat" name="'.$select_name.'">';
  1942. if (is_array($cate_arbo))
  1943. {
  1944. if (! count($cate_arbo)) $output.= '<option value="-1" disabled="disabled">'.$langs->trans("NoCategoriesDefined").'</option>';
  1945. else
  1946. {
  1947. $output.= '<option value="-1">&nbsp;</option>';
  1948. foreach($cate_arbo as $key => $value)
  1949. {
  1950. if ($cate_arbo[$key]['id'] == $selected)
  1951. {
  1952. $add = 'selected="selected" ';
  1953. }
  1954. else
  1955. {
  1956. $add = '';
  1957. }
  1958. $output.= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'],$maxlength,'middle').'</option>';
  1959. }
  1960. }
  1961. }
  1962. $output.= '</select>';
  1963. $output.= "\n";
  1964. return $output;
  1965. }
  1966. /**
  1967. * Show a confirmation HTML form or AJAX popup
  1968. *
  1969. * @param page Url of page to call if confirmation is OK
  1970. * @param title title
  1971. * @param question question
  1972. * @param action action
  1973. * @param formquestion an array with forms complementary inputs
  1974. * @param selectedchoice "" or "no" or "yes"
  1975. * @param useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No
  1976. * @param height Force height of box
  1977. * @return string 'ajax' if a confirm ajax popup is shown, 'html' if it's an html form
  1978. */
  1979. function form_confirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=170, $width=500)
  1980. {
  1981. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  1982. }
  1983. /**
  1984. * Show a confirmation HTML form or AJAX popup
  1985. *
  1986. * @param string $page Url of page to call if confirmation is OK
  1987. * @param string $title Title
  1988. * @param string $question Question
  1989. * @param string $action Action
  1990. * @param array $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , ))
  1991. * @param string $selectedchoice "" or "no" or "yes"
  1992. * @param int $useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No
  1993. * @param int $height Force height of box
  1994. * @return string 'ajax' if a confirm ajax popup is shown, 'html' if it's an html form
  1995. */
  1996. function formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=170, $width=500)
  1997. {
  1998. global $langs,$conf;
  1999. $more='';
  2000. $formconfirm='';
  2001. $inputarray=array();
  2002. if (is_array($formquestion) && count($formquestion) > 0)
  2003. {
  2004. $more.='<table class="paddingrightonly" width="100%">'."\n";
  2005. $more.='<tr><td colspan="3" valign="top">'.$formquestion['text'].'</td></tr>'."\n";
  2006. foreach ($formquestion as $key => $input)
  2007. {
  2008. if (is_array($input))
  2009. {
  2010. if ($input['type'] == 'text')
  2011. {
  2012. $more.='<tr><td valign="top">'.$input['label'].'</td><td valign="top" colspan="2" align="left"><input type="text" class="flat" id="'.$input['name'].'" name="'.$input['name'].'" size="'.$input['size'].'" value="'.$input['value'].'" /></td></tr>'."\n";
  2013. }
  2014. else if ($input['type'] == 'password')
  2015. {
  2016. $more.='<tr><td valign="top">'.$input['label'].'</td><td valign="top" colspan="2" align="left"><input type="password" class="flat" id="'.$input['name'].'" name="'.$input['name'].'" size="'.$input['size'].'" value="'.$input['value'].'" /></td></tr>'."\n";
  2017. }
  2018. else if ($input['type'] == 'select')
  2019. {
  2020. $more.='<tr><td valign="top" style="padding: 4px !important;">';
  2021. if (! empty($input['label'])) $more.=$input['label'].'</td><td valign="top" colspan="2" align="left" style="padding: 4px !important;">';
  2022. $more.=$this->selectarray($input['name'],$input['values'],$input['default'],1);
  2023. $more.='</td></tr>'."\n";
  2024. }
  2025. else if ($input['type'] == 'checkbox')
  2026. {
  2027. $more.='<tr>';
  2028. $more.='<td valign="top">'.$input['label'].' </td><td valign="top" align="left">';
  2029. $more.='<input type="checkbox" class="flat" id="'.$input['name'].'" name="'.$input['name'].'"';
  2030. if (! is_bool($input['value']) && $input['value'] != 'false') $more.=' checked="checked"';
  2031. if (is_bool($input['value']) && $input['value']) $more.=' checked="checked"';
  2032. if ($input['disabled']) $more.=' disabled="disabled"';
  2033. $more.=' /></td>';
  2034. $more.='<td valign="top" align="left">&nbsp;</td>';
  2035. $more.='</tr>'."\n";
  2036. }
  2037. else if ($input['type'] == 'radio')
  2038. {
  2039. $i=0;
  2040. foreach($input['values'] as $selkey => $selval)
  2041. {
  2042. $more.='<tr>';
  2043. if ($i==0) $more.='<td valign="top">'.$input['label'].'</td>';
  2044. else $more.='<td>&nbsp;</td>';
  2045. $more.='<td valign="top" width="20"><input type="radio" class="flat" id="'.$input['name'].'" name="'.$input['name'].'" value="'.$selkey.'"';
  2046. if ($input['disabled']) $more.=' disabled="disabled"';
  2047. $more.=' /></td>';
  2048. $more.='<td valign="top" align="left">';
  2049. $more.=$selval;
  2050. $more.='</td></tr>'."\n";
  2051. $i++;
  2052. }
  2053. }
  2054. else if ($input['type'] == 'other')
  2055. {
  2056. $more.='<tr><td valign="top">';
  2057. if (! empty($input['label'])) $more.=$input['label'].'</td><td valign="top" colspan="2" align="left">';
  2058. $more.=$input['value'];
  2059. $more.='</td></tr>'."\n";
  2060. }
  2061. array_push($inputarray,$input['name']);
  2062. }
  2063. }
  2064. $more.='</table>'."\n";
  2065. }
  2066. $formconfirm.= "\n<!-- begin form_confirm -->\n";
  2067. if ($useajax && $conf->use_javascript_ajax)
  2068. {
  2069. $autoOpen=true;
  2070. $dialogconfirm='dialog-confirm';
  2071. if (! is_int($useajax)) {
  2072. $button=$useajax;
  2073. $useajax=1;
  2074. $autoOpen=false;
  2075. $dialogconfirm.='-'.$button;
  2076. }
  2077. $pageyes=$page.'&action='.$action.'&confirm=yes';
  2078. $pageno=($useajax == 2?$page.'&confirm=no':'');
  2079. // New code using jQuery only
  2080. $formconfirm.= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
  2081. if (! empty($more)) $formconfirm.= '<p>'.$more.'</p>';
  2082. $formconfirm.= img_help('','').' '.$question;
  2083. $formconfirm.= '</div>'."\n";
  2084. $formconfirm.= '<script type="text/javascript">
  2085. $(function() {
  2086. var choice=\'ko\';
  2087. var $inputarray='.json_encode($inputarray).';
  2088. var button=\''.$button.'\';
  2089. var dialogconfirm=\''.$dialogconfirm.'\';
  2090. $( "#" + dialogconfirm ).dialog({
  2091. autoOpen: '.($autoOpen?'true':'false').',
  2092. resizable: false,
  2093. height:'.$height.',
  2094. width:'.$width.',
  2095. modal: true,
  2096. closeOnEscape: false,
  2097. close: function(event, ui) {
  2098. if (choice == \'ok\') {
  2099. var options="";
  2100. if ($inputarray.length>0) {
  2101. $.each($inputarray, function() {
  2102. var inputname = this;
  2103. var inputvalue = $("#" + this).val();
  2104. options += \'&\' + inputname + \'=\' + inputvalue;
  2105. });
  2106. //alert(options);
  2107. }
  2108. location.href=\''.$pageyes.'\' + options;
  2109. }
  2110. '.($pageno?'if (choice == \'ko\') location.href=\''.$pageno.'\';':'').'
  2111. },
  2112. buttons: {
  2113. \''.dol_escape_js($langs->transnoentities("Yes")).'\': function() {
  2114. choice=\'ok\';
  2115. $(this).dialog(\'close\');
  2116. },
  2117. \''.dol_escape_js($langs->transnoentities("No")).'\': function() {
  2118. choice=\'ko\';
  2119. $(this).dialog(\'close\');
  2120. }
  2121. }
  2122. });
  2123. if (button.length > 0) {
  2124. $( "#" + button ).click(function() {
  2125. $("#" + dialogconfirm ).dialog(\'open\');
  2126. });
  2127. }
  2128. });
  2129. </script>';
  2130. $formconfirm.= "\n";
  2131. }
  2132. else
  2133. {
  2134. $formconfirm.= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
  2135. $formconfirm.= '<input type="hidden" name="action" value="'.$action.'">';
  2136. $formconfirm.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'."\n";
  2137. $formconfirm.= '<table width="100%" class="valid">'."\n";
  2138. // Ligne titre
  2139. $formconfirm.= '<tr class="validtitre"><td class="validtitre" colspan="3">'.img_picto('','recent').' '.$title.'</td></tr>'."\n";
  2140. // Ligne formulaire
  2141. if ($more)
  2142. {
  2143. $formconfirm.='<tr class="valid"><td class="valid" colspan="3">'."\n";
  2144. $formconfirm.=$more;
  2145. $formconfirm.='</td></tr>'."\n";
  2146. }
  2147. // Ligne message
  2148. $formconfirm.= '<tr class="valid">';
  2149. $formconfirm.= '<td class="valid">'.$question.'</td>';
  2150. $formconfirm.= '<td class="valid">';
  2151. $newselectedchoice=empty($selectedchoice)?"no":$selectedchoice;
  2152. $formconfirm.= $this->selectyesno("confirm",$newselectedchoice);
  2153. $formconfirm.= '</td>';
  2154. $formconfirm.= '<td class="valid" align="center"><input class="button" type="submit" value="'.$langs->trans("Validate").'"></td>';
  2155. $formconfirm.= '</tr>'."\n";
  2156. $formconfirm.= '</table>'."\n";
  2157. if (is_array($formquestion))
  2158. {
  2159. foreach ($formquestion as $key => $input)
  2160. {
  2161. if ($input['type'] == 'hidden') $formconfirm.= '<input type="hidden" name="'.$input['name'].'" value="'.$input['value'].'">';
  2162. }
  2163. }
  2164. $formconfirm.= "</form>\n";
  2165. $formconfirm.= '<br>';
  2166. }
  2167. $formconfirm.= "<!-- end form_confirm -->\n";
  2168. return $formconfirm;
  2169. }
  2170. /**
  2171. * Show a form to select a project
  2172. *
  2173. * @param int $page Page
  2174. * @param int $socid Id third party
  2175. * @param int $selected Id pre-selected project
  2176. * @param string $htmlname Name of select field
  2177. * @return void
  2178. */
  2179. function form_project($page, $socid, $selected='', $htmlname='projectid')
  2180. {
  2181. global $langs;
  2182. require_once(DOL_DOCUMENT_ROOT."/core/lib/project.lib.php");
  2183. $langs->load("project");
  2184. if ($htmlname != "none")
  2185. {
  2186. print '<form method="post" action="'.$page.'">';
  2187. print '<input type="hidden" name="action" value="classin">';
  2188. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  2189. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  2190. print '<tr><td>';
  2191. //print "$socid,$selected,$htmlname";
  2192. select_projects($socid,$selected,$htmlname);
  2193. print '</td>';
  2194. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  2195. print '</tr></table></form>';
  2196. }
  2197. else
  2198. {
  2199. if ($selected)
  2200. {
  2201. $projet = new Project($this->db);
  2202. $projet->fetch($selected);
  2203. //print '<a href="'.DOL_URL_ROOT.'/projet/fiche.php?id='.$selected.'">'.$projet->title.'</a>';
  2204. print $projet->getNomUrl(0,'',1);
  2205. }
  2206. else
  2207. {
  2208. print "&nbsp;";
  2209. }
  2210. }
  2211. }
  2212. /**
  2213. * Show a form to select payment conditions
  2214. *
  2215. * @param page Page
  2216. * @param selected Id condition pre-selectionne
  2217. * @param htmlname Name of select html field
  2218. * @param addempty Ajoute entree vide
  2219. * @return void
  2220. */
  2221. function form_conditions_reglement($page, $selected='', $htmlname='cond_reglement_id', $addempty=0)
  2222. {
  2223. global $langs;
  2224. if ($htmlname != "none")
  2225. {
  2226. print '<form method="post" action="'.$page.'">';
  2227. print '<input type="hidden" name="action" value="setconditions">';
  2228. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  2229. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  2230. print '<tr><td>';
  2231. $this->select_conditions_paiements($selected,$htmlname,-1,$addempty);
  2232. print '</td>';
  2233. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  2234. print '</tr></table></form>';
  2235. }
  2236. else
  2237. {
  2238. if ($selected)
  2239. {
  2240. $this->load_cache_conditions_paiements();
  2241. print $this->cache_conditions_paiements[$selected]['label'];
  2242. } else {
  2243. print "&nbsp;";
  2244. }
  2245. }
  2246. }
  2247. /**
  2248. * Show a form to select a delivery delay
  2249. *
  2250. * @param page Page
  2251. * @param selected Id condition pre-selectionne
  2252. * @param htmlname Name of select html field
  2253. * @param addempty Ajoute entree vide
  2254. * @return void
  2255. */
  2256. function form_availability($page, $selected='', $htmlname='availability', $addempty=0)
  2257. {
  2258. global $langs;
  2259. if ($htmlname != "none")
  2260. {
  2261. print '<form method="post" action="'.$page.'">';
  2262. print '<input type="hidden" name="action" value="setavailability">';
  2263. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  2264. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  2265. print '<tr><td>';
  2266. $this->select_availability($selected,$htmlname,-1,$addempty);
  2267. print '</td>';
  2268. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  2269. print '</tr></table></form>';
  2270. }
  2271. else
  2272. {
  2273. if ($selected)
  2274. {
  2275. $this->load_cache_availability();
  2276. print $this->cache_availability[$selected]['label'];
  2277. } else {
  2278. print "&nbsp;";
  2279. }
  2280. }
  2281. }
  2282. /**
  2283. * Show a select form to select origin
  2284. *
  2285. * @param page Page
  2286. * @param selected Id condition pre-selectionne
  2287. * @param htmlname Name of select html field
  2288. * @param addempty Add empty entry
  2289. * @return void
  2290. */
  2291. function form_demand_reason($page, $selected='', $htmlname='demandreason', $addempty=0)
  2292. {
  2293. global $langs;
  2294. if ($htmlname != "none")
  2295. {
  2296. print '<form method="post" action="'.$page.'">';
  2297. print '<input type="hidden" name="action" value="setdemandreason">';
  2298. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  2299. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  2300. print '<tr><td>';
  2301. $this->select_demand_reason($selected,$htmlname,-1,$addempty);
  2302. print '</td>';
  2303. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  2304. print '</tr></table></form>';
  2305. }
  2306. else
  2307. {
  2308. if ($selected)
  2309. {
  2310. $this->load_cache_demand_reason();
  2311. foreach ($this->cache_demand_reason as $key => $val)
  2312. {
  2313. if ($val['id'] == $selected)
  2314. {
  2315. print $val['label'];
  2316. break;
  2317. }
  2318. }
  2319. } else {
  2320. print "&nbsp;";
  2321. }
  2322. }
  2323. }
  2324. /**
  2325. * Show a form to select a date
  2326. *
  2327. * @param page Page
  2328. * @param selected Date preselected
  2329. * @param htmlname Name of input html field
  2330. * @return void
  2331. */
  2332. function form_date($page, $selected='', $htmlname)
  2333. {
  2334. global $langs;
  2335. if ($htmlname != "none")
  2336. {
  2337. print '<form method="post" action="'.$page.'" name="form'.$htmlname.'">';
  2338. print '<input type="hidden" name="action" value="set'.$htmlname.'">';
  2339. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  2340. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  2341. print '<tr><td>';
  2342. print $this->select_date($selected,$htmlname,0,0,1,'form'.$htmlname);
  2343. print '</td>';
  2344. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  2345. print '</tr></table></form>';
  2346. }
  2347. else
  2348. {
  2349. if ($selected)
  2350. {
  2351. $this->load_cache_types_paiements();
  2352. print $this->cache_types_paiements[$selected]['label'];
  2353. } else {
  2354. print "&nbsp;";
  2355. }
  2356. }
  2357. }
  2358. /**
  2359. * Show a select form to choose a user
  2360. *
  2361. * @param page Page
  2362. * @param selected Id of user preselected
  2363. * @param htmlname Name of input html field
  2364. * @param exclude List of users id to exclude
  2365. * @param include List of users id to include
  2366. * @return void
  2367. */
  2368. function form_users($page, $selected='', $htmlname='userid', $exclude='', $include='')
  2369. {
  2370. global $langs;
  2371. if ($htmlname != "none")
  2372. {
  2373. print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  2374. print '<input type="hidden" name="action" value="set'.$htmlname.'">';
  2375. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  2376. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  2377. print '<tr><td>';
  2378. print $this->select_users($selected,$htmlname,1,$exclude,0,$include);
  2379. print '</td>';
  2380. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  2381. print '</tr></table></form>';
  2382. }
  2383. else
  2384. {
  2385. if ($selected)
  2386. {
  2387. require_once(DOL_DOCUMENT_ROOT ."/user/class/user.class.php");
  2388. //$this->load_cache_contacts();
  2389. //print $this->cache_contacts[$selected];
  2390. $theuser=new User($this->db);
  2391. $theuser->fetch($selected);
  2392. print $theuser->getNomUrl(1);
  2393. } else {
  2394. print "&nbsp;";
  2395. }
  2396. }
  2397. }
  2398. /**
  2399. * Affiche formulaire de selection des modes de reglement
  2400. *
  2401. * @param page Page
  2402. * @param selected Id mode pre-selectionne
  2403. * @param htmlname Name of select html field
  2404. * @return void
  2405. */
  2406. function form_modes_reglement($page, $selected='', $htmlname='mode_reglement_id')
  2407. {
  2408. global $langs;
  2409. if ($htmlname != "none")
  2410. {
  2411. print '<form method="POST" action="'.$page.'">';
  2412. print '<input type="hidden" name="action" value="setmode">';
  2413. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  2414. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  2415. print '<tr><td>';
  2416. $this->select_types_paiements($selected,$htmlname);
  2417. print '</td>';
  2418. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  2419. print '</tr></table></form>';
  2420. }
  2421. else
  2422. {
  2423. if ($selected)
  2424. {
  2425. $this->load_cache_types_paiements();
  2426. print $this->cache_types_paiements[$selected]['label'];
  2427. } else {
  2428. print "&nbsp;";
  2429. }
  2430. }
  2431. }
  2432. /**
  2433. * Show a select box with available absolute discounts
  2434. *
  2435. * @param string $page Page URL where form is shown
  2436. * @param int $selected Value pre-selected
  2437. * @param string $htmlname Nom du formulaire select. Si none, non modifiable
  2438. * @param int $socid Third party id
  2439. * @param float $amount Total amount available
  2440. * @param string $filter SQL filter on discounts
  2441. * @param int $maxvalue Max value for lines that can be selected
  2442. * @param string $more More string to add
  2443. * @return void
  2444. */
  2445. function form_remise_dispo($page, $selected='', $htmlname='remise_id',$socid, $amount, $filter='', $maxvalue=0, $more='')
  2446. {
  2447. global $conf,$langs;
  2448. if ($htmlname != "none")
  2449. {
  2450. print '<form method="post" action="'.$page.'">';
  2451. print '<input type="hidden" name="action" value="setabsolutediscount">';
  2452. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  2453. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  2454. print '<tr><td nowrap="nowrap">';
  2455. //if (! $filter || $filter=="fk_facture_source IS NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount),$langs->transnoentities("Currency".$conf->monnaie)).': '; // If we want deposit to be substracted to payments only and not to total of final invoice
  2456. if (! $filter || $filter=="fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description='(DEPOSIT)')") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount),$langs->transnoentities("Currency".$conf->monnaie)).': ';
  2457. else print $langs->trans("CompanyHasCreditNote",price($amount),$langs->transnoentities("Currency".$conf->monnaie)).': ';
  2458. $newfilter='fk_facture IS NULL AND fk_facture_line IS NULL'; // Remises disponibles
  2459. if ($filter) $newfilter.=' AND ('.$filter.')';
  2460. $nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue);
  2461. print '</td>';
  2462. print '<td>';
  2463. if ($nbqualifiedlines > 0)
  2464. {
  2465. print ' &nbsp; <input type="submit" class="button" value="'.$langs->trans("UseLine").'"';
  2466. if ($filter && $filter != "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description='(DEPOSIT)')") print '" title="'.$langs->trans("UseCreditNoteInInvoicePayment");
  2467. print '">';
  2468. }
  2469. if ($more) print $more;
  2470. print '</td>';
  2471. print '</tr></table></form>';
  2472. }
  2473. else
  2474. {
  2475. if ($selected)
  2476. {
  2477. print $selected;
  2478. }
  2479. else
  2480. {
  2481. print "0";
  2482. }
  2483. }
  2484. }
  2485. /**
  2486. * Affiche formulaire de selection des contacts
  2487. *
  2488. * @param page Page
  2489. * @param selected Id contact pre-selectionne
  2490. * @param htmlname Nom du formulaire select
  2491. * @return void
  2492. */
  2493. function form_contacts($page, $societe, $selected='', $htmlname='contactidp')
  2494. {
  2495. global $langs;
  2496. if ($htmlname != "none")
  2497. {
  2498. print '<form method="post" action="'.$page.'">';
  2499. print '<input type="hidden" name="action" value="set_contact">';
  2500. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  2501. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  2502. print '<tr><td>';
  2503. $num=$this->select_contacts($societe->id, $selected, $htmlname);
  2504. if ($num==0)
  2505. {
  2506. print '<font class="error">Cette societe n\'a pas de contact, veuillez en cr�er un avant de faire votre proposition commerciale</font><br>';
  2507. print '<a href="'.DOL_URL_ROOT.'/contact/fiche.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$langs->trans('AddContact').'</a>';
  2508. }
  2509. print '</td>';
  2510. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  2511. print '</tr></table></form>';
  2512. }
  2513. else
  2514. {
  2515. if ($selected)
  2516. {
  2517. require_once(DOL_DOCUMENT_ROOT ."/contact/class/contact.class.php");
  2518. //$this->load_cache_contacts();
  2519. //print $this->cache_contacts[$selected];
  2520. $contact=new Contact($this->db);
  2521. $contact->fetch($selected);
  2522. print $contact->getFullName($langs);
  2523. } else {
  2524. print "&nbsp;";
  2525. }
  2526. }
  2527. }
  2528. /**
  2529. * Affiche formulaire de selection des tiers
  2530. *
  2531. * @param page Page
  2532. * @param selected Id contact pre-selectionne
  2533. * @param htmlname Nom du formulaire select
  2534. * @return void
  2535. */
  2536. function form_thirdparty($page, $selected='', $htmlname='socid')
  2537. {
  2538. global $langs;
  2539. if ($htmlname != "none")
  2540. {
  2541. print '<form method="post" action="'.$page.'">';
  2542. print '<input type="hidden" name="action" value="set_thirdparty">';
  2543. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  2544. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  2545. print '<tr><td>';
  2546. $num=$this->select_societes($selected , $htmlname);
  2547. print '</td>';
  2548. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  2549. print '</tr></table></form>';
  2550. }
  2551. else
  2552. {
  2553. if ($selected)
  2554. {
  2555. require_once(DOL_DOCUMENT_ROOT ."/societe/class/societe.class.php");
  2556. $soc = new Societe($this->db);
  2557. $soc->fetch($selected);
  2558. print $soc->getNomUrl($langs);
  2559. } else {
  2560. print "&nbsp;";
  2561. }
  2562. }
  2563. }
  2564. /**
  2565. * Affiche formulaire de selection de l'adresse
  2566. *
  2567. * @param page Page
  2568. * @param selected Id condition pre-selectionne
  2569. * @param htmlname Nom du formulaire select
  2570. * @param origin Origine de l'appel pour pouvoir creer un retour
  2571. * @param originid Id de l'origine
  2572. * @return void
  2573. */
  2574. function form_address($page, $selected='', $socid, $htmlname='address_id', $origin='', $originid='')
  2575. {
  2576. global $langs,$conf;
  2577. if ($htmlname != "none")
  2578. {
  2579. print '<form method="post" action="'.$page.'">';
  2580. print '<input type="hidden" name="action" value="setaddress">';
  2581. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  2582. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  2583. print '<tr><td>';
  2584. $this->select_address($selected, $socid, $htmlname, 1);
  2585. print '</td>';
  2586. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'">';
  2587. $langs->load("companies");
  2588. print ' &nbsp; <a href='.DOL_URL_ROOT.'/comm/address.php?socid='.$socid.'&action=create&origin='.$origin.'&originid='.$originid.'>'.$langs->trans("AddAddress").'</a>';
  2589. print '</td></tr></table></form>';
  2590. }
  2591. else
  2592. {
  2593. if ($selected)
  2594. {
  2595. require_once(DOL_DOCUMENT_ROOT ."/societe/class/address.class.php");
  2596. $address=new Address($this->db);
  2597. $result=$address->fetch_address($selected);
  2598. print '<a href='.DOL_URL_ROOT.'/comm/address.php?socid='.$address->socid.'&id='.$address->id.'&action=edit&origin='.$origin.'&originid='.$originid.'>'.$address->label.'</a>';
  2599. }
  2600. else
  2601. {
  2602. print "&nbsp;";
  2603. }
  2604. }
  2605. }
  2606. /**
  2607. * Retourne la liste des devises, dans la langue de l'utilisateur
  2608. *
  2609. * @param selected code devise pre-selectionne
  2610. * @param htmlname nom de la liste deroulante
  2611. * @return void
  2612. */
  2613. function select_currency($selected='',$htmlname='currency_id')
  2614. {
  2615. print $this->selectcurrency($selected,$htmlname);
  2616. }
  2617. /**
  2618. * Retourne la liste des devises, dans la langue de l'utilisateur
  2619. *
  2620. * @param selected code devise pre-selectionne
  2621. * @param htmlname nom de la liste deroulante
  2622. */
  2623. function selectcurrency($selected='',$htmlname='currency_id')
  2624. {
  2625. global $conf,$langs,$user;
  2626. $langs->load("dict");
  2627. $out='';
  2628. $currencyArray=array();
  2629. $label=array();
  2630. if ($selected=='euro' || $selected=='euros') $selected='EUR'; // Pour compatibilite
  2631. $sql = "SELECT code_iso, label";
  2632. $sql.= " FROM ".MAIN_DB_PREFIX."c_currencies";
  2633. $sql.= " WHERE active = 1";
  2634. $sql.= " ORDER BY code_iso ASC";
  2635. $resql=$this->db->query($sql);
  2636. if ($resql)
  2637. {
  2638. $out.= '<select class="flat" name="'.$htmlname.'">';
  2639. $num = $this->db->num_rows($resql);
  2640. $i = 0;
  2641. if ($num)
  2642. {
  2643. $foundselected=false;
  2644. while ($i < $num) {
  2645. $obj = $this->db->fetch_object($resql);
  2646. $currencyArray[$i]['code_iso'] = $obj->code_iso;
  2647. $currencyArray[$i]['label'] = ($obj->code_iso && $langs->trans("Currency".$obj->code_iso)!="Currency".$obj->code_iso?$langs->trans("Currency".$obj->code_iso):($obj->label!='-'?$obj->label:''));
  2648. $label[$i] = $currencyArray[$i]['label'];
  2649. $i++;
  2650. }
  2651. array_multisort($label, SORT_ASC, $currencyArray);
  2652. foreach ($currencyArray as $row) {
  2653. if ($selected && $selected == $row['code_iso']) {
  2654. $foundselected=true;
  2655. $out.= '<option value="'.$row['code_iso'].'" selected="selected">';
  2656. } else {
  2657. $out.= '<option value="'.$row['code_iso'].'">';
  2658. }
  2659. $out.= $row['label'];
  2660. if ($row['code_iso']) $out.= ' ('.$row['code_iso'] . ')';
  2661. $out.= '</option>';
  2662. }
  2663. }
  2664. $out.= '</select>';
  2665. if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionnarySetup"),1);
  2666. return $out;
  2667. }
  2668. else
  2669. {
  2670. dol_print_error($this->db);
  2671. }
  2672. }
  2673. /**
  2674. * Output an HTML select vat rate
  2675. *
  2676. * @param htmlname Nom champ html
  2677. * @param selectedrate Forcage du taux tva pre-selectionne. Mettre '' pour aucun forcage.
  2678. * @param societe_vendeuse Objet societe vendeuse
  2679. * @param societe_acheteuse Objet societe acheteuse
  2680. * @param idprod Id product
  2681. * @param info_bits Miscellaneous information on line
  2682. * @param type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  2683. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  2684. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  2685. * Si (vendeur et acheteur dans Communaute europeenne) et bien vendu = moyen de transports neuf (auto, bateau, avion), TVA par defaut=0 (La TVA doit etre paye par l'acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
  2686. * Si (vendeur et acheteur dans Communaute europeenne) et bien vendu autre que transport neuf alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  2687. * Sinon la TVA proposee par defaut=0. Fin de regle.
  2688. * @deprecated
  2689. * @return void
  2690. */
  2691. function select_tva($htmlname='tauxtva', $selectedrate='', $societe_vendeuse='', $societe_acheteuse='', $idprod=0, $info_bits=0, $type='')
  2692. {
  2693. print $this->load_tva($htmlname, $selectedrate, $societe_vendeuse, $societe_acheteuse, $idprod, $info_bits, $type);
  2694. }
  2695. /**
  2696. * Output an HTML select vat rate
  2697. *
  2698. * @param htmlname Nom champ html
  2699. * @param selectedrate Forcage du taux tva pre-selectionne. Mettre '' pour aucun forcage.
  2700. * @param societe_vendeuse Objet societe vendeuse
  2701. * @param societe_acheteuse Objet societe acheteuse
  2702. * @param idprod Id product
  2703. * @param info_bits Miscellaneous information on line (1 for NPR)
  2704. * @param type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  2705. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  2706. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  2707. * Si (vendeur et acheteur dans Communaute europeenne) et bien vendu = moyen de transports neuf (auto, bateau, avion), TVA par defaut=0 (La TVA doit etre paye par l'acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
  2708. * Si (vendeur et acheteur dans Communaute europeenne) et bien vendu autre que transport neuf alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  2709. * Sinon la TVA proposee par defaut=0. Fin de regle.
  2710. * @return void
  2711. */
  2712. function load_tva($htmlname='tauxtva', $selectedrate='', $societe_vendeuse='', $societe_acheteuse='', $idprod=0, $info_bits=0, $type='')
  2713. {
  2714. global $langs,$conf,$mysoc;
  2715. $return='';
  2716. $txtva=array();
  2717. $libtva=array();
  2718. $nprtva=array();
  2719. // Define defaultnpr and defaultttx
  2720. $defaultnpr=($info_bits & 0x01);
  2721. $defaultnpr=(preg_match('/\*/',$selectedrate) ? 1 : $defaultnpr);
  2722. $defaulttx=str_replace('*','',$selectedrate);
  2723. // Check parameters
  2724. if (is_object($societe_vendeuse) && ! $societe_vendeuse->pays_code)
  2725. {
  2726. if ($societe_vendeuse->id == $mysoc->id)
  2727. {
  2728. $return.= '<font class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</div>';
  2729. }
  2730. else
  2731. {
  2732. $return.= '<font class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</div>';
  2733. }
  2734. return $return;
  2735. }
  2736. //var_dump($societe_acheteuse);
  2737. //print "name=$name, selectedrate=$selectedrate, seller=".$societe_vendeuse->pays_code." buyer=".$societe_acheteuse->pays_code." buyer is company=".$societe_acheteuse->isACompany()." idprod=$idprod, info_bits=$info_bits type=$type";
  2738. //exit;
  2739. // Get list of all VAT rates to show
  2740. // First we defined code_pays to use to find list
  2741. if (is_object($societe_vendeuse))
  2742. {
  2743. $code_pays="'".$societe_vendeuse->pays_code."'";
  2744. }
  2745. else
  2746. {
  2747. $code_pays="'".$mysoc->pays_code."'"; // Pour compatibilite ascendente
  2748. }
  2749. if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) // If option to have vat for end customer for services is on
  2750. {
  2751. if (! $societe_vendeuse->isInEEC() && $societe_acheteuse->isInEEC() && ! $societe_acheteuse->isACompany())
  2752. {
  2753. // We also add the buyer
  2754. if (is_numeric($type))
  2755. {
  2756. if ($type == 1) // We know product is a service
  2757. {
  2758. $code_pays.=",'".$societe_acheteuse->pays_code."'";
  2759. }
  2760. }
  2761. else if (! $idprod) // We don't know type of product
  2762. {
  2763. $code_pays.=",'".$societe_acheteuse->pays_code."'";
  2764. }
  2765. else
  2766. {
  2767. $prodstatic=new Product($this->db);
  2768. $prodstatic->fetch($idprod);
  2769. if ($prodstatic->type == 1) // We know product is a service
  2770. {
  2771. $code_pays.=",'".$societe_acheteuse->pays_code."'";
  2772. }
  2773. }
  2774. }
  2775. }
  2776. // Now we get list
  2777. $sql = "SELECT DISTINCT t.taux, t.recuperableonly";
  2778. $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_pays as p";
  2779. $sql.= " WHERE t.fk_pays = p.rowid";
  2780. $sql.= " AND t.active = 1";
  2781. $sql.= " AND p.code in (".$code_pays.")";
  2782. $sql.= " ORDER BY t.taux ASC, t.recuperableonly ASC";
  2783. $resql=$this->db->query($sql);
  2784. if ($resql)
  2785. {
  2786. $num = $this->db->num_rows($resql);
  2787. if ($num)
  2788. {
  2789. for ($i = 0; $i < $num; $i++)
  2790. {
  2791. $obj = $this->db->fetch_object($resql);
  2792. $txtva[$i] = $obj->taux;
  2793. $libtva[$i] = $obj->taux.'%';
  2794. $nprtva[$i] = $obj->recuperableonly;
  2795. }
  2796. }
  2797. else
  2798. {
  2799. $return.= '<font class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry",$code_pays).'</font>';
  2800. }
  2801. }
  2802. else
  2803. {
  2804. $return.= '<font class="error">'.$this->db->error().'</font>';
  2805. }
  2806. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  2807. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
  2808. {
  2809. $defaulttx=get_default_tva($societe_vendeuse,$societe_acheteuse,$idprod);
  2810. $defaultnpr=get_default_npr($societe_vendeuse,$societe_acheteuse,$idprod);
  2811. }
  2812. // Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
  2813. // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
  2814. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
  2815. {
  2816. $defaulttx = $txtva[count($txtva)-1];
  2817. }
  2818. $nbdetaux = count($txtva);
  2819. if ($nbdetaux > 0)
  2820. {
  2821. $return.= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
  2822. for ($i = 0 ; $i < $nbdetaux ; $i++)
  2823. {
  2824. //print "xxxxx".$txtva[$i]."-".$nprtva[$i];
  2825. $return.= '<option value="'.$txtva[$i];
  2826. $return.= $nprtva[$i] ? '*': '';
  2827. $return.= '"';
  2828. if ($txtva[$i] == $defaulttx && $nprtva[$i] == $defaultnpr)
  2829. {
  2830. $return.= ' selected="selected"';
  2831. }
  2832. $return.= '>'.vatrate($libtva[$i]);
  2833. $return.= $nprtva[$i] ? ' *': '';
  2834. $return.= '</option>';
  2835. $this->tva_taux_value[$i] = $txtva[$i];
  2836. $this->tva_taux_libelle[$i] = $libtva[$i];
  2837. $this->tva_taux_npr[$i] = $nprtva[$i];
  2838. }
  2839. $return.= '</select>';
  2840. }
  2841. return $return;
  2842. }
  2843. /**
  2844. * Show a HTML widget to input a date or combo list for day, month, years and optionnaly hours and minutes
  2845. * Fields are preselected with :
  2846. * - set_time date (Local PHP server timestamps or date format YYYY-MM-DD or YYYY-MM-DD HH:MM)
  2847. * - local date of PHP server if set_time is ''
  2848. * - Empty (fields empty) if set_time is -1 (in this case, parameter empty must also have value 1)
  2849. *
  2850. * @param set_time Pre-selected date (must be a local PHP server timestamp)
  2851. * @param prefix Prefix for fields name
  2852. * @param h 1=Show also hours
  2853. * @param m 1=Show also minutes
  2854. * @param empty 0=Fields required, 1=Empty input is allowed
  2855. * @param form_name Form name. Used by popup dates.
  2856. * @param d 1=Show days, month, years
  2857. * @param addnowbutton Add a button "Now"
  2858. * @param nooutput Do not output html string but return it
  2859. * @param disabled Disable input fields
  2860. * @param fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  2861. * @return nothing or string if nooutput is 1
  2862. */
  2863. function select_date($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name="", $d=1, $addnowbutton=0, $nooutput=0, $disabled=0, $fullday='')
  2864. {
  2865. global $conf,$langs;
  2866. $retstring='';
  2867. if($prefix=='') $prefix='re';
  2868. if($h == '') $h=0;
  2869. if($m == '') $m=0;
  2870. if($empty == '') $empty=0;
  2871. if (! $set_time && $empty == 0) $set_time = dol_now('tzuser');
  2872. // Analysis of the pre-selection date
  2873. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/',$set_time,$reg))
  2874. {
  2875. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  2876. $syear = $reg[1];
  2877. $smonth = $reg[2];
  2878. $sday = $reg[3];
  2879. $shour = $reg[4];
  2880. $smin = $reg[5];
  2881. }
  2882. elseif (strval($set_time) != '' && $set_time != -1)
  2883. {
  2884. // set_time est un timestamps (0 possible)
  2885. $syear = dol_print_date($set_time, "%Y");
  2886. $smonth = dol_print_date($set_time, "%m");
  2887. $sday = dol_print_date($set_time, "%d");
  2888. $shour = dol_print_date($set_time, "%H");
  2889. $smin = dol_print_date($set_time, "%M");
  2890. }
  2891. else
  2892. {
  2893. // Date est '' ou vaut -1
  2894. $syear = '';
  2895. $smonth = '';
  2896. $sday = '';
  2897. $shour = '';
  2898. $smin = '';
  2899. }
  2900. if ($d)
  2901. {
  2902. // Show date with popup
  2903. if ($conf->use_javascript_ajax && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none"))
  2904. {
  2905. //print "e".$set_time." t ".$conf->format_date_short;
  2906. if (strval($set_time) != '' && $set_time != -1)
  2907. {
  2908. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  2909. $formated_date=dol_print_date($set_time,$langs->trans("FormatDateShort")); // FormatDateShort for dol_print_date/FormatDateShortJava that is same for javascript
  2910. }
  2911. // Calendrier popup version eldy
  2912. if (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == "eldy")
  2913. {
  2914. // Zone de saisie manuelle de la date
  2915. $retstring.='<input id="'.$prefix.'" name="'.$prefix.'" type="text" size="9" maxlength="11" value="'.$formated_date.'"';
  2916. $retstring.=($disabled?' disabled="disabled"':'');
  2917. $retstring.=' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJava").'\'); "'; // FormatDateShort for dol_print_date/FormatDateShortJava that is same for javascript
  2918. $retstring.='>';
  2919. // Icone calendrier
  2920. if (! $disabled)
  2921. {
  2922. $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
  2923. $base=DOL_URL_ROOT.'/core/';
  2924. $retstring.=' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJava").'\',\''.$langs->defaultlang.'\');">'.img_object($langs->trans("SelectDate"),'calendarday').'</button>';
  2925. }
  2926. $retstring.='<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  2927. $retstring.='<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  2928. $retstring.='<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  2929. }
  2930. else
  2931. {
  2932. print "Bad value of calendar";
  2933. }
  2934. }
  2935. // Show date with combo selects
  2936. if (empty($conf->use_javascript_ajax) || $conf->global->MAIN_POPUP_CALENDAR == "none")
  2937. {
  2938. // Day
  2939. $retstring.='<select'.($disabled?' disabled="disabled"':'').' class="flat" name="'.$prefix.'day">';
  2940. if ($empty || $set_time == -1)
  2941. {
  2942. $retstring.='<option value="0" selected="selected">&nbsp;</option>';
  2943. }
  2944. for ($day = 1 ; $day <= 31; $day++)
  2945. {
  2946. if ($day == $sday)
  2947. {
  2948. $retstring.="<option value=\"$day\" selected=\"selected\">$day";
  2949. }
  2950. else
  2951. {
  2952. $retstring.="<option value=\"$day\">$day";
  2953. }
  2954. $retstring.="</option>";
  2955. }
  2956. $retstring.="</select>";
  2957. $retstring.='<select'.($disabled?' disabled="disabled"':'').' class="flat" name="'.$prefix.'month">';
  2958. if ($empty || $set_time == -1)
  2959. {
  2960. $retstring.='<option value="0" selected="selected">&nbsp;</option>';
  2961. }
  2962. // Month
  2963. for ($month = 1 ; $month <= 12 ; $month++)
  2964. {
  2965. $retstring.='<option value="'.$month.'"'.($month == $smonth?' selected="selected"':'').'>';
  2966. $retstring.=dol_print_date(mktime(12,0,0,$month,1,2000),"%b");
  2967. $retstring.="</option>";
  2968. }
  2969. $retstring.="</select>";
  2970. // Year
  2971. if ($empty || $set_time == -1)
  2972. {
  2973. $retstring.='<input'.($disabled?' disabled="disabled"':'').' class="flat" type="text" size="3" maxlength="4" name="'.$prefix.'year" value="'.$syear.'">';
  2974. }
  2975. else
  2976. {
  2977. $retstring.='<select'.($disabled?' disabled="disabled"':'').' class="flat" name="'.$prefix.'year">';
  2978. for ($year = $syear - 5; $year < $syear + 10 ; $year++)
  2979. {
  2980. if ($year == $syear)
  2981. {
  2982. $retstring.="<option value=\"$year\" selected=\"true\">".$year;
  2983. }
  2984. else
  2985. {
  2986. $retstring.="<option value=\"$year\">".$year;
  2987. }
  2988. $retstring.="</option>";
  2989. }
  2990. $retstring.="</select>\n";
  2991. }
  2992. }
  2993. }
  2994. if ($d && $h) $retstring.='&nbsp;';
  2995. if ($h)
  2996. {
  2997. // Show hour
  2998. $retstring.='<select'.($disabled?' disabled="disabled"':'').' class="flat '.($fullday?$fullday.'hour':'').'" name="'.$prefix.'hour">';
  2999. if ($empty) $retstring.='<option value="-1">&nbsp;</option>';
  3000. for ($hour = 0; $hour < 24; $hour++)
  3001. {
  3002. if (dol_strlen($hour) < 2)
  3003. {
  3004. $hour = "0" . $hour;
  3005. }
  3006. if ($hour == $shour)
  3007. {
  3008. $retstring.="<option value=\"$hour\" selected=\"true\">$hour</option>";
  3009. }
  3010. else
  3011. {
  3012. $retstring.="<option value=\"$hour\">$hour</option>";
  3013. }
  3014. }
  3015. $retstring.="</select>";
  3016. $retstring.="H\n";
  3017. }
  3018. if ($m)
  3019. {
  3020. // Show minutes
  3021. $retstring.='<select'.($disabled?' disabled="disabled"':'').' class="flat '.($fullday?$fullday.'min':'').'" name="'.$prefix.'min">';
  3022. if ($empty) $retstring.='<option value="-1">&nbsp;</option>';
  3023. for ($min = 0; $min < 60 ; $min++)
  3024. {
  3025. if (dol_strlen($min) < 2)
  3026. {
  3027. $min = "0" . $min;
  3028. }
  3029. if ($min == $smin)
  3030. {
  3031. $retstring.="<option value=\"$min\" selected=\"true\">$min</option>";
  3032. }
  3033. else
  3034. {
  3035. $retstring.="<option value=\"$min\">$min</option>";
  3036. }
  3037. }
  3038. $retstring.="</select>";
  3039. $retstring.="M\n";
  3040. }
  3041. // Add a "Now" button
  3042. if ($conf->use_javascript_ajax && $addnowbutton)
  3043. {
  3044. // Script which will be inserted in the OnClick of the "Now" button
  3045. $reset_scripts = "";
  3046. // Generate the date part, depending on the use or not of the javascript calendar
  3047. if (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == "eldy")
  3048. {
  3049. $base=DOL_URL_ROOT.'/core/lib/';
  3050. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJava").'\',\''.$langs->defaultlang.'\');';
  3051. }
  3052. else
  3053. {
  3054. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  3055. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  3056. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  3057. }
  3058. // Generate the hour part
  3059. if ($h)
  3060. {
  3061. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  3062. $reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  3063. if ($fullday) $reset_scripts .= ' } ';
  3064. }
  3065. // Generate the minute part
  3066. if ($m)
  3067. {
  3068. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  3069. $reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  3070. if ($fullday) $reset_scripts .= ' } ';
  3071. }
  3072. // If reset_scripts is not empty, print the button with the reset_scripts in OnClick
  3073. if ($reset_scripts)
  3074. {
  3075. $retstring.='<button class="dpInvisibleButtons" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="Now" onClick="'.$reset_scripts.'">';
  3076. $retstring.=$langs->trans("Now");
  3077. $retstring.='</button> ';
  3078. }
  3079. }
  3080. if (! empty($nooutput)) return $retstring;
  3081. print $retstring;
  3082. return;
  3083. }
  3084. /**
  3085. * Function to show a form to select a duration on a page
  3086. *
  3087. * @param string $prefix prefix
  3088. * @param int $iSecond Default preselected duration (number of seconds)
  3089. * @param int $disabled Disable the combo box
  3090. * @return void
  3091. */
  3092. function select_duration($prefix,$iSecond='',$disabled=0)
  3093. {
  3094. if ($iSecond)
  3095. {
  3096. require_once(DOL_DOCUMENT_ROOT."/core/lib/date.lib.php");
  3097. $hourSelected = ConvertSecondToTime($iSecond,'hour');
  3098. $minSelected = ConvertSecondToTime($iSecond,'min');
  3099. }
  3100. print '<select class="flat" name="'.$prefix.'hour"'.($disabled?' disabled="disabled"':'').'>';
  3101. for ($hour = 0; $hour < 24; $hour++)
  3102. {
  3103. print '<option value="'.$hour.'"';
  3104. if ($hourSelected == $hour)
  3105. {
  3106. print " selected=\"true\"";
  3107. }
  3108. print ">".$hour."</option>";
  3109. }
  3110. print "</select>";
  3111. print "H &nbsp;";
  3112. print '<select class="flat" name="'.$prefix.'min"'.($disabled?' disabled="disabled"':'').'>';
  3113. for ($min = 0; $min <= 55; $min=$min+5)
  3114. {
  3115. print '<option value="'.$min.'"';
  3116. if ($minSelected == $min) print ' selected="selected"';
  3117. print '>'.$min.'</option>';
  3118. }
  3119. print "</select>";
  3120. print "M&nbsp;";
  3121. }
  3122. /**
  3123. * Show a select form from an array
  3124. *
  3125. * @param htmlname Name of html select area
  3126. * @param array Array with key+value
  3127. * @param id Preselected key
  3128. * @param show_empty 1 si il faut ajouter une valeur vide dans la liste, 0 sinon
  3129. * @param key_in_label 1 pour afficher la key dans la valeur "[key] value"
  3130. * @param value_as_key 1 to use value as key
  3131. * @param option Valeur de l'option en fonction du type choisi
  3132. * @param translate Translate and encode value
  3133. * @param maxlen Length maximum for labels
  3134. * @param disabled Html select box is disabled
  3135. * @return string HTML select string
  3136. */
  3137. function selectarray($htmlname, $array, $id='', $show_empty=0, $key_in_label=0, $value_as_key=0, $option='', $translate=0, $maxlen=0, $disabled=0)
  3138. {
  3139. global $langs;
  3140. $out='<select id="'.$htmlname.'" '.($disabled?'disabled="disabled" ':'').'class="flat" name="'.$htmlname.'" '.($option != ''?$option:'').'>';
  3141. if ($show_empty)
  3142. {
  3143. $out.='<option value="-1"'.($id==-1?' selected="selected"':'').'>&nbsp;</option>'."\n";
  3144. }
  3145. if (is_array($array))
  3146. {
  3147. foreach($array as $key => $value)
  3148. {
  3149. $out.='<option value="'.($value_as_key?$value:$key).'"';
  3150. // Si il faut pre-selectionner une valeur
  3151. if ($id != '' && ($id == $key || $id == $value))
  3152. {
  3153. $out.=' selected="selected"';
  3154. }
  3155. $out.='>';
  3156. if ($key_in_label)
  3157. {
  3158. $newval=($translate?$langs->trans($value):$value);
  3159. $selectOptionValue = dol_htmlentitiesbr($key.' - '.($maxlen?dol_trunc($newval,$maxlen):$newval));
  3160. $out.=$selectOptionValue;
  3161. }
  3162. else
  3163. {
  3164. $newval=($translate?$langs->trans($value):$value);
  3165. $selectOptionValue = dol_htmlentitiesbr($maxlen?dol_trunc($newval,$maxlen):$newval);
  3166. if ($value == '' || $value == '-') { $selectOptionValue='&nbsp;'; }
  3167. $out.=$selectOptionValue;
  3168. }
  3169. $out.="</option>\n";
  3170. }
  3171. }
  3172. $out.="</select>";
  3173. return $out;
  3174. }
  3175. /**
  3176. * Show a select form from an array
  3177. *
  3178. * @deprecated Use selectarray instead
  3179. * @return void
  3180. */
  3181. function select_array($htmlname, $array, $id='', $show_empty=0, $key_in_label=0, $value_as_key=0, $option='', $translate=0, $maxlen=0)
  3182. {
  3183. print $this->selectarray($htmlname, $array, $id, $show_empty, $key_in_label, $value_as_key, $option, $translate, $maxlen);
  3184. }
  3185. /**
  3186. * Return an html string with a select combo box to choose yes or no
  3187. *
  3188. * @param name Name of html select field
  3189. * @param value Pre-selected value
  3190. * @param option 0 return yes/no, 1 return 1/0
  3191. * @return int or string See option
  3192. */
  3193. function selectyesno($htmlname,$value='',$option=0)
  3194. {
  3195. global $langs;
  3196. $yes="yes"; $no="no";
  3197. if ($option)
  3198. {
  3199. $yes="1";
  3200. $no="0";
  3201. }
  3202. $resultyesno = '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">'."\n";
  3203. if (("$value" == 'yes') || ($value == 1))
  3204. {
  3205. $resultyesno .= '<option value="'.$yes.'" selected="selected">'.$langs->trans("Yes").'</option>'."\n";
  3206. $resultyesno .= '<option value="'.$no.'">'.$langs->trans("No").'</option>'."\n";
  3207. }
  3208. else
  3209. {
  3210. $resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
  3211. $resultyesno .= '<option value="'.$no.'" selected="selected">'.$langs->trans("No").'</option>'."\n";
  3212. }
  3213. $resultyesno .= '</select>'."\n";
  3214. return $resultyesno;
  3215. }
  3216. /**
  3217. * Return list of export templates
  3218. *
  3219. * @param selected Id modele pre-selectionne
  3220. * @param htmlname Nom de la zone select
  3221. * @param type Type des modeles recherches
  3222. * @param useempty Affiche valeur vide dans liste
  3223. * @return void
  3224. */
  3225. function select_export_model($selected='',$htmlname='exportmodelid',$type='',$useempty=0)
  3226. {
  3227. $sql = "SELECT rowid, label";
  3228. $sql.= " FROM ".MAIN_DB_PREFIX."export_model";
  3229. $sql.= " WHERE type = '".$type."'";
  3230. $sql.= " ORDER BY rowid";
  3231. $result = $this->db->query($sql);
  3232. if ($result)
  3233. {
  3234. print '<select class="flat" name="'.$htmlname.'">';
  3235. if ($useempty)
  3236. {
  3237. print '<option value="-1">&nbsp;</option>';
  3238. }
  3239. $num = $this->db->num_rows($result);
  3240. $i = 0;
  3241. while ($i < $num)
  3242. {
  3243. $obj = $this->db->fetch_object($result);
  3244. if ($selected == $obj->rowid)
  3245. {
  3246. print '<option value="'.$obj->rowid.'" selected="selected">';
  3247. }
  3248. else
  3249. {
  3250. print '<option value="'.$obj->rowid.'">';
  3251. }
  3252. print $obj->label;
  3253. print '</option>';
  3254. $i++;
  3255. }
  3256. print "</select>";
  3257. }
  3258. else {
  3259. dol_print_error($this->db);
  3260. }
  3261. }
  3262. /**
  3263. * Return a HTML area with the reference of object and a navigation bar for a business object
  3264. * To add a particular filter on select, you must set $object->next_prev_filter to SQL criteria.
  3265. *
  3266. * @param object Object to show
  3267. * @param paramid Name of parameter to use to name the id into the URL link
  3268. * @param morehtml More html content to output just before the nav bar
  3269. * @param shownav Show Condition (navigation is shown if value is 1)
  3270. * @param fieldid Nom du champ en base a utiliser pour select next et previous
  3271. * @param fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  3272. * @param morehtmlref Code html supplementaire a afficher apres ref
  3273. * @param moreparam More param to add in nav link url.
  3274. * @return string Portion HTML avec ref + boutons nav
  3275. */
  3276. function showrefnav($object,$paramid,$morehtml='',$shownav=1,$fieldid='rowid',$fieldref='ref',$morehtmlref='',$moreparam='')
  3277. {
  3278. $ret='';
  3279. //print "$paramid,$morehtml,$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  3280. $object->load_previous_next_ref((isset($object->next_prev_filter)?$object->next_prev_filter:''),$fieldid);
  3281. $previous_ref = $object->ref_previous?'<a href="'.$_SERVER["PHP_SELF"].'?'.$paramid.'='.urlencode($object->ref_previous).$moreparam.'">'.img_previous().'</a>':'';
  3282. $next_ref = $object->ref_next?'<a href="'.$_SERVER["PHP_SELF"].'?'.$paramid.'='.urlencode($object->ref_next).$moreparam.'">'.img_next().'</a>':'';
  3283. //print "xx".$previous_ref."x".$next_ref;
  3284. if ($previous_ref || $next_ref || $morehtml) {
  3285. $ret.='<table class="nobordernopadding" width="100%"><tr class="nobordernopadding"><td class="nobordernopadding">';
  3286. }
  3287. $ret.=$object->$fieldref;
  3288. if ($morehtmlref) {
  3289. $ret.=' '.$morehtmlref;
  3290. }
  3291. if ($morehtml) {
  3292. $ret.='</td><td class="nobordernopadding" align="right">'.$morehtml;
  3293. }
  3294. if ($shownav && ($previous_ref || $next_ref)) {
  3295. $ret.='</td><td class="nobordernopadding" align="center" width="20">'.$previous_ref.'</td>';
  3296. $ret.='<td class="nobordernopadding" align="center" width="20">'.$next_ref;
  3297. }
  3298. if ($previous_ref || $next_ref || $morehtml)
  3299. {
  3300. $ret.='</td></tr></table>';
  3301. }
  3302. return $ret;
  3303. }
  3304. /**
  3305. * Return HTML code to output a photo
  3306. *
  3307. * @param modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  3308. * @param object Object containing data to retrieve file name
  3309. * @param width Width of photo
  3310. * @return string HTML code to output photo
  3311. */
  3312. function showphoto($modulepart,$object,$width=100)
  3313. {
  3314. global $conf;
  3315. $ret='';$dir='';$file='';$altfile='';$email='';
  3316. if ($modulepart=='societe')
  3317. {
  3318. $dir=$conf->societe->dir_output;
  3319. $smallfile=$object->logo;
  3320. $smallfile=preg_replace('/(\.png|\.gif|\.jpg|\.jpeg|\.bmp)/i','_small\\1',$smallfile);
  3321. if ($object->logo) $file=$object->id.'/logos/thumbs/'.$smallfile;
  3322. }
  3323. else if ($modulepart=='userphoto')
  3324. {
  3325. $dir=$conf->user->dir_output;
  3326. if ($object->photo) $file=get_exdir($object->id,2).$object->photo;
  3327. if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg"; // For backward compatibility
  3328. $email=$object->email;
  3329. }
  3330. else if ($modulepart=='memberphoto')
  3331. {
  3332. $dir=$conf->adherent->dir_output;
  3333. if ($object->photo) $file=get_exdir($object->id,2).'photos/'.$object->photo;
  3334. if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg"; // For backward compatibility
  3335. $email=$object->email;
  3336. }
  3337. if ($dir)
  3338. {
  3339. $cache='0';
  3340. if ($file && file_exists($dir."/".$file))
  3341. {
  3342. // TODO Link to large image
  3343. $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&file='.urlencode($file).'&cache='.$cache.'">';
  3344. $ret.='<img alt="Photo" id="photologo'.(preg_replace('/[^a-z]/i','_',$file)).'" class="photologo" border="0" width="'.$width.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&file='.urlencode($file).'&cache='.$cache.'">';
  3345. $ret.='</a>';
  3346. }
  3347. else if ($altfile && file_exists($dir."/".$altfile))
  3348. {
  3349. $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&file='.urlencode($file).'&cache='.$cache.'">';
  3350. $ret.='<img alt="Photo alt" id="photologo'.(preg_replace('/[^a-z]/i','_',$file)).'" class="photologo" border="0" width="'.$width.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&file='.urlencode($altfile).'&cache='.$cache.'">';
  3351. $ret.='</a>';
  3352. }
  3353. else
  3354. {
  3355. if ($conf->gravatar->enabled && $email)
  3356. {
  3357. global $dolibarr_main_url_root;
  3358. $ret.='<!-- Put link to gravatar -->';
  3359. $ret.='<img alt="Photo found on Gravatar" title="Photo Gravatar.com - email '.$email.'" border="0" width="'.$width.'" src="http://www.gravatar.com/avatar/'.dol_hash($email).'?s='.$width.'&d='.urlencode( dol_buildpath('/theme/common/nophoto.jpg',2) ).'">';
  3360. }
  3361. else
  3362. {
  3363. $ret.='<img alt="No photo" border="0" width="'.$width.'" src="'.DOL_URL_ROOT.'/theme/common/nophoto.jpg">';
  3364. }
  3365. }
  3366. }
  3367. else dol_print_error('','Call of showphoto with wrong parameters');
  3368. /* Disabled. lightbox seems to not work. I don't know why.
  3369. $ret.="\n<script type=\"text/javascript\">
  3370. jQuery(function() {
  3371. jQuery('.photologo').lightBox();
  3372. });
  3373. </script>\n";
  3374. $ret.="\n<script type=\"text/javascript\">
  3375. jQuery(function() {
  3376. jQuery('.photologo').lightBox({
  3377. overlayBgColor: '#FFF',
  3378. overlayOpacity: 0.6,
  3379. imageLoading: '".DOL_URL_ROOT."/includes/jquery/plugins/lightbox/images/lightbox-ico-loading.gif',
  3380. imageBtnClose: '".DOL_URL_ROOT."/includes/jquery/plugins/lightbox/images/lightbox-btn-close.gif',
  3381. imageBtnPrev: '".DOL_URL_ROOT."/includes/jquery/plugins/lightbox/images/lightbox-btn-prev.gif',
  3382. imageBtnNext: '".DOL_URL_ROOT."/includes/jquery/plugins/lightbox/images/lightbox-btn-next.gif',
  3383. containerResizeSpeed: 350,
  3384. txtImage: 'Imagem',
  3385. txtOf: 'de'
  3386. });
  3387. });
  3388. </script>\n";
  3389. */
  3390. return $ret;
  3391. }
  3392. /**
  3393. * Return select list of groups
  3394. *
  3395. * @param string $selected Id group preselected
  3396. * @param string $htmlname Field name in form
  3397. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  3398. * @param string $exclude Array list of groups id to exclude
  3399. * @param int $disabled If select list must be disabled
  3400. * @param string $include Array list of groups id to include
  3401. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  3402. * @param int $force_entity Possibility to force entity
  3403. * @return void
  3404. */
  3405. function select_dolgroups($selected='',$htmlname='groupid',$show_empty=0,$exclude='',$disabled=0,$include='',$enableonly='',$force_entity='')
  3406. {
  3407. global $conf,$user,$langs;
  3408. // Permettre l'exclusion de groupes
  3409. if (is_array($exclude)) $excludeGroups = implode("','",$exclude);
  3410. // Permettre l'inclusion de groupes
  3411. if (is_array($include)) $includeGroups = implode("','",$include);
  3412. $out='';
  3413. // On recherche les groupes
  3414. $sql = "SELECT ug.rowid, ug.nom ";
  3415. if(! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  3416. {
  3417. $sql.= ", e.label";
  3418. }
  3419. $sql.= " FROM ".MAIN_DB_PREFIX."usergroup as ug ";
  3420. if(! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  3421. {
  3422. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e on e.rowid=ug.entity";
  3423. if ($force_entity) $sql.= " WHERE ug.entity IN (0,".$force_entity.")";
  3424. else $sql.= " WHERE ug.entity IS NOT NULL";
  3425. }
  3426. else
  3427. {
  3428. $sql.= " WHERE ug.entity IN (0,".$conf->entity.")";
  3429. }
  3430. if (is_array($exclude) && $excludeGroups) $sql.= " AND ug.rowid NOT IN ('".$excludeGroups."')";
  3431. if (is_array($include) && $includeGroups) $sql.= " AND ug.rowid IN ('".$includeGroups."')";
  3432. $sql.= " ORDER BY ug.nom ASC";
  3433. dol_syslog("Form::select_dolgroups sql=".$sql);
  3434. $resql=$this->db->query($sql);
  3435. if ($resql)
  3436. {
  3437. $num = $this->db->num_rows($resql);
  3438. $i = 0;
  3439. if ($num)
  3440. {
  3441. $out.= '<select class="flat" name="'.$htmlname.'"'.($disabled?' disabled="disabled"':'').'>';
  3442. if ($show_empty) $out.= '<option value="-1"'.($id==-1?' selected="selected"':'').'>&nbsp;</option>'."\n";
  3443. while ($i < $num)
  3444. {
  3445. $obj = $this->db->fetch_object($resql);
  3446. $disableline=0;
  3447. if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=1;
  3448. $out.= '<option value="'.$obj->rowid.'"';
  3449. if ($disableline) $out.= ' disabled="disabled"';
  3450. if ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && $selected == $obj->rowid))
  3451. {
  3452. $out.= ' selected="selected"';
  3453. }
  3454. $out.= '>';
  3455. $out.= $obj->nom;
  3456. if(! empty($conf->multicompany->enabled) && empty($conf->multicompany->transverse_mode) && $conf->entity == 1)
  3457. {
  3458. $out.= " (".$obj->label.")";
  3459. }
  3460. $out.= '</option>';
  3461. $i++;
  3462. }
  3463. }
  3464. else
  3465. {
  3466. $out.= '<select class="flat" name="'.$htmlname.'" disabled="disabled">';
  3467. $out.= '<option value="">'.$langs->trans("None").'</option>';
  3468. }
  3469. $out.= '</select>';
  3470. }
  3471. else
  3472. {
  3473. dol_print_error($this->db);
  3474. }
  3475. return $out;
  3476. }
  3477. }
  3478. ?>